babylon.no-module.max.js 5.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972
  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. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  450. var preparedSourceCode = this._processPrecision(sourceCode);
  451. if (this._engine.webGLVersion == 1) {
  452. callback(preparedSourceCode);
  453. return;
  454. }
  455. // Already converted
  456. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  457. callback(preparedSourceCode.replace("#version 300 es", ""));
  458. return;
  459. }
  460. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  461. // Remove extensions
  462. // #extension GL_OES_standard_derivatives : enable
  463. // #extension GL_EXT_shader_texture_lod : enable
  464. // #extension GL_EXT_frag_depth : enable
  465. // #extension GL_EXT_draw_buffers : require
  466. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  467. var result = preparedSourceCode.replace(regex, "");
  468. // Migrate to GLSL v300
  469. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  470. result = result.replace(/attribute[ \t]/g, "in ");
  471. result = result.replace(/[ \t]attribute/g, " in");
  472. if (isFragment) {
  473. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  474. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/texture2D\s*\(/g, "texture(");
  476. result = result.replace(/textureCube\s*\(/g, "texture(");
  477. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  478. result = result.replace(/gl_FragColor/g, "glFragColor");
  479. result = result.replace(/gl_FragData/g, "glFragData");
  480. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  481. }
  482. callback(result);
  483. };
  484. Effect.prototype._processIncludes = function (sourceCode, callback) {
  485. var _this = this;
  486. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  487. var match = regex.exec(sourceCode);
  488. var returnValue = new String(sourceCode);
  489. while (match != null) {
  490. var includeFile = match[1];
  491. // Uniform declaration
  492. if (includeFile.indexOf("__decl__") !== -1) {
  493. includeFile = includeFile.replace(/__decl__/, "");
  494. if (this._engine.supportsUniformBuffers) {
  495. includeFile = includeFile.replace(/Vertex/, "Ubo");
  496. includeFile = includeFile.replace(/Fragment/, "Ubo");
  497. }
  498. includeFile = includeFile + "Declaration";
  499. }
  500. if (Effect.IncludesShadersStore[includeFile]) {
  501. // Substitution
  502. var includeContent = Effect.IncludesShadersStore[includeFile];
  503. if (match[2]) {
  504. var splits = match[3].split(",");
  505. for (var index = 0; index < splits.length; index += 2) {
  506. var source = new RegExp(splits[index], "g");
  507. var dest = splits[index + 1];
  508. includeContent = includeContent.replace(source, dest);
  509. }
  510. }
  511. if (match[4]) {
  512. var indexString = match[5];
  513. if (indexString.indexOf("..") !== -1) {
  514. var indexSplits = indexString.split("..");
  515. var minIndex = parseInt(indexSplits[0]);
  516. var maxIndex = parseInt(indexSplits[1]);
  517. var sourceIncludeContent = includeContent.slice(0);
  518. includeContent = "";
  519. if (isNaN(maxIndex)) {
  520. maxIndex = this._indexParameters[indexSplits[1]];
  521. }
  522. for (var i = minIndex; i < maxIndex; i++) {
  523. if (!this._engine.supportsUniformBuffers) {
  524. // Ubo replacement
  525. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  526. return p1 + "{X}";
  527. });
  528. }
  529. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  530. }
  531. }
  532. else {
  533. if (!this._engine.supportsUniformBuffers) {
  534. // Ubo replacement
  535. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  536. return p1 + "{X}";
  537. });
  538. }
  539. includeContent = includeContent.replace(/\{X\}/g, indexString);
  540. }
  541. }
  542. // Replace
  543. returnValue = returnValue.replace(match[0], includeContent);
  544. }
  545. else {
  546. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  547. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  548. Effect.IncludesShadersStore[includeFile] = fileContent;
  549. _this._processIncludes(returnValue, callback);
  550. });
  551. return;
  552. }
  553. match = regex.exec(sourceCode);
  554. }
  555. callback(returnValue);
  556. };
  557. Effect.prototype._processPrecision = function (source) {
  558. if (source.indexOf("precision highp float") === -1) {
  559. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  560. source = "precision mediump float;\n" + source;
  561. }
  562. else {
  563. source = "precision highp float;\n" + source;
  564. }
  565. }
  566. else {
  567. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  568. source = source.replace("precision highp float", "precision mediump float");
  569. }
  570. }
  571. return source;
  572. };
  573. /**
  574. * Recompiles the webGL program
  575. * @param vertexSourceCode The source code for the vertex shader.
  576. * @param fragmentSourceCode The source code for the fragment shader.
  577. * @param onCompiled Callback called when completed.
  578. * @param onError Callback called on error.
  579. * @hidden
  580. */
  581. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  582. var _this = this;
  583. this._isReady = false;
  584. this._vertexSourceCodeOverride = vertexSourceCode;
  585. this._fragmentSourceCodeOverride = fragmentSourceCode;
  586. this.onError = function (effect, error) {
  587. if (onError) {
  588. onError(error);
  589. }
  590. };
  591. this.onCompiled = function () {
  592. var scenes = _this.getEngine().scenes;
  593. for (var i = 0; i < scenes.length; i++) {
  594. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  595. }
  596. if (onCompiled) {
  597. onCompiled(_this._program);
  598. }
  599. };
  600. this._fallbacks = null;
  601. this._prepareEffect();
  602. };
  603. /**
  604. * Gets the uniform locations of the the specified variable names
  605. * @param names THe names of the variables to lookup.
  606. * @returns Array of locations in the same order as variable names.
  607. */
  608. Effect.prototype.getSpecificUniformLocations = function (names) {
  609. var engine = this._engine;
  610. return engine.getUniforms(this._program, names);
  611. };
  612. /**
  613. * Prepares the effect
  614. * @hidden
  615. */
  616. Effect.prototype._prepareEffect = function () {
  617. var attributesNames = this._attributesNames;
  618. var defines = this.defines;
  619. var fallbacks = this._fallbacks;
  620. this._valueCache = {};
  621. var previousProgram = this._program;
  622. try {
  623. var engine = this._engine;
  624. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  625. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  626. }
  627. else {
  628. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  629. }
  630. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  631. if (engine.supportsUniformBuffers) {
  632. for (var name in this._uniformBuffersNames) {
  633. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  634. }
  635. }
  636. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  637. this._attributes = engine.getAttributes(this._program, attributesNames);
  638. var index;
  639. for (index = 0; index < this._samplers.length; index++) {
  640. var sampler = this.getUniform(this._samplers[index]);
  641. if (sampler == null) {
  642. this._samplers.splice(index, 1);
  643. index--;
  644. }
  645. }
  646. engine.bindSamplers(this);
  647. this._compilationError = "";
  648. this._isReady = true;
  649. if (this.onCompiled) {
  650. this.onCompiled(this);
  651. }
  652. this.onCompileObservable.notifyObservers(this);
  653. this.onCompileObservable.clear();
  654. // Unbind mesh reference in fallbacks
  655. if (this._fallbacks) {
  656. this._fallbacks.unBindMesh();
  657. }
  658. if (previousProgram) {
  659. this.getEngine()._deleteProgram(previousProgram);
  660. }
  661. }
  662. catch (e) {
  663. this._compilationError = e.message;
  664. // Let's go through fallbacks then
  665. BABYLON.Tools.Error("Unable to compile effect:");
  666. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  667. return " " + uniform;
  668. }));
  669. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  670. return " " + attribute;
  671. }));
  672. BABYLON.Tools.Error("Error: " + this._compilationError);
  673. if (previousProgram) {
  674. this._program = previousProgram;
  675. this._isReady = true;
  676. if (this.onError) {
  677. this.onError(this, this._compilationError);
  678. }
  679. this.onErrorObservable.notifyObservers(this);
  680. }
  681. if (fallbacks && fallbacks.isMoreFallbacks) {
  682. BABYLON.Tools.Error("Trying next fallback.");
  683. this.defines = fallbacks.reduce(this.defines, this);
  684. this._prepareEffect();
  685. }
  686. else { // Sorry we did everything we can
  687. if (this.onError) {
  688. this.onError(this, this._compilationError);
  689. }
  690. this.onErrorObservable.notifyObservers(this);
  691. this.onErrorObservable.clear();
  692. // Unbind mesh reference in fallbacks
  693. if (this._fallbacks) {
  694. this._fallbacks.unBindMesh();
  695. }
  696. }
  697. }
  698. };
  699. Object.defineProperty(Effect.prototype, "isSupported", {
  700. /**
  701. * Checks if the effect is supported. (Must be called after compilation)
  702. */
  703. get: function () {
  704. return this._compilationError === "";
  705. },
  706. enumerable: true,
  707. configurable: true
  708. });
  709. /**
  710. * Binds a texture to the engine to be used as output of the shader.
  711. * @param channel Name of the output variable.
  712. * @param texture Texture to bind.
  713. * @hidden
  714. */
  715. Effect.prototype._bindTexture = function (channel, texture) {
  716. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  717. };
  718. /**
  719. * Sets a texture on the engine to be used in the shader.
  720. * @param channel Name of the sampler variable.
  721. * @param texture Texture to set.
  722. */
  723. Effect.prototype.setTexture = function (channel, texture) {
  724. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  725. };
  726. /**
  727. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  728. * @param channel Name of the sampler variable.
  729. * @param texture Texture to set.
  730. */
  731. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  732. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  733. };
  734. /**
  735. * Sets an array of textures on the engine to be used in the shader.
  736. * @param channel Name of the variable.
  737. * @param textures Textures to set.
  738. */
  739. Effect.prototype.setTextureArray = function (channel, textures) {
  740. if (this._samplers.indexOf(channel + "Ex") === -1) {
  741. var initialPos = this._samplers.indexOf(channel);
  742. for (var index = 1; index < textures.length; index++) {
  743. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  744. }
  745. }
  746. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  747. };
  748. /**
  749. * 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)
  750. * @param channel Name of the sampler variable.
  751. * @param postProcess Post process to get the input texture from.
  752. */
  753. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  754. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  755. };
  756. /**
  757. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  758. * 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)
  759. * @param channel Name of the sampler variable.
  760. * @param postProcess Post process to get the output texture from.
  761. */
  762. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  763. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  764. };
  765. /** @hidden */
  766. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  767. var cache = this._valueCache[uniformName];
  768. var flag = matrix.updateFlag;
  769. if (cache !== undefined && cache === flag) {
  770. return false;
  771. }
  772. this._valueCache[uniformName] = flag;
  773. return true;
  774. };
  775. /** @hidden */
  776. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  777. var cache = this._valueCache[uniformName];
  778. if (!cache) {
  779. cache = [x, y];
  780. this._valueCache[uniformName] = cache;
  781. return true;
  782. }
  783. var changed = false;
  784. if (cache[0] !== x) {
  785. cache[0] = x;
  786. changed = true;
  787. }
  788. if (cache[1] !== y) {
  789. cache[1] = y;
  790. changed = true;
  791. }
  792. return changed;
  793. };
  794. /** @hidden */
  795. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  796. var cache = this._valueCache[uniformName];
  797. if (!cache) {
  798. cache = [x, y, z];
  799. this._valueCache[uniformName] = cache;
  800. return true;
  801. }
  802. var changed = false;
  803. if (cache[0] !== x) {
  804. cache[0] = x;
  805. changed = true;
  806. }
  807. if (cache[1] !== y) {
  808. cache[1] = y;
  809. changed = true;
  810. }
  811. if (cache[2] !== z) {
  812. cache[2] = z;
  813. changed = true;
  814. }
  815. return changed;
  816. };
  817. /** @hidden */
  818. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  819. var cache = this._valueCache[uniformName];
  820. if (!cache) {
  821. cache = [x, y, z, w];
  822. this._valueCache[uniformName] = cache;
  823. return true;
  824. }
  825. var changed = false;
  826. if (cache[0] !== x) {
  827. cache[0] = x;
  828. changed = true;
  829. }
  830. if (cache[1] !== y) {
  831. cache[1] = y;
  832. changed = true;
  833. }
  834. if (cache[2] !== z) {
  835. cache[2] = z;
  836. changed = true;
  837. }
  838. if (cache[3] !== w) {
  839. cache[3] = w;
  840. changed = true;
  841. }
  842. return changed;
  843. };
  844. /**
  845. * Binds a buffer to a uniform.
  846. * @param buffer Buffer to bind.
  847. * @param name Name of the uniform variable to bind to.
  848. */
  849. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  850. var bufferName = this._uniformBuffersNames[name];
  851. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  852. return;
  853. }
  854. Effect._baseCache[bufferName] = buffer;
  855. this._engine.bindUniformBufferBase(buffer, bufferName);
  856. };
  857. /**
  858. * Binds block to a uniform.
  859. * @param blockName Name of the block to bind.
  860. * @param index Index to bind.
  861. */
  862. Effect.prototype.bindUniformBlock = function (blockName, index) {
  863. this._engine.bindUniformBlock(this._program, blockName, index);
  864. };
  865. /**
  866. * Sets an interger value on a uniform variable.
  867. * @param uniformName Name of the variable.
  868. * @param value Value to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setInt = function (uniformName, value) {
  872. var cache = this._valueCache[uniformName];
  873. if (cache !== undefined && cache === value) {
  874. return this;
  875. }
  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. }
  1071. this._valueCache[uniformName] = value;
  1072. this._engine.setFloat(this.getUniform(uniformName), value);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a boolean on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param bool value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setBool = function (uniformName, bool) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === bool) {
  1084. return this;
  1085. }
  1086. this._valueCache[uniformName] = bool;
  1087. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1088. return this;
  1089. };
  1090. /**
  1091. * Sets a Vector2 on a uniform variable.
  1092. * @param uniformName Name of the variable.
  1093. * @param vector2 vector2 to be set.
  1094. * @returns this effect.
  1095. */
  1096. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1097. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1098. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1099. }
  1100. return this;
  1101. };
  1102. /**
  1103. * Sets a float2 on a uniform variable.
  1104. * @param uniformName Name of the variable.
  1105. * @param x First float in float2.
  1106. * @param y Second float in float2.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1110. if (this._cacheFloat2(uniformName, x, y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector3 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector3 Value to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1122. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float3 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float3.
  1131. * @param y Second float in float3.
  1132. * @param z Third float in float3.
  1133. * @returns this effect.
  1134. */
  1135. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1136. if (this._cacheFloat3(uniformName, x, y, z)) {
  1137. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1138. }
  1139. return this;
  1140. };
  1141. /**
  1142. * Sets a Vector4 on a uniform variable.
  1143. * @param uniformName Name of the variable.
  1144. * @param vector4 Value to be set.
  1145. * @returns this effect.
  1146. */
  1147. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1148. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1149. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1150. }
  1151. return this;
  1152. };
  1153. /**
  1154. * Sets a float4 on a uniform variable.
  1155. * @param uniformName Name of the variable.
  1156. * @param x First float in float4.
  1157. * @param y Second float in float4.
  1158. * @param z Third float in float4.
  1159. * @param w Fourth float in float4.
  1160. * @returns this effect.
  1161. */
  1162. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1163. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1164. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1165. }
  1166. return this;
  1167. };
  1168. /**
  1169. * Sets a Color3 on a uniform variable.
  1170. * @param uniformName Name of the variable.
  1171. * @param color3 Value to be set.
  1172. * @returns this effect.
  1173. */
  1174. Effect.prototype.setColor3 = function (uniformName, color3) {
  1175. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1176. this._engine.setColor3(this.getUniform(uniformName), color3);
  1177. }
  1178. return this;
  1179. };
  1180. /**
  1181. * Sets a Color4 on a uniform variable.
  1182. * @param uniformName Name of the variable.
  1183. * @param color3 Value to be set.
  1184. * @param alpha Alpha value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1188. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1189. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable
  1195. * @param uniformName defines the name of the variable
  1196. * @param color4 defines the value to be set
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1200. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1201. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * This function will add a new shader to the shader store
  1207. * @param name the name of the shader
  1208. * @param pixelShader optional pixel shader content
  1209. * @param vertexShader optional vertex shader content
  1210. */
  1211. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1212. if (pixelShader) {
  1213. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1214. }
  1215. if (vertexShader) {
  1216. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1217. }
  1218. };
  1219. /**
  1220. * Resets the cache of effects.
  1221. */
  1222. Effect.ResetCache = function () {
  1223. Effect._baseCache = {};
  1224. };
  1225. Effect._uniqueIdSeed = 0;
  1226. Effect._baseCache = {};
  1227. /**
  1228. * Store of each shader (The can be looked up using effect.key)
  1229. */
  1230. Effect.ShadersStore = {};
  1231. /**
  1232. * Store of each included file for a shader (The can be looked up using effect.key)
  1233. */
  1234. Effect.IncludesShadersStore = {};
  1235. return Effect;
  1236. }());
  1237. BABYLON.Effect = Effect;
  1238. })(BABYLON || (BABYLON = {}));
  1239. //# sourceMappingURL=babylon.effect.js.map
  1240. //# sourceMappingURL=babylon.types.js.map
  1241. var BABYLON;
  1242. (function (BABYLON) {
  1243. /**
  1244. * Gather the list of keyboard event types as constants.
  1245. */
  1246. var KeyboardEventTypes = /** @class */ (function () {
  1247. function KeyboardEventTypes() {
  1248. }
  1249. /**
  1250. * The keydown event is fired when a key becomes active (pressed).
  1251. */
  1252. KeyboardEventTypes.KEYDOWN = 0x01;
  1253. /**
  1254. * The keyup event is fired when a key has been released.
  1255. */
  1256. KeyboardEventTypes.KEYUP = 0x02;
  1257. return KeyboardEventTypes;
  1258. }());
  1259. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1260. /**
  1261. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1262. */
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. /**
  1265. * Instantiates a new keyboard info.
  1266. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1267. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1268. * @param event Defines the related dom event
  1269. */
  1270. function KeyboardInfo(
  1271. /**
  1272. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1273. */
  1274. type,
  1275. /**
  1276. * Defines the related dom event
  1277. */
  1278. event) {
  1279. this.type = type;
  1280. this.event = event;
  1281. }
  1282. return KeyboardInfo;
  1283. }());
  1284. BABYLON.KeyboardInfo = KeyboardInfo;
  1285. /**
  1286. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1287. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1288. */
  1289. var KeyboardInfoPre = /** @class */ (function (_super) {
  1290. __extends(KeyboardInfoPre, _super);
  1291. /**
  1292. * Instantiates a new keyboard pre info.
  1293. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1294. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1295. * @param event Defines the related dom event
  1296. */
  1297. function KeyboardInfoPre(
  1298. /**
  1299. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1300. */
  1301. type,
  1302. /**
  1303. * Defines the related dom event
  1304. */
  1305. event) {
  1306. var _this = _super.call(this, type, event) || this;
  1307. _this.type = type;
  1308. _this.event = event;
  1309. _this.skipOnPointerObservable = false;
  1310. return _this;
  1311. }
  1312. return KeyboardInfoPre;
  1313. }(KeyboardInfo));
  1314. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1315. })(BABYLON || (BABYLON = {}));
  1316. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1317. var BABYLON;
  1318. (function (BABYLON) {
  1319. /**
  1320. * Gather the list of pointer event types as constants.
  1321. */
  1322. var PointerEventTypes = /** @class */ (function () {
  1323. function PointerEventTypes() {
  1324. }
  1325. /**
  1326. * 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.
  1327. */
  1328. PointerEventTypes.POINTERDOWN = 0x01;
  1329. /**
  1330. * The pointerup event is fired when a pointer is no longer active.
  1331. */
  1332. PointerEventTypes.POINTERUP = 0x02;
  1333. /**
  1334. * The pointermove event is fired when a pointer changes coordinates.
  1335. */
  1336. PointerEventTypes.POINTERMOVE = 0x04;
  1337. /**
  1338. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1339. */
  1340. PointerEventTypes.POINTERWHEEL = 0x08;
  1341. /**
  1342. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1343. */
  1344. PointerEventTypes.POINTERPICK = 0x10;
  1345. /**
  1346. * The pointertap event is fired when a the object has been touched and released without drag.
  1347. */
  1348. PointerEventTypes.POINTERTAP = 0x20;
  1349. /**
  1350. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1351. */
  1352. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1353. return PointerEventTypes;
  1354. }());
  1355. BABYLON.PointerEventTypes = PointerEventTypes;
  1356. /**
  1357. * Base class of pointer info types.
  1358. */
  1359. var PointerInfoBase = /** @class */ (function () {
  1360. /**
  1361. * Instantiates the base class of pointers info.
  1362. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1363. * @param event Defines the related dom event
  1364. */
  1365. function PointerInfoBase(
  1366. /**
  1367. * Defines the type of event (BABYLON.PointerEventTypes)
  1368. */
  1369. type,
  1370. /**
  1371. * Defines the related dom event
  1372. */
  1373. event) {
  1374. this.type = type;
  1375. this.event = event;
  1376. }
  1377. return PointerInfoBase;
  1378. }());
  1379. BABYLON.PointerInfoBase = PointerInfoBase;
  1380. /**
  1381. * This class is used to store pointer related info for the onPrePointerObservable event.
  1382. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1383. */
  1384. var PointerInfoPre = /** @class */ (function (_super) {
  1385. __extends(PointerInfoPre, _super);
  1386. /**
  1387. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1388. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1389. * @param event Defines the related dom event
  1390. * @param localX Defines the local x coordinates of the pointer when the event occured
  1391. * @param localY Defines the local y coordinates of the pointer when the event occured
  1392. */
  1393. function PointerInfoPre(type, event, localX, localY) {
  1394. var _this = _super.call(this, type, event) || this;
  1395. /**
  1396. * Ray from a pointer if availible (eg. 6dof controller)
  1397. */
  1398. _this.ray = null;
  1399. _this.skipOnPointerObservable = false;
  1400. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1401. return _this;
  1402. }
  1403. return PointerInfoPre;
  1404. }(PointerInfoBase));
  1405. BABYLON.PointerInfoPre = PointerInfoPre;
  1406. /**
  1407. * This type contains all the data related to a pointer event in Babylon.js.
  1408. * 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.
  1409. */
  1410. var PointerInfo = /** @class */ (function (_super) {
  1411. __extends(PointerInfo, _super);
  1412. /**
  1413. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1414. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1415. * @param event Defines the related dom event
  1416. * @param pickInfo Defines the picking info associated to the info (if any)\
  1417. */
  1418. function PointerInfo(type, event,
  1419. /**
  1420. * Defines the picking info associated to the info (if any)\
  1421. */
  1422. pickInfo) {
  1423. var _this = _super.call(this, type, event) || this;
  1424. _this.pickInfo = pickInfo;
  1425. return _this;
  1426. }
  1427. return PointerInfo;
  1428. }(PointerInfoBase));
  1429. BABYLON.PointerInfo = PointerInfo;
  1430. })(BABYLON || (BABYLON = {}));
  1431. //# sourceMappingURL=babylon.pointerEvents.js.map
  1432. var BABYLON;
  1433. (function (BABYLON) {
  1434. /**
  1435. * Constant used to convert a value to gamma space
  1436. * @ignorenaming
  1437. */
  1438. BABYLON.ToGammaSpace = 1 / 2.2;
  1439. /**
  1440. * Constant used to convert a value to linear space
  1441. * @ignorenaming
  1442. */
  1443. BABYLON.ToLinearSpace = 2.2;
  1444. /**
  1445. * Constant used to define the minimal number value in Babylon.js
  1446. * @ignorenaming
  1447. */
  1448. BABYLON.Epsilon = 0.001;
  1449. /**
  1450. * Class used to hold a RBG color
  1451. */
  1452. var Color3 = /** @class */ (function () {
  1453. /**
  1454. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1455. * @param r defines the red component (between 0 and 1, default is 0)
  1456. * @param g defines the green component (between 0 and 1, default is 0)
  1457. * @param b defines the blue component (between 0 and 1, default is 0)
  1458. */
  1459. function Color3(
  1460. /**
  1461. * Defines the red component (between 0 and 1, default is 0)
  1462. */
  1463. r,
  1464. /**
  1465. * Defines the green component (between 0 and 1, default is 0)
  1466. */
  1467. g,
  1468. /**
  1469. * Defines the blue component (between 0 and 1, default is 0)
  1470. */
  1471. b) {
  1472. if (r === void 0) { r = 0; }
  1473. if (g === void 0) { g = 0; }
  1474. if (b === void 0) { b = 0; }
  1475. this.r = r;
  1476. this.g = g;
  1477. this.b = b;
  1478. }
  1479. /**
  1480. * Creates a string with the Color3 current values
  1481. * @returns the string representation of the Color3 object
  1482. */
  1483. Color3.prototype.toString = function () {
  1484. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1485. };
  1486. /**
  1487. * Returns the string "Color3"
  1488. * @returns "Color3"
  1489. */
  1490. Color3.prototype.getClassName = function () {
  1491. return "Color3";
  1492. };
  1493. /**
  1494. * Compute the Color3 hash code
  1495. * @returns an unique number that can be used to hash Color3 objects
  1496. */
  1497. Color3.prototype.getHashCode = function () {
  1498. var hash = this.r || 0;
  1499. hash = (hash * 397) ^ (this.g || 0);
  1500. hash = (hash * 397) ^ (this.b || 0);
  1501. return hash;
  1502. };
  1503. // Operators
  1504. /**
  1505. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1506. * @param array defines the array where to store the r,g,b components
  1507. * @param index defines an optional index in the target array to define where to start storing values
  1508. * @returns the current Color3 object
  1509. */
  1510. Color3.prototype.toArray = function (array, index) {
  1511. if (index === undefined) {
  1512. index = 0;
  1513. }
  1514. array[index] = this.r;
  1515. array[index + 1] = this.g;
  1516. array[index + 2] = this.b;
  1517. return this;
  1518. };
  1519. /**
  1520. * Returns a new Color4 object from the current Color3 and the given alpha
  1521. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  1522. * @returns a new Color4 object
  1523. */
  1524. Color3.prototype.toColor4 = function (alpha) {
  1525. if (alpha === void 0) { alpha = 1; }
  1526. return new Color4(this.r, this.g, this.b, alpha);
  1527. };
  1528. /**
  1529. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1530. * @returns the new array
  1531. */
  1532. Color3.prototype.asArray = function () {
  1533. var result = new Array();
  1534. this.toArray(result, 0);
  1535. return result;
  1536. };
  1537. /**
  1538. * Returns the luminance value
  1539. * @returns a float value
  1540. */
  1541. Color3.prototype.toLuminance = function () {
  1542. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1543. };
  1544. /**
  1545. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1546. * @param otherColor defines the second operand
  1547. * @returns the new Color3 object
  1548. */
  1549. Color3.prototype.multiply = function (otherColor) {
  1550. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1551. };
  1552. /**
  1553. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1554. * @param otherColor defines the second operand
  1555. * @param result defines the Color3 object where to store the result
  1556. * @returns the current Color3
  1557. */
  1558. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1559. result.r = this.r * otherColor.r;
  1560. result.g = this.g * otherColor.g;
  1561. result.b = this.b * otherColor.b;
  1562. return this;
  1563. };
  1564. /**
  1565. * Determines equality between Color3 objects
  1566. * @param otherColor defines the second operand
  1567. * @returns true if the rgb values are equal to the given ones
  1568. */
  1569. Color3.prototype.equals = function (otherColor) {
  1570. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1571. };
  1572. /**
  1573. * Determines equality between the current Color3 object and a set of r,b,g values
  1574. * @param r defines the red component to check
  1575. * @param g defines the green component to check
  1576. * @param b defines the blue component to check
  1577. * @returns true if the rgb values are equal to the given ones
  1578. */
  1579. Color3.prototype.equalsFloats = function (r, g, b) {
  1580. return this.r === r && this.g === g && this.b === b;
  1581. };
  1582. /**
  1583. * Multiplies in place each rgb value by scale
  1584. * @param scale defines the scaling factor
  1585. * @returns the updated Color3
  1586. */
  1587. Color3.prototype.scale = function (scale) {
  1588. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1589. };
  1590. /**
  1591. * Multiplies the rgb values by scale and stores the result into "result"
  1592. * @param scale defines the scaling factor
  1593. * @param result defines the Color3 object where to store the result
  1594. * @returns the unmodified current Color3
  1595. */
  1596. Color3.prototype.scaleToRef = function (scale, result) {
  1597. result.r = this.r * scale;
  1598. result.g = this.g * scale;
  1599. result.b = this.b * scale;
  1600. return this;
  1601. };
  1602. /**
  1603. * Scale the current Color3 values by a factor and add the result to a given Color3
  1604. * @param scale defines the scale factor
  1605. * @param result defines color to store the result into
  1606. * @returns the unmodified current Color3
  1607. */
  1608. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1609. result.r += this.r * scale;
  1610. result.g += this.g * scale;
  1611. result.b += this.b * scale;
  1612. return this;
  1613. };
  1614. /**
  1615. * Clamps the rgb values by the min and max values and stores the result into "result"
  1616. * @param min defines minimum clamping value (default is 0)
  1617. * @param max defines maximum clamping value (default is 1)
  1618. * @param result defines color to store the result into
  1619. * @returns the original Color3
  1620. */
  1621. Color3.prototype.clampToRef = function (min, max, result) {
  1622. if (min === void 0) { min = 0; }
  1623. if (max === void 0) { max = 1; }
  1624. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1625. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1626. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1627. return this;
  1628. };
  1629. /**
  1630. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1631. * @param otherColor defines the second operand
  1632. * @returns the new Color3
  1633. */
  1634. Color3.prototype.add = function (otherColor) {
  1635. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1636. };
  1637. /**
  1638. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1639. * @param otherColor defines the second operand
  1640. * @param result defines Color3 object to store the result into
  1641. * @returns the unmodified current Color3
  1642. */
  1643. Color3.prototype.addToRef = function (otherColor, result) {
  1644. result.r = this.r + otherColor.r;
  1645. result.g = this.g + otherColor.g;
  1646. result.b = this.b + otherColor.b;
  1647. return this;
  1648. };
  1649. /**
  1650. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1651. * @param otherColor defines the second operand
  1652. * @returns the new Color3
  1653. */
  1654. Color3.prototype.subtract = function (otherColor) {
  1655. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1656. };
  1657. /**
  1658. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1659. * @param otherColor defines the second operand
  1660. * @param result defines Color3 object to store the result into
  1661. * @returns the unmodified current Color3
  1662. */
  1663. Color3.prototype.subtractToRef = function (otherColor, result) {
  1664. result.r = this.r - otherColor.r;
  1665. result.g = this.g - otherColor.g;
  1666. result.b = this.b - otherColor.b;
  1667. return this;
  1668. };
  1669. /**
  1670. * Copy the current object
  1671. * @returns a new Color3 copied the current one
  1672. */
  1673. Color3.prototype.clone = function () {
  1674. return new Color3(this.r, this.g, this.b);
  1675. };
  1676. /**
  1677. * Copies the rgb values from the source in the current Color3
  1678. * @param source defines the source Color3 object
  1679. * @returns the updated Color3 object
  1680. */
  1681. Color3.prototype.copyFrom = function (source) {
  1682. this.r = source.r;
  1683. this.g = source.g;
  1684. this.b = source.b;
  1685. return this;
  1686. };
  1687. /**
  1688. * Updates the Color3 rgb values from the given floats
  1689. * @param r defines the red component to read from
  1690. * @param g defines the green component to read from
  1691. * @param b defines the blue component to read from
  1692. * @returns the current Color3 object
  1693. */
  1694. Color3.prototype.copyFromFloats = function (r, g, b) {
  1695. this.r = r;
  1696. this.g = g;
  1697. this.b = b;
  1698. return this;
  1699. };
  1700. /**
  1701. * Updates the Color3 rgb values from the given floats
  1702. * @param r defines the red component to read from
  1703. * @param g defines the green component to read from
  1704. * @param b defines the blue component to read from
  1705. * @returns the current Color3 object
  1706. */
  1707. Color3.prototype.set = function (r, g, b) {
  1708. return this.copyFromFloats(r, g, b);
  1709. };
  1710. /**
  1711. * Compute the Color3 hexadecimal code as a string
  1712. * @returns a string containing the hexadecimal representation of the Color3 object
  1713. */
  1714. Color3.prototype.toHexString = function () {
  1715. var intR = (this.r * 255) | 0;
  1716. var intG = (this.g * 255) | 0;
  1717. var intB = (this.b * 255) | 0;
  1718. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1719. };
  1720. /**
  1721. * Computes a new Color3 converted from the current one to linear space
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.prototype.toLinearSpace = function () {
  1725. var convertedColor = new Color3();
  1726. this.toLinearSpaceToRef(convertedColor);
  1727. return convertedColor;
  1728. };
  1729. /**
  1730. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1731. * @param convertedColor defines the Color3 object where to store the linear space version
  1732. * @returns the unmodified Color3
  1733. */
  1734. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1735. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1736. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1737. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1738. return this;
  1739. };
  1740. /**
  1741. * Computes a new Color3 converted from the current one to gamma space
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.prototype.toGammaSpace = function () {
  1745. var convertedColor = new Color3();
  1746. this.toGammaSpaceToRef(convertedColor);
  1747. return convertedColor;
  1748. };
  1749. /**
  1750. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1751. * @param convertedColor defines the Color3 object where to store the gamma space version
  1752. * @returns the unmodified Color3
  1753. */
  1754. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1755. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1756. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1757. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1758. return this;
  1759. };
  1760. // Statics
  1761. /**
  1762. * Creates a new Color3 from the string containing valid hexadecimal values
  1763. * @param hex defines a string containing valid hexadecimal values
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.FromHexString = function (hex) {
  1767. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1768. return new Color3(0, 0, 0);
  1769. }
  1770. var r = parseInt(hex.substring(1, 3), 16);
  1771. var g = parseInt(hex.substring(3, 5), 16);
  1772. var b = parseInt(hex.substring(5, 7), 16);
  1773. return Color3.FromInts(r, g, b);
  1774. };
  1775. /**
  1776. * Creates a new Vector3 from the starting index of the given array
  1777. * @param array defines the source array
  1778. * @param offset defines an offset in the source array
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.FromArray = function (array, offset) {
  1782. if (offset === void 0) { offset = 0; }
  1783. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1784. };
  1785. /**
  1786. * Creates a new Color3 from integer values (< 256)
  1787. * @param r defines the red component to read from (value between 0 and 255)
  1788. * @param g defines the green component to read from (value between 0 and 255)
  1789. * @param b defines the blue component to read from (value between 0 and 255)
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.FromInts = function (r, g, b) {
  1793. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1794. };
  1795. /**
  1796. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1797. * @param start defines the start Color3 value
  1798. * @param end defines the end Color3 value
  1799. * @param amount defines the gradient value between start and end
  1800. * @returns a new Color3 object
  1801. */
  1802. Color3.Lerp = function (start, end, amount) {
  1803. var result = new Color3(0.0, 0.0, 0.0);
  1804. Color3.LerpToRef(start, end, amount, result);
  1805. return result;
  1806. };
  1807. /**
  1808. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1809. * @param left defines the start value
  1810. * @param right defines the end value
  1811. * @param amount defines the gradient factor
  1812. * @param result defines the Color3 object where to store the result
  1813. */
  1814. Color3.LerpToRef = function (left, right, amount, result) {
  1815. result.r = left.r + ((right.r - left.r) * amount);
  1816. result.g = left.g + ((right.g - left.g) * amount);
  1817. result.b = left.b + ((right.b - left.b) * amount);
  1818. };
  1819. /**
  1820. * Returns a Color3 value containing a red color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.Red = function () { return new Color3(1, 0, 0); };
  1824. /**
  1825. * Returns a Color3 value containing a green color
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Green = function () { return new Color3(0, 1, 0); };
  1829. /**
  1830. * Returns a Color3 value containing a blue color
  1831. * @returns a new Color3 object
  1832. */
  1833. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1834. /**
  1835. * Returns a Color3 value containing a black color
  1836. * @returns a new Color3 object
  1837. */
  1838. Color3.Black = function () { return new Color3(0, 0, 0); };
  1839. /**
  1840. * Returns a Color3 value containing a white color
  1841. * @returns a new Color3 object
  1842. */
  1843. Color3.White = function () { return new Color3(1, 1, 1); };
  1844. /**
  1845. * Returns a Color3 value containing a purple color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1849. /**
  1850. * Returns a Color3 value containing a magenta color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1854. /**
  1855. * Returns a Color3 value containing a yellow color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1859. /**
  1860. * Returns a Color3 value containing a gray color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1864. /**
  1865. * Returns a Color3 value containing a teal color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1869. /**
  1870. * Returns a Color3 value containing a random color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1874. return Color3;
  1875. }());
  1876. BABYLON.Color3 = Color3;
  1877. /**
  1878. * Class used to hold a RBGA color
  1879. */
  1880. var Color4 = /** @class */ (function () {
  1881. /**
  1882. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1883. * @param r defines the red component (between 0 and 1, default is 0)
  1884. * @param g defines the green component (between 0 and 1, default is 0)
  1885. * @param b defines the blue component (between 0 and 1, default is 0)
  1886. * @param a defines the alpha component (between 0 and 1, default is 1)
  1887. */
  1888. function Color4(
  1889. /**
  1890. * Defines the red component (between 0 and 1, default is 0)
  1891. */
  1892. r,
  1893. /**
  1894. * Defines the green component (between 0 and 1, default is 0)
  1895. */
  1896. g,
  1897. /**
  1898. * Defines the blue component (between 0 and 1, default is 0)
  1899. */
  1900. b,
  1901. /**
  1902. * Defines the alpha component (between 0 and 1, default is 1)
  1903. */
  1904. a) {
  1905. if (r === void 0) { r = 0; }
  1906. if (g === void 0) { g = 0; }
  1907. if (b === void 0) { b = 0; }
  1908. if (a === void 0) { a = 1; }
  1909. this.r = r;
  1910. this.g = g;
  1911. this.b = b;
  1912. this.a = a;
  1913. }
  1914. // Operators
  1915. /**
  1916. * Adds in place the given Color4 values to the current Color4 object
  1917. * @param right defines the second operand
  1918. * @returns the current updated Color4 object
  1919. */
  1920. Color4.prototype.addInPlace = function (right) {
  1921. this.r += right.r;
  1922. this.g += right.g;
  1923. this.b += right.b;
  1924. this.a += right.a;
  1925. return this;
  1926. };
  1927. /**
  1928. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1929. * @returns the new array
  1930. */
  1931. Color4.prototype.asArray = function () {
  1932. var result = new Array();
  1933. this.toArray(result, 0);
  1934. return result;
  1935. };
  1936. /**
  1937. * Stores from the starting index in the given array the Color4 successive values
  1938. * @param array defines the array where to store the r,g,b components
  1939. * @param index defines an optional index in the target array to define where to start storing values
  1940. * @returns the current Color4 object
  1941. */
  1942. Color4.prototype.toArray = function (array, index) {
  1943. if (index === undefined) {
  1944. index = 0;
  1945. }
  1946. array[index] = this.r;
  1947. array[index + 1] = this.g;
  1948. array[index + 2] = this.b;
  1949. array[index + 3] = this.a;
  1950. return this;
  1951. };
  1952. /**
  1953. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1954. * @param right defines the second operand
  1955. * @returns a new Color4 object
  1956. */
  1957. Color4.prototype.add = function (right) {
  1958. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1959. };
  1960. /**
  1961. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1962. * @param right defines the second operand
  1963. * @returns a new Color4 object
  1964. */
  1965. Color4.prototype.subtract = function (right) {
  1966. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1967. };
  1968. /**
  1969. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1970. * @param right defines the second operand
  1971. * @param result defines the Color4 object where to store the result
  1972. * @returns the current Color4 object
  1973. */
  1974. Color4.prototype.subtractToRef = function (right, result) {
  1975. result.r = this.r - right.r;
  1976. result.g = this.g - right.g;
  1977. result.b = this.b - right.b;
  1978. result.a = this.a - right.a;
  1979. return this;
  1980. };
  1981. /**
  1982. * Creates a new Color4 with the current Color4 values multiplied by scale
  1983. * @param scale defines the scaling factor to apply
  1984. * @returns a new Color4 object
  1985. */
  1986. Color4.prototype.scale = function (scale) {
  1987. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1988. };
  1989. /**
  1990. * Multiplies the current Color4 values by scale and stores the result in "result"
  1991. * @param scale defines the scaling factor to apply
  1992. * @param result defines the Color4 object where to store the result
  1993. * @returns the current unmodified Color4
  1994. */
  1995. Color4.prototype.scaleToRef = function (scale, result) {
  1996. result.r = this.r * scale;
  1997. result.g = this.g * scale;
  1998. result.b = this.b * scale;
  1999. result.a = this.a * scale;
  2000. return this;
  2001. };
  2002. /**
  2003. * Scale the current Color4 values by a factor and add the result to a given Color4
  2004. * @param scale defines the scale factor
  2005. * @param result defines the Color4 object where to store the result
  2006. * @returns the unmodified current Color4
  2007. */
  2008. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2009. result.r += this.r * scale;
  2010. result.g += this.g * scale;
  2011. result.b += this.b * scale;
  2012. result.a += this.a * scale;
  2013. return this;
  2014. };
  2015. /**
  2016. * Clamps the rgb values by the min and max values and stores the result into "result"
  2017. * @param min defines minimum clamping value (default is 0)
  2018. * @param max defines maximum clamping value (default is 1)
  2019. * @param result defines color to store the result into.
  2020. * @returns the cuurent Color4
  2021. */
  2022. Color4.prototype.clampToRef = function (min, max, result) {
  2023. if (min === void 0) { min = 0; }
  2024. if (max === void 0) { max = 1; }
  2025. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2026. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2027. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2028. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2029. return this;
  2030. };
  2031. /**
  2032. * Multipy an Color4 value by another and return a new Color4 object
  2033. * @param color defines the Color4 value to multiply by
  2034. * @returns a new Color4 object
  2035. */
  2036. Color4.prototype.multiply = function (color) {
  2037. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2038. };
  2039. /**
  2040. * Multipy a Color4 value by another and push the result in a reference value
  2041. * @param color defines the Color4 value to multiply by
  2042. * @param result defines the Color4 to fill the result in
  2043. * @returns the result Color4
  2044. */
  2045. Color4.prototype.multiplyToRef = function (color, result) {
  2046. result.r = this.r * color.r;
  2047. result.g = this.g * color.g;
  2048. result.b = this.b * color.b;
  2049. result.a = this.a * color.a;
  2050. return result;
  2051. };
  2052. /**
  2053. * Creates a string with the Color4 current values
  2054. * @returns the string representation of the Color4 object
  2055. */
  2056. Color4.prototype.toString = function () {
  2057. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2058. };
  2059. /**
  2060. * Returns the string "Color4"
  2061. * @returns "Color4"
  2062. */
  2063. Color4.prototype.getClassName = function () {
  2064. return "Color4";
  2065. };
  2066. /**
  2067. * Compute the Color4 hash code
  2068. * @returns an unique number that can be used to hash Color4 objects
  2069. */
  2070. Color4.prototype.getHashCode = function () {
  2071. var hash = this.r || 0;
  2072. hash = (hash * 397) ^ (this.g || 0);
  2073. hash = (hash * 397) ^ (this.b || 0);
  2074. hash = (hash * 397) ^ (this.a || 0);
  2075. return hash;
  2076. };
  2077. /**
  2078. * Creates a new Color4 copied from the current one
  2079. * @returns a new Color4 object
  2080. */
  2081. Color4.prototype.clone = function () {
  2082. return new Color4(this.r, this.g, this.b, this.a);
  2083. };
  2084. /**
  2085. * Copies the given Color4 values into the current one
  2086. * @param source defines the source Color4 object
  2087. * @returns the current updated Color4 object
  2088. */
  2089. Color4.prototype.copyFrom = function (source) {
  2090. this.r = source.r;
  2091. this.g = source.g;
  2092. this.b = source.b;
  2093. this.a = source.a;
  2094. return this;
  2095. };
  2096. /**
  2097. * Copies the given float values into the current one
  2098. * @param r defines the red component to read from
  2099. * @param g defines the green component to read from
  2100. * @param b defines the blue component to read from
  2101. * @param a defines the alpha component to read from
  2102. * @returns the current updated Color4 object
  2103. */
  2104. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2105. this.r = r;
  2106. this.g = g;
  2107. this.b = b;
  2108. this.a = a;
  2109. return this;
  2110. };
  2111. /**
  2112. * Copies the given float values into the current one
  2113. * @param r defines the red component to read from
  2114. * @param g defines the green component to read from
  2115. * @param b defines the blue component to read from
  2116. * @param a defines the alpha component to read from
  2117. * @returns the current updated Color4 object
  2118. */
  2119. Color4.prototype.set = function (r, g, b, a) {
  2120. return this.copyFromFloats(r, g, b, a);
  2121. };
  2122. /**
  2123. * Compute the Color4 hexadecimal code as a string
  2124. * @returns a string containing the hexadecimal representation of the Color4 object
  2125. */
  2126. Color4.prototype.toHexString = function () {
  2127. var intR = (this.r * 255) | 0;
  2128. var intG = (this.g * 255) | 0;
  2129. var intB = (this.b * 255) | 0;
  2130. var intA = (this.a * 255) | 0;
  2131. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2132. };
  2133. /**
  2134. * Computes a new Color4 converted from the current one to linear space
  2135. * @returns a new Color4 object
  2136. */
  2137. Color4.prototype.toLinearSpace = function () {
  2138. var convertedColor = new Color4();
  2139. this.toLinearSpaceToRef(convertedColor);
  2140. return convertedColor;
  2141. };
  2142. /**
  2143. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2144. * @param convertedColor defines the Color4 object where to store the linear space version
  2145. * @returns the unmodified Color4
  2146. */
  2147. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2148. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2149. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2150. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2151. convertedColor.a = this.a;
  2152. return this;
  2153. };
  2154. /**
  2155. * Computes a new Color4 converted from the current one to gamma space
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.prototype.toGammaSpace = function () {
  2159. var convertedColor = new Color4();
  2160. this.toGammaSpaceToRef(convertedColor);
  2161. return convertedColor;
  2162. };
  2163. /**
  2164. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2165. * @param convertedColor defines the Color4 object where to store the gamma space version
  2166. * @returns the unmodified Color4
  2167. */
  2168. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2169. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2170. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2171. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2172. convertedColor.a = this.a;
  2173. return this;
  2174. };
  2175. // Statics
  2176. /**
  2177. * Creates a new Color4 from the string containing valid hexadecimal values
  2178. * @param hex defines a string containing valid hexadecimal values
  2179. * @returns a new Color4 object
  2180. */
  2181. Color4.FromHexString = function (hex) {
  2182. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2183. return new Color4(0.0, 0.0, 0.0, 0.0);
  2184. }
  2185. var r = parseInt(hex.substring(1, 3), 16);
  2186. var g = parseInt(hex.substring(3, 5), 16);
  2187. var b = parseInt(hex.substring(5, 7), 16);
  2188. var a = parseInt(hex.substring(7, 9), 16);
  2189. return Color4.FromInts(r, g, b, a);
  2190. };
  2191. /**
  2192. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2193. * @param left defines the start value
  2194. * @param right defines the end value
  2195. * @param amount defines the gradient factor
  2196. * @returns a new Color4 object
  2197. */
  2198. Color4.Lerp = function (left, right, amount) {
  2199. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2200. Color4.LerpToRef(left, right, amount, result);
  2201. return result;
  2202. };
  2203. /**
  2204. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2205. * @param left defines the start value
  2206. * @param right defines the end value
  2207. * @param amount defines the gradient factor
  2208. * @param result defines the Color4 object where to store data
  2209. */
  2210. Color4.LerpToRef = function (left, right, amount, result) {
  2211. result.r = left.r + (right.r - left.r) * amount;
  2212. result.g = left.g + (right.g - left.g) * amount;
  2213. result.b = left.b + (right.b - left.b) * amount;
  2214. result.a = left.a + (right.a - left.a) * amount;
  2215. };
  2216. /**
  2217. * Creates a new Color4 from a Color3 and an alpha value
  2218. * @param color3 defines the source Color3 to read from
  2219. * @param alpha defines the alpha component (1.0 by default)
  2220. * @returns a new Color4 object
  2221. */
  2222. Color4.FromColor3 = function (color3, alpha) {
  2223. if (alpha === void 0) { alpha = 1.0; }
  2224. return new Color4(color3.r, color3.g, color3.b, alpha);
  2225. };
  2226. /**
  2227. * Creates a new Color4 from the starting index element of the given array
  2228. * @param array defines the source array to read from
  2229. * @param offset defines the offset in the source array
  2230. * @returns a new Color4 object
  2231. */
  2232. Color4.FromArray = function (array, offset) {
  2233. if (offset === void 0) { offset = 0; }
  2234. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2235. };
  2236. /**
  2237. * Creates a new Color3 from integer values (< 256)
  2238. * @param r defines the red component to read from (value between 0 and 255)
  2239. * @param g defines the green component to read from (value between 0 and 255)
  2240. * @param b defines the blue component to read from (value between 0 and 255)
  2241. * @param a defines the alpha component to read from (value between 0 and 255)
  2242. * @returns a new Color3 object
  2243. */
  2244. Color4.FromInts = function (r, g, b, a) {
  2245. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2246. };
  2247. /**
  2248. * Check the content of a given array and convert it to an array containing RGBA data
  2249. * If the original array was already containing count * 4 values then it is returned directly
  2250. * @param colors defines the array to check
  2251. * @param count defines the number of RGBA data to expect
  2252. * @returns an array containing count * 4 values (RGBA)
  2253. */
  2254. Color4.CheckColors4 = function (colors, count) {
  2255. // Check if color3 was used
  2256. if (colors.length === count * 3) {
  2257. var colors4 = [];
  2258. for (var index = 0; index < colors.length; index += 3) {
  2259. var newIndex = (index / 3) * 4;
  2260. colors4[newIndex] = colors[index];
  2261. colors4[newIndex + 1] = colors[index + 1];
  2262. colors4[newIndex + 2] = colors[index + 2];
  2263. colors4[newIndex + 3] = 1.0;
  2264. }
  2265. return colors4;
  2266. }
  2267. return colors;
  2268. };
  2269. return Color4;
  2270. }());
  2271. BABYLON.Color4 = Color4;
  2272. /**
  2273. * Class representing a vector containing 2 coordinates
  2274. */
  2275. var Vector2 = /** @class */ (function () {
  2276. /**
  2277. * Creates a new Vector2 from the given x and y coordinates
  2278. * @param x defines the first coordinate
  2279. * @param y defines the second coordinate
  2280. */
  2281. function Vector2(
  2282. /** defines the first coordinate */
  2283. x,
  2284. /** defines the second coordinate */
  2285. y) {
  2286. if (x === void 0) { x = 0; }
  2287. if (y === void 0) { y = 0; }
  2288. this.x = x;
  2289. this.y = y;
  2290. }
  2291. /**
  2292. * Gets a string with the Vector2 coordinates
  2293. * @returns a string with the Vector2 coordinates
  2294. */
  2295. Vector2.prototype.toString = function () {
  2296. return "{X: " + this.x + " Y:" + this.y + "}";
  2297. };
  2298. /**
  2299. * Gets class name
  2300. * @returns the string "Vector2"
  2301. */
  2302. Vector2.prototype.getClassName = function () {
  2303. return "Vector2";
  2304. };
  2305. /**
  2306. * Gets current vector hash code
  2307. * @returns the Vector2 hash code as a number
  2308. */
  2309. Vector2.prototype.getHashCode = function () {
  2310. var hash = this.x || 0;
  2311. hash = (hash * 397) ^ (this.y || 0);
  2312. return hash;
  2313. };
  2314. // Operators
  2315. /**
  2316. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2317. * @param array defines the source array
  2318. * @param index defines the offset in source array
  2319. * @returns the current Vector2
  2320. */
  2321. Vector2.prototype.toArray = function (array, index) {
  2322. if (index === void 0) { index = 0; }
  2323. array[index] = this.x;
  2324. array[index + 1] = this.y;
  2325. return this;
  2326. };
  2327. /**
  2328. * Copy the current vector to an array
  2329. * @returns a new array with 2 elements: the Vector2 coordinates.
  2330. */
  2331. Vector2.prototype.asArray = function () {
  2332. var result = new Array();
  2333. this.toArray(result, 0);
  2334. return result;
  2335. };
  2336. /**
  2337. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2338. * @param source defines the source Vector2
  2339. * @returns the current updated Vector2
  2340. */
  2341. Vector2.prototype.copyFrom = function (source) {
  2342. this.x = source.x;
  2343. this.y = source.y;
  2344. return this;
  2345. };
  2346. /**
  2347. * Sets the Vector2 coordinates with the given floats
  2348. * @param x defines the first coordinate
  2349. * @param y defines the second coordinate
  2350. * @returns the current updated Vector2
  2351. */
  2352. Vector2.prototype.copyFromFloats = function (x, y) {
  2353. this.x = x;
  2354. this.y = y;
  2355. return this;
  2356. };
  2357. /**
  2358. * Sets the Vector2 coordinates with the given floats
  2359. * @param x defines the first coordinate
  2360. * @param y defines the second coordinate
  2361. * @returns the current updated Vector2
  2362. */
  2363. Vector2.prototype.set = function (x, y) {
  2364. return this.copyFromFloats(x, y);
  2365. };
  2366. /**
  2367. * Add another vector with the current one
  2368. * @param otherVector defines the other vector
  2369. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2370. */
  2371. Vector2.prototype.add = function (otherVector) {
  2372. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2373. };
  2374. /**
  2375. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2376. * @param otherVector defines the other vector
  2377. * @param result defines the target vector
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.addToRef = function (otherVector, result) {
  2381. result.x = this.x + otherVector.x;
  2382. result.y = this.y + otherVector.y;
  2383. return this;
  2384. };
  2385. /**
  2386. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2387. * @param otherVector defines the other vector
  2388. * @returns the current updated Vector2
  2389. */
  2390. Vector2.prototype.addInPlace = function (otherVector) {
  2391. this.x += otherVector.x;
  2392. this.y += otherVector.y;
  2393. return this;
  2394. };
  2395. /**
  2396. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2397. * @param otherVector defines the other vector
  2398. * @returns a new Vector2
  2399. */
  2400. Vector2.prototype.addVector3 = function (otherVector) {
  2401. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2402. };
  2403. /**
  2404. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2405. * @param otherVector defines the other vector
  2406. * @returns a new Vector2
  2407. */
  2408. Vector2.prototype.subtract = function (otherVector) {
  2409. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2410. };
  2411. /**
  2412. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2413. * @param otherVector defines the other vector
  2414. * @param result defines the target vector
  2415. * @returns the unmodified current Vector2
  2416. */
  2417. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2418. result.x = this.x - otherVector.x;
  2419. result.y = this.y - otherVector.y;
  2420. return this;
  2421. };
  2422. /**
  2423. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2424. * @param otherVector defines the other vector
  2425. * @returns the current updated Vector2
  2426. */
  2427. Vector2.prototype.subtractInPlace = function (otherVector) {
  2428. this.x -= otherVector.x;
  2429. this.y -= otherVector.y;
  2430. return this;
  2431. };
  2432. /**
  2433. * Multiplies in place the current Vector2 coordinates by the given ones
  2434. * @param otherVector defines the other vector
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2438. this.x *= otherVector.x;
  2439. this.y *= otherVector.y;
  2440. return this;
  2441. };
  2442. /**
  2443. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2444. * @param otherVector defines the other vector
  2445. * @returns a new Vector2
  2446. */
  2447. Vector2.prototype.multiply = function (otherVector) {
  2448. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2449. };
  2450. /**
  2451. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2452. * @param otherVector defines the other vector
  2453. * @param result defines the target vector
  2454. * @returns the unmodified current Vector2
  2455. */
  2456. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2457. result.x = this.x * otherVector.x;
  2458. result.y = this.y * otherVector.y;
  2459. return this;
  2460. };
  2461. /**
  2462. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2463. * @param x defines the first coordinate
  2464. * @param y defines the second coordinate
  2465. * @returns a new Vector2
  2466. */
  2467. Vector2.prototype.multiplyByFloats = function (x, y) {
  2468. return new Vector2(this.x * x, this.y * y);
  2469. };
  2470. /**
  2471. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2472. * @param otherVector defines the other vector
  2473. * @returns a new Vector2
  2474. */
  2475. Vector2.prototype.divide = function (otherVector) {
  2476. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2477. };
  2478. /**
  2479. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2480. * @param otherVector defines the other vector
  2481. * @param result defines the target vector
  2482. * @returns the unmodified current Vector2
  2483. */
  2484. Vector2.prototype.divideToRef = function (otherVector, result) {
  2485. result.x = this.x / otherVector.x;
  2486. result.y = this.y / otherVector.y;
  2487. return this;
  2488. };
  2489. /**
  2490. * Divides the current Vector2 coordinates by the given ones
  2491. * @param otherVector defines the other vector
  2492. * @returns the current updated Vector2
  2493. */
  2494. Vector2.prototype.divideInPlace = function (otherVector) {
  2495. return this.divideToRef(otherVector, this);
  2496. };
  2497. /**
  2498. * Gets a new Vector2 with current Vector2 negated coordinates
  2499. * @returns a new Vector2
  2500. */
  2501. Vector2.prototype.negate = function () {
  2502. return new Vector2(-this.x, -this.y);
  2503. };
  2504. /**
  2505. * Multiply the Vector2 coordinates by scale
  2506. * @param scale defines the scaling factor
  2507. * @returns the current updated Vector2
  2508. */
  2509. Vector2.prototype.scaleInPlace = function (scale) {
  2510. this.x *= scale;
  2511. this.y *= scale;
  2512. return this;
  2513. };
  2514. /**
  2515. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2516. * @param scale defines the scaling factor
  2517. * @returns a new Vector2
  2518. */
  2519. Vector2.prototype.scale = function (scale) {
  2520. var result = new Vector2(0, 0);
  2521. this.scaleToRef(scale, result);
  2522. return result;
  2523. };
  2524. /**
  2525. * Scale the current Vector2 values by a factor to a given Vector2
  2526. * @param scale defines the scale factor
  2527. * @param result defines the Vector2 object where to store the result
  2528. * @returns the unmodified current Vector2
  2529. */
  2530. Vector2.prototype.scaleToRef = function (scale, result) {
  2531. result.x = this.x * scale;
  2532. result.y = this.y * scale;
  2533. return this;
  2534. };
  2535. /**
  2536. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2537. * @param scale defines the scale factor
  2538. * @param result defines the Vector2 object where to store the result
  2539. * @returns the unmodified current Vector2
  2540. */
  2541. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2542. result.x += this.x * scale;
  2543. result.y += this.y * scale;
  2544. return this;
  2545. };
  2546. /**
  2547. * Gets a boolean if two vectors are equals
  2548. * @param otherVector defines the other vector
  2549. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2550. */
  2551. Vector2.prototype.equals = function (otherVector) {
  2552. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2553. };
  2554. /**
  2555. * Gets a boolean if two vectors are equals (using an epsilon value)
  2556. * @param otherVector defines the other vector
  2557. * @param epsilon defines the minimal distance to consider equality
  2558. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2559. */
  2560. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2561. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2562. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2563. };
  2564. /**
  2565. * Gets a new Vector2 from current Vector2 floored values
  2566. * @returns a new Vector2
  2567. */
  2568. Vector2.prototype.floor = function () {
  2569. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2570. };
  2571. /**
  2572. * Gets a new Vector2 from current Vector2 floored values
  2573. * @returns a new Vector2
  2574. */
  2575. Vector2.prototype.fract = function () {
  2576. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2577. };
  2578. // Properties
  2579. /**
  2580. * Gets the length of the vector
  2581. * @returns the vector length (float)
  2582. */
  2583. Vector2.prototype.length = function () {
  2584. return Math.sqrt(this.x * this.x + this.y * this.y);
  2585. };
  2586. /**
  2587. * Gets the vector squared length
  2588. * @returns the vector squared length (float)
  2589. */
  2590. Vector2.prototype.lengthSquared = function () {
  2591. return (this.x * this.x + this.y * this.y);
  2592. };
  2593. // Methods
  2594. /**
  2595. * Normalize the vector
  2596. * @returns the current updated Vector2
  2597. */
  2598. Vector2.prototype.normalize = function () {
  2599. var len = this.length();
  2600. if (len === 0) {
  2601. return this;
  2602. }
  2603. var num = 1.0 / len;
  2604. this.x *= num;
  2605. this.y *= num;
  2606. return this;
  2607. };
  2608. /**
  2609. * Gets a new Vector2 copied from the Vector2
  2610. * @returns a new Vector2
  2611. */
  2612. Vector2.prototype.clone = function () {
  2613. return new Vector2(this.x, this.y);
  2614. };
  2615. // Statics
  2616. /**
  2617. * Gets a new Vector2(0, 0)
  2618. * @returns a new Vector2
  2619. */
  2620. Vector2.Zero = function () {
  2621. return new Vector2(0, 0);
  2622. };
  2623. /**
  2624. * Gets a new Vector2(1, 1)
  2625. * @returns a new Vector2
  2626. */
  2627. Vector2.One = function () {
  2628. return new Vector2(1, 1);
  2629. };
  2630. /**
  2631. * Gets a new Vector2 set from the given index element of the given array
  2632. * @param array defines the data source
  2633. * @param offset defines the offset in the data source
  2634. * @returns a new Vector2
  2635. */
  2636. Vector2.FromArray = function (array, offset) {
  2637. if (offset === void 0) { offset = 0; }
  2638. return new Vector2(array[offset], array[offset + 1]);
  2639. };
  2640. /**
  2641. * Sets "result" from the given index element of the given array
  2642. * @param array defines the data source
  2643. * @param offset defines the offset in the data source
  2644. * @param result defines the target vector
  2645. */
  2646. Vector2.FromArrayToRef = function (array, offset, result) {
  2647. result.x = array[offset];
  2648. result.y = array[offset + 1];
  2649. };
  2650. /**
  2651. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2652. * @param value1 defines 1st point of control
  2653. * @param value2 defines 2nd point of control
  2654. * @param value3 defines 3rd point of control
  2655. * @param value4 defines 4th point of control
  2656. * @param amount defines the interpolation factor
  2657. * @returns a new Vector2
  2658. */
  2659. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2660. var squared = amount * amount;
  2661. var cubed = amount * squared;
  2662. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2663. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2664. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2665. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2666. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2667. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2668. return new Vector2(x, y);
  2669. };
  2670. /**
  2671. * 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".
  2672. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2673. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2674. * @param value defines the value to clamp
  2675. * @param min defines the lower limit
  2676. * @param max defines the upper limit
  2677. * @returns a new Vector2
  2678. */
  2679. Vector2.Clamp = function (value, min, max) {
  2680. var x = value.x;
  2681. x = (x > max.x) ? max.x : x;
  2682. x = (x < min.x) ? min.x : x;
  2683. var y = value.y;
  2684. y = (y > max.y) ? max.y : y;
  2685. y = (y < min.y) ? min.y : y;
  2686. return new Vector2(x, y);
  2687. };
  2688. /**
  2689. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2690. * @param value1 defines the 1st control point
  2691. * @param tangent1 defines the outgoing tangent
  2692. * @param value2 defines the 2nd control point
  2693. * @param tangent2 defines the incoming tangent
  2694. * @param amount defines the interpolation factor
  2695. * @returns a new Vector2
  2696. */
  2697. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2698. var squared = amount * amount;
  2699. var cubed = amount * squared;
  2700. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2701. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2702. var part3 = (cubed - (2.0 * squared)) + amount;
  2703. var part4 = cubed - squared;
  2704. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2705. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2706. return new Vector2(x, y);
  2707. };
  2708. /**
  2709. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2710. * @param start defines the start vector
  2711. * @param end defines the end vector
  2712. * @param amount defines the interpolation factor
  2713. * @returns a new Vector2
  2714. */
  2715. Vector2.Lerp = function (start, end, amount) {
  2716. var x = start.x + ((end.x - start.x) * amount);
  2717. var y = start.y + ((end.y - start.y) * amount);
  2718. return new Vector2(x, y);
  2719. };
  2720. /**
  2721. * Gets the dot product of the vector "left" and the vector "right"
  2722. * @param left defines first vector
  2723. * @param right defines second vector
  2724. * @returns the dot product (float)
  2725. */
  2726. Vector2.Dot = function (left, right) {
  2727. return left.x * right.x + left.y * right.y;
  2728. };
  2729. /**
  2730. * Returns a new Vector2 equal to the normalized given vector
  2731. * @param vector defines the vector to normalize
  2732. * @returns a new Vector2
  2733. */
  2734. Vector2.Normalize = function (vector) {
  2735. var newVector = vector.clone();
  2736. newVector.normalize();
  2737. return newVector;
  2738. };
  2739. /**
  2740. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2741. * @param left defines 1st vector
  2742. * @param right defines 2nd vector
  2743. * @returns a new Vector2
  2744. */
  2745. Vector2.Minimize = function (left, right) {
  2746. var x = (left.x < right.x) ? left.x : right.x;
  2747. var y = (left.y < right.y) ? left.y : right.y;
  2748. return new Vector2(x, y);
  2749. };
  2750. /**
  2751. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2752. * @param left defines 1st vector
  2753. * @param right defines 2nd vector
  2754. * @returns a new Vector2
  2755. */
  2756. Vector2.Maximize = function (left, right) {
  2757. var x = (left.x > right.x) ? left.x : right.x;
  2758. var y = (left.y > right.y) ? left.y : right.y;
  2759. return new Vector2(x, y);
  2760. };
  2761. /**
  2762. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2763. * @param vector defines the vector to transform
  2764. * @param transformation defines the matrix to apply
  2765. * @returns a new Vector2
  2766. */
  2767. Vector2.Transform = function (vector, transformation) {
  2768. var r = Vector2.Zero();
  2769. Vector2.TransformToRef(vector, transformation, r);
  2770. return r;
  2771. };
  2772. /**
  2773. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2774. * @param vector defines the vector to transform
  2775. * @param transformation defines the matrix to apply
  2776. * @param result defines the target vector
  2777. */
  2778. Vector2.TransformToRef = function (vector, transformation, result) {
  2779. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2780. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2781. result.x = x;
  2782. result.y = y;
  2783. };
  2784. /**
  2785. * Determines if a given vector is included in a triangle
  2786. * @param p defines the vector to test
  2787. * @param p0 defines 1st triangle point
  2788. * @param p1 defines 2nd triangle point
  2789. * @param p2 defines 3rd triangle point
  2790. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2791. */
  2792. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2793. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2794. var sign = a < 0 ? -1 : 1;
  2795. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2796. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2797. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2798. };
  2799. /**
  2800. * Gets the distance between the vectors "value1" and "value2"
  2801. * @param value1 defines first vector
  2802. * @param value2 defines second vector
  2803. * @returns the distance between vectors
  2804. */
  2805. Vector2.Distance = function (value1, value2) {
  2806. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2807. };
  2808. /**
  2809. * Returns the squared distance between the vectors "value1" and "value2"
  2810. * @param value1 defines first vector
  2811. * @param value2 defines second vector
  2812. * @returns the squared distance between vectors
  2813. */
  2814. Vector2.DistanceSquared = function (value1, value2) {
  2815. var x = value1.x - value2.x;
  2816. var y = value1.y - value2.y;
  2817. return (x * x) + (y * y);
  2818. };
  2819. /**
  2820. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2821. * @param value1 defines first vector
  2822. * @param value2 defines second vector
  2823. * @returns a new Vector2
  2824. */
  2825. Vector2.Center = function (value1, value2) {
  2826. var center = value1.add(value2);
  2827. center.scaleInPlace(0.5);
  2828. return center;
  2829. };
  2830. /**
  2831. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2832. * @param p defines the middle point
  2833. * @param segA defines one point of the segment
  2834. * @param segB defines the other point of the segment
  2835. * @returns the shortest distance
  2836. */
  2837. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2838. var l2 = Vector2.DistanceSquared(segA, segB);
  2839. if (l2 === 0.0) {
  2840. return Vector2.Distance(p, segA);
  2841. }
  2842. var v = segB.subtract(segA);
  2843. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2844. var proj = segA.add(v.multiplyByFloats(t, t));
  2845. return Vector2.Distance(p, proj);
  2846. };
  2847. return Vector2;
  2848. }());
  2849. BABYLON.Vector2 = Vector2;
  2850. /**
  2851. * Classed used to store (x,y,z) vector representation
  2852. * A Vector3 is the main object used in 3D geometry
  2853. * It can represent etiher the coordinates of a point the space, either a direction
  2854. * Reminder: Babylon.js uses a left handed forward facing system
  2855. */
  2856. var Vector3 = /** @class */ (function () {
  2857. /**
  2858. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2859. * @param x defines the first coordinates (on X axis)
  2860. * @param y defines the second coordinates (on Y axis)
  2861. * @param z defines the third coordinates (on Z axis)
  2862. */
  2863. function Vector3(
  2864. /**
  2865. * Defines the first coordinates (on X axis)
  2866. */
  2867. x,
  2868. /**
  2869. * Defines the second coordinates (on Y axis)
  2870. */
  2871. y,
  2872. /**
  2873. * Defines the third coordinates (on Z axis)
  2874. */
  2875. z) {
  2876. if (x === void 0) { x = 0; }
  2877. if (y === void 0) { y = 0; }
  2878. if (z === void 0) { z = 0; }
  2879. this.x = x;
  2880. this.y = y;
  2881. this.z = z;
  2882. }
  2883. /**
  2884. * Creates a string representation of the Vector3
  2885. * @returns a string with the Vector3 coordinates.
  2886. */
  2887. Vector3.prototype.toString = function () {
  2888. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2889. };
  2890. /**
  2891. * Gets the class name
  2892. * @returns the string "Vector3"
  2893. */
  2894. Vector3.prototype.getClassName = function () {
  2895. return "Vector3";
  2896. };
  2897. /**
  2898. * Creates the Vector3 hash code
  2899. * @returns a number which tends to be unique between Vector3 instances
  2900. */
  2901. Vector3.prototype.getHashCode = function () {
  2902. var hash = this.x || 0;
  2903. hash = (hash * 397) ^ (this.y || 0);
  2904. hash = (hash * 397) ^ (this.z || 0);
  2905. return hash;
  2906. };
  2907. // Operators
  2908. /**
  2909. * Creates an array containing three elements : the coordinates of the Vector3
  2910. * @returns a new array of numbers
  2911. */
  2912. Vector3.prototype.asArray = function () {
  2913. var result = [];
  2914. this.toArray(result, 0);
  2915. return result;
  2916. };
  2917. /**
  2918. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2919. * @param array defines the destination array
  2920. * @param index defines the offset in the destination array
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.toArray = function (array, index) {
  2924. if (index === void 0) { index = 0; }
  2925. array[index] = this.x;
  2926. array[index + 1] = this.y;
  2927. array[index + 2] = this.z;
  2928. return this;
  2929. };
  2930. /**
  2931. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2932. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2933. */
  2934. Vector3.prototype.toQuaternion = function () {
  2935. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2936. };
  2937. /**
  2938. * Adds the given vector to the current Vector3
  2939. * @param otherVector defines the second operand
  2940. * @returns the current updated Vector3
  2941. */
  2942. Vector3.prototype.addInPlace = function (otherVector) {
  2943. this.x += otherVector.x;
  2944. this.y += otherVector.y;
  2945. this.z += otherVector.z;
  2946. return this;
  2947. };
  2948. /**
  2949. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2950. * @param otherVector defines the second operand
  2951. * @returns the resulting Vector3
  2952. */
  2953. Vector3.prototype.add = function (otherVector) {
  2954. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2955. };
  2956. /**
  2957. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2958. * @param otherVector defines the second operand
  2959. * @param result defines the Vector3 object where to store the result
  2960. * @returns the current Vector3
  2961. */
  2962. Vector3.prototype.addToRef = function (otherVector, result) {
  2963. result.x = this.x + otherVector.x;
  2964. result.y = this.y + otherVector.y;
  2965. result.z = this.z + otherVector.z;
  2966. return this;
  2967. };
  2968. /**
  2969. * Subtract the given vector from the current Vector3
  2970. * @param otherVector defines the second operand
  2971. * @returns the current updated Vector3
  2972. */
  2973. Vector3.prototype.subtractInPlace = function (otherVector) {
  2974. this.x -= otherVector.x;
  2975. this.y -= otherVector.y;
  2976. this.z -= otherVector.z;
  2977. return this;
  2978. };
  2979. /**
  2980. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2981. * @param otherVector defines the second operand
  2982. * @returns the resulting Vector3
  2983. */
  2984. Vector3.prototype.subtract = function (otherVector) {
  2985. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2986. };
  2987. /**
  2988. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2989. * @param otherVector defines the second operand
  2990. * @param result defines the Vector3 object where to store the result
  2991. * @returns the current Vector3
  2992. */
  2993. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2994. result.x = this.x - otherVector.x;
  2995. result.y = this.y - otherVector.y;
  2996. result.z = this.z - otherVector.z;
  2997. return this;
  2998. };
  2999. /**
  3000. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  3001. * @param x defines the x coordinate of the operand
  3002. * @param y defines the y coordinate of the operand
  3003. * @param z defines the z coordinate of the operand
  3004. * @returns the resulting Vector3
  3005. */
  3006. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3007. return new Vector3(this.x - x, this.y - y, this.z - z);
  3008. };
  3009. /**
  3010. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3011. * @param x defines the x coordinate of the operand
  3012. * @param y defines the y coordinate of the operand
  3013. * @param z defines the z coordinate of the operand
  3014. * @param result defines the Vector3 object where to store the result
  3015. * @returns the current Vector3
  3016. */
  3017. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3018. result.x = this.x - x;
  3019. result.y = this.y - y;
  3020. result.z = this.z - z;
  3021. return this;
  3022. };
  3023. /**
  3024. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3025. * @returns a new Vector3
  3026. */
  3027. Vector3.prototype.negate = function () {
  3028. return new Vector3(-this.x, -this.y, -this.z);
  3029. };
  3030. /**
  3031. * Multiplies the Vector3 coordinates by the float "scale"
  3032. * @param scale defines the multiplier factor
  3033. * @returns the current updated Vector3
  3034. */
  3035. Vector3.prototype.scaleInPlace = function (scale) {
  3036. this.x *= scale;
  3037. this.y *= scale;
  3038. this.z *= scale;
  3039. return this;
  3040. };
  3041. /**
  3042. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3043. * @param scale defines the multiplier factor
  3044. * @returns a new Vector3
  3045. */
  3046. Vector3.prototype.scale = function (scale) {
  3047. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3048. };
  3049. /**
  3050. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3051. * @param scale defines the multiplier factor
  3052. * @param result defines the Vector3 object where to store the result
  3053. * @returns the current Vector3
  3054. */
  3055. Vector3.prototype.scaleToRef = function (scale, result) {
  3056. result.x = this.x * scale;
  3057. result.y = this.y * scale;
  3058. result.z = this.z * scale;
  3059. return this;
  3060. };
  3061. /**
  3062. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3063. * @param scale defines the scale factor
  3064. * @param result defines the Vector3 object where to store the result
  3065. * @returns the unmodified current Vector3
  3066. */
  3067. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3068. result.x += this.x * scale;
  3069. result.y += this.y * scale;
  3070. result.z += this.z * scale;
  3071. return this;
  3072. };
  3073. /**
  3074. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3075. * @param otherVector defines the second operand
  3076. * @returns true if both vectors are equals
  3077. */
  3078. Vector3.prototype.equals = function (otherVector) {
  3079. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3080. };
  3081. /**
  3082. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3083. * @param otherVector defines the second operand
  3084. * @param epsilon defines the minimal distance to define values as equals
  3085. * @returns true if both vectors are distant less than epsilon
  3086. */
  3087. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3088. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3089. 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);
  3090. };
  3091. /**
  3092. * Returns true if the current Vector3 coordinates equals the given floats
  3093. * @param x defines the x coordinate of the operand
  3094. * @param y defines the y coordinate of the operand
  3095. * @param z defines the z coordinate of the operand
  3096. * @returns true if both vectors are equals
  3097. */
  3098. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3099. return this.x === x && this.y === y && this.z === z;
  3100. };
  3101. /**
  3102. * Multiplies the current Vector3 coordinates by the given ones
  3103. * @param otherVector defines the second operand
  3104. * @returns the current updated Vector3
  3105. */
  3106. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3107. this.x *= otherVector.x;
  3108. this.y *= otherVector.y;
  3109. this.z *= otherVector.z;
  3110. return this;
  3111. };
  3112. /**
  3113. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3114. * @param otherVector defines the second operand
  3115. * @returns the new Vector3
  3116. */
  3117. Vector3.prototype.multiply = function (otherVector) {
  3118. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3119. };
  3120. /**
  3121. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3122. * @param otherVector defines the second operand
  3123. * @param result defines the Vector3 object where to store the result
  3124. * @returns the current Vector3
  3125. */
  3126. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3127. result.x = this.x * otherVector.x;
  3128. result.y = this.y * otherVector.y;
  3129. result.z = this.z * otherVector.z;
  3130. return this;
  3131. };
  3132. /**
  3133. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3134. * @param x defines the x coordinate of the operand
  3135. * @param y defines the y coordinate of the operand
  3136. * @param z defines the z coordinate of the operand
  3137. * @returns the new Vector3
  3138. */
  3139. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3140. return new Vector3(this.x * x, this.y * y, this.z * z);
  3141. };
  3142. /**
  3143. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3144. * @param otherVector defines the second operand
  3145. * @returns the new Vector3
  3146. */
  3147. Vector3.prototype.divide = function (otherVector) {
  3148. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3149. };
  3150. /**
  3151. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3152. * @param otherVector defines the second operand
  3153. * @param result defines the Vector3 object where to store the result
  3154. * @returns the current Vector3
  3155. */
  3156. Vector3.prototype.divideToRef = function (otherVector, result) {
  3157. result.x = this.x / otherVector.x;
  3158. result.y = this.y / otherVector.y;
  3159. result.z = this.z / otherVector.z;
  3160. return this;
  3161. };
  3162. /**
  3163. * Divides the current Vector3 coordinates by the given ones.
  3164. * @param otherVector defines the second operand
  3165. * @returns the current updated Vector3
  3166. */
  3167. Vector3.prototype.divideInPlace = function (otherVector) {
  3168. return this.divideToRef(otherVector, this);
  3169. };
  3170. /**
  3171. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3172. * @param other defines the second operand
  3173. * @returns the current updated Vector3
  3174. */
  3175. Vector3.prototype.minimizeInPlace = function (other) {
  3176. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  3177. };
  3178. /**
  3179. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3180. * @param other defines the second operand
  3181. * @returns the current updated Vector3
  3182. */
  3183. Vector3.prototype.maximizeInPlace = function (other) {
  3184. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  3185. };
  3186. /**
  3187. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  3188. * @param x defines the x coordinate of the operand
  3189. * @param y defines the y coordinate of the operand
  3190. * @param z defines the z coordinate of the operand
  3191. * @returns the current updated Vector3
  3192. */
  3193. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  3194. if (x < this.x) {
  3195. this.x = x;
  3196. }
  3197. if (y < this.y) {
  3198. this.y = y;
  3199. }
  3200. if (z < this.z) {
  3201. this.z = z;
  3202. }
  3203. return this;
  3204. };
  3205. /**
  3206. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3207. * @param x defines the x coordinate of the operand
  3208. * @param y defines the y coordinate of the operand
  3209. * @param z defines the z coordinate of the operand
  3210. * @returns the current updated Vector3
  3211. */
  3212. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3213. if (x > this.x) {
  3214. this.x = x;
  3215. }
  3216. if (y > this.y) {
  3217. this.y = y;
  3218. }
  3219. if (z > this.z) {
  3220. this.z = z;
  3221. }
  3222. return this;
  3223. };
  3224. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3225. /**
  3226. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3227. */
  3228. get: function () {
  3229. var absX = Math.abs(this.x);
  3230. var absY = Math.abs(this.y);
  3231. if (absX !== absY) {
  3232. return true;
  3233. }
  3234. var absZ = Math.abs(this.z);
  3235. if (absX !== absZ) {
  3236. return true;
  3237. }
  3238. if (absY !== absZ) {
  3239. return true;
  3240. }
  3241. return false;
  3242. },
  3243. enumerable: true,
  3244. configurable: true
  3245. });
  3246. /**
  3247. * Gets a new Vector3 from current Vector3 floored values
  3248. * @returns a new Vector3
  3249. */
  3250. Vector3.prototype.floor = function () {
  3251. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3252. };
  3253. /**
  3254. * Gets a new Vector3 from current Vector3 floored values
  3255. * @returns a new Vector3
  3256. */
  3257. Vector3.prototype.fract = function () {
  3258. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3259. };
  3260. // Properties
  3261. /**
  3262. * Gets the length of the Vector3
  3263. * @returns the length of the Vecto3
  3264. */
  3265. Vector3.prototype.length = function () {
  3266. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3267. };
  3268. /**
  3269. * Gets the squared length of the Vector3
  3270. * @returns squared length of the Vector3
  3271. */
  3272. Vector3.prototype.lengthSquared = function () {
  3273. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3274. };
  3275. /**
  3276. * Normalize the current Vector3.
  3277. * Please note that this is an in place operation.
  3278. * @returns the current updated Vector3
  3279. */
  3280. Vector3.prototype.normalize = function () {
  3281. var len = this.length();
  3282. if (len === 0 || len === 1.0) {
  3283. return this;
  3284. }
  3285. var num = 1.0 / len;
  3286. this.x *= num;
  3287. this.y *= num;
  3288. this.z *= num;
  3289. return this;
  3290. };
  3291. /**
  3292. * Normalize the current Vector3 to a new vector
  3293. * @returns the new Vector3
  3294. */
  3295. Vector3.prototype.normalizeToNew = function () {
  3296. var normalized = new Vector3(0, 0, 0);
  3297. this.normalizeToRef(normalized);
  3298. return normalized;
  3299. };
  3300. /**
  3301. * Normalize the current Vector3 to the reference
  3302. * @param reference define the Vector3 to update
  3303. * @returns the updated Vector3
  3304. */
  3305. Vector3.prototype.normalizeToRef = function (reference) {
  3306. var len = this.length();
  3307. if (len === 0 || len === 1.0) {
  3308. reference.set(this.x, this.y, this.z);
  3309. return reference;
  3310. }
  3311. var scale = 1.0 / len;
  3312. this.scaleToRef(scale, reference);
  3313. return reference;
  3314. };
  3315. /**
  3316. * Creates a new Vector3 copied from the current Vector3
  3317. * @returns the new Vector3
  3318. */
  3319. Vector3.prototype.clone = function () {
  3320. return new Vector3(this.x, this.y, this.z);
  3321. };
  3322. /**
  3323. * Copies the given vector coordinates to the current Vector3 ones
  3324. * @param source defines the source Vector3
  3325. * @returns the current updated Vector3
  3326. */
  3327. Vector3.prototype.copyFrom = function (source) {
  3328. this.x = source.x;
  3329. this.y = source.y;
  3330. this.z = source.z;
  3331. return this;
  3332. };
  3333. /**
  3334. * Copies the given floats to the current Vector3 coordinates
  3335. * @param x defines the x coordinate of the operand
  3336. * @param y defines the y coordinate of the operand
  3337. * @param z defines the z coordinate of the operand
  3338. * @returns the current updated Vector3
  3339. */
  3340. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3341. this.x = x;
  3342. this.y = y;
  3343. this.z = z;
  3344. return this;
  3345. };
  3346. /**
  3347. * Copies the given floats to the current Vector3 coordinates
  3348. * @param x defines the x coordinate of the operand
  3349. * @param y defines the y coordinate of the operand
  3350. * @param z defines the z coordinate of the operand
  3351. * @returns the current updated Vector3
  3352. */
  3353. Vector3.prototype.set = function (x, y, z) {
  3354. return this.copyFromFloats(x, y, z);
  3355. };
  3356. // Statics
  3357. /**
  3358. * Get the clip factor between two vectors
  3359. * @param vector0 defines the first operand
  3360. * @param vector1 defines the second operand
  3361. * @param axis defines the axis to use
  3362. * @param size defines the size along the axis
  3363. * @returns the clip factor
  3364. */
  3365. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3366. var d0 = Vector3.Dot(vector0, axis) - size;
  3367. var d1 = Vector3.Dot(vector1, axis) - size;
  3368. var s = d0 / (d0 - d1);
  3369. return s;
  3370. };
  3371. /**
  3372. * Get angle between two vectors
  3373. * @param vector0 angle between vector0 and vector1
  3374. * @param vector1 angle between vector0 and vector1
  3375. * @param normal direction of the normal
  3376. * @return the angle between vector0 and vector1
  3377. */
  3378. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3379. var v0 = MathTmp.Vector3[1].copyFrom(vector0).normalize();
  3380. var v1 = MathTmp.Vector3[2].copyFrom(vector1).normalize();
  3381. var dot = Vector3.Dot(v0, v1);
  3382. var n = MathTmp.Vector3[3];
  3383. Vector3.CrossToRef(v0, v1, n);
  3384. if (Vector3.Dot(n, normal) > 0) {
  3385. return Math.acos(dot);
  3386. }
  3387. return -Math.acos(dot);
  3388. };
  3389. /**
  3390. * Returns a new Vector3 set from the index "offset" of the given array
  3391. * @param array defines the source array
  3392. * @param offset defines the offset in the source array
  3393. * @returns the new Vector3
  3394. */
  3395. Vector3.FromArray = function (array, offset) {
  3396. if (!offset) {
  3397. offset = 0;
  3398. }
  3399. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3403. * This function is deprecated. Use FromArray instead
  3404. * @param array defines the source array
  3405. * @param offset defines the offset in the source array
  3406. * @returns the new Vector3
  3407. */
  3408. Vector3.FromFloatArray = function (array, offset) {
  3409. return Vector3.FromArray(array, offset);
  3410. };
  3411. /**
  3412. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3413. * @param array defines the source array
  3414. * @param offset defines the offset in the source array
  3415. * @param result defines the Vector3 where to store the result
  3416. */
  3417. Vector3.FromArrayToRef = function (array, offset, result) {
  3418. result.x = array[offset];
  3419. result.y = array[offset + 1];
  3420. result.z = array[offset + 2];
  3421. };
  3422. /**
  3423. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3424. * This function is deprecated. Use FromArrayToRef instead.
  3425. * @param array defines the source array
  3426. * @param offset defines the offset in the source array
  3427. * @param result defines the Vector3 where to store the result
  3428. */
  3429. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3430. return Vector3.FromArrayToRef(array, offset, result);
  3431. };
  3432. /**
  3433. * Sets the given vector "result" with the given floats.
  3434. * @param x defines the x coordinate of the source
  3435. * @param y defines the y coordinate of the source
  3436. * @param z defines the z coordinate of the source
  3437. * @param result defines the Vector3 where to store the result
  3438. */
  3439. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3440. result.x = x;
  3441. result.y = y;
  3442. result.z = z;
  3443. };
  3444. /**
  3445. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3446. * @returns a new empty Vector3
  3447. */
  3448. Vector3.Zero = function () {
  3449. return new Vector3(0.0, 0.0, 0.0);
  3450. };
  3451. /**
  3452. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3453. * @returns a new unit Vector3
  3454. */
  3455. Vector3.One = function () {
  3456. return new Vector3(1.0, 1.0, 1.0);
  3457. };
  3458. /**
  3459. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3460. * @returns a new up Vector3
  3461. */
  3462. Vector3.Up = function () {
  3463. return new Vector3(0.0, 1.0, 0.0);
  3464. };
  3465. /**
  3466. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3467. * @returns a new down Vector3
  3468. */
  3469. Vector3.Down = function () {
  3470. return new Vector3(0.0, -1.0, 0.0);
  3471. };
  3472. /**
  3473. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3474. * @returns a new forward Vector3
  3475. */
  3476. Vector3.Forward = function () {
  3477. return new Vector3(0.0, 0.0, 1.0);
  3478. };
  3479. /**
  3480. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3481. * @returns a new forward Vector3
  3482. */
  3483. Vector3.Backward = function () {
  3484. return new Vector3(0.0, 0.0, -1.0);
  3485. };
  3486. /**
  3487. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3488. * @returns a new right Vector3
  3489. */
  3490. Vector3.Right = function () {
  3491. return new Vector3(1.0, 0.0, 0.0);
  3492. };
  3493. /**
  3494. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3495. * @returns a new left Vector3
  3496. */
  3497. Vector3.Left = function () {
  3498. return new Vector3(-1.0, 0.0, 0.0);
  3499. };
  3500. /**
  3501. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3502. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3503. * @param vector defines the Vector3 to transform
  3504. * @param transformation defines the transformation matrix
  3505. * @returns the transformed Vector3
  3506. */
  3507. Vector3.TransformCoordinates = function (vector, transformation) {
  3508. var result = Vector3.Zero();
  3509. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3510. return result;
  3511. };
  3512. /**
  3513. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3514. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3515. * @param vector defines the Vector3 to transform
  3516. * @param transformation defines the transformation matrix
  3517. * @param result defines the Vector3 where to store the result
  3518. */
  3519. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3520. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3521. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3522. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3523. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3524. result.x = x / w;
  3525. result.y = y / w;
  3526. result.z = z / w;
  3527. };
  3528. /**
  3529. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3530. * This method computes tranformed coordinates only, not transformed direction vectors
  3531. * @param x define the x coordinate of the source vector
  3532. * @param y define the y coordinate of the source vector
  3533. * @param z define the z coordinate of the source vector
  3534. * @param transformation defines the transformation matrix
  3535. * @param result defines the Vector3 where to store the result
  3536. */
  3537. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3538. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3539. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3540. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3541. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3542. result.x = rx / rw;
  3543. result.y = ry / rw;
  3544. result.z = rz / rw;
  3545. };
  3546. /**
  3547. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3548. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3549. * @param vector defines the Vector3 to transform
  3550. * @param transformation defines the transformation matrix
  3551. * @returns the new Vector3
  3552. */
  3553. Vector3.TransformNormal = function (vector, transformation) {
  3554. var result = Vector3.Zero();
  3555. Vector3.TransformNormalToRef(vector, transformation, result);
  3556. return result;
  3557. };
  3558. /**
  3559. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3560. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3561. * @param vector defines the Vector3 to transform
  3562. * @param transformation defines the transformation matrix
  3563. * @param result defines the Vector3 where to store the result
  3564. */
  3565. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3568. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3569. result.x = x;
  3570. result.y = y;
  3571. result.z = z;
  3572. };
  3573. /**
  3574. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3575. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3576. * @param x define the x coordinate of the source vector
  3577. * @param y define the y coordinate of the source vector
  3578. * @param z define the z coordinate of the source vector
  3579. * @param transformation defines the transformation matrix
  3580. * @param result defines the Vector3 where to store the result
  3581. */
  3582. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3583. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3584. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3585. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3586. };
  3587. /**
  3588. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3589. * @param value1 defines the first control point
  3590. * @param value2 defines the second control point
  3591. * @param value3 defines the third control point
  3592. * @param value4 defines the fourth control point
  3593. * @param amount defines the amount on the spline to use
  3594. * @returns the new Vector3
  3595. */
  3596. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3597. var squared = amount * amount;
  3598. var cubed = amount * squared;
  3599. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3600. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3601. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3602. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3603. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3604. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3605. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3606. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3607. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3608. return new Vector3(x, y, z);
  3609. };
  3610. /**
  3611. * 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"
  3612. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3613. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3614. * @param value defines the current value
  3615. * @param min defines the lower range value
  3616. * @param max defines the upper range value
  3617. * @returns the new Vector3
  3618. */
  3619. Vector3.Clamp = function (value, min, max) {
  3620. var x = value.x;
  3621. x = (x > max.x) ? max.x : x;
  3622. x = (x < min.x) ? min.x : x;
  3623. var y = value.y;
  3624. y = (y > max.y) ? max.y : y;
  3625. y = (y < min.y) ? min.y : y;
  3626. var z = value.z;
  3627. z = (z > max.z) ? max.z : z;
  3628. z = (z < min.z) ? min.z : z;
  3629. return new Vector3(x, y, z);
  3630. };
  3631. /**
  3632. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3633. * @param value1 defines the first control point
  3634. * @param tangent1 defines the first tangent vector
  3635. * @param value2 defines the second control point
  3636. * @param tangent2 defines the second tangent vector
  3637. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3638. * @returns the new Vector3
  3639. */
  3640. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3641. var squared = amount * amount;
  3642. var cubed = amount * squared;
  3643. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3644. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3645. var part3 = (cubed - (2.0 * squared)) + amount;
  3646. var part4 = cubed - squared;
  3647. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3648. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3649. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3650. return new Vector3(x, y, z);
  3651. };
  3652. /**
  3653. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3654. * @param start defines the start value
  3655. * @param end defines the end value
  3656. * @param amount max defines amount between both (between 0 and 1)
  3657. * @returns the new Vector3
  3658. */
  3659. Vector3.Lerp = function (start, end, amount) {
  3660. var result = new Vector3(0, 0, 0);
  3661. Vector3.LerpToRef(start, end, amount, result);
  3662. return result;
  3663. };
  3664. /**
  3665. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3666. * @param start defines the start value
  3667. * @param end defines the end value
  3668. * @param amount max defines amount between both (between 0 and 1)
  3669. * @param result defines the Vector3 where to store the result
  3670. */
  3671. Vector3.LerpToRef = function (start, end, amount, result) {
  3672. result.x = start.x + ((end.x - start.x) * amount);
  3673. result.y = start.y + ((end.y - start.y) * amount);
  3674. result.z = start.z + ((end.z - start.z) * amount);
  3675. };
  3676. /**
  3677. * Returns the dot product (float) between the vectors "left" and "right"
  3678. * @param left defines the left operand
  3679. * @param right defines the right operand
  3680. * @returns the dot product
  3681. */
  3682. Vector3.Dot = function (left, right) {
  3683. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3684. };
  3685. /**
  3686. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3687. * The cross product is then orthogonal to both "left" and "right"
  3688. * @param left defines the left operand
  3689. * @param right defines the right operand
  3690. * @returns the cross product
  3691. */
  3692. Vector3.Cross = function (left, right) {
  3693. var result = Vector3.Zero();
  3694. Vector3.CrossToRef(left, right, result);
  3695. return result;
  3696. };
  3697. /**
  3698. * Sets the given vector "result" with the cross product of "left" and "right"
  3699. * The cross product is then orthogonal to both "left" and "right"
  3700. * @param left defines the left operand
  3701. * @param right defines the right operand
  3702. * @param result defines the Vector3 where to store the result
  3703. */
  3704. Vector3.CrossToRef = function (left, right, result) {
  3705. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3706. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3707. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3708. result.copyFrom(MathTmp.Vector3[0]);
  3709. };
  3710. /**
  3711. * Returns a new Vector3 as the normalization of the given vector
  3712. * @param vector defines the Vector3 to normalize
  3713. * @returns the new Vector3
  3714. */
  3715. Vector3.Normalize = function (vector) {
  3716. var result = Vector3.Zero();
  3717. Vector3.NormalizeToRef(vector, result);
  3718. return result;
  3719. };
  3720. /**
  3721. * Sets the given vector "result" with the normalization of the given first vector
  3722. * @param vector defines the Vector3 to normalize
  3723. * @param result defines the Vector3 where to store the result
  3724. */
  3725. Vector3.NormalizeToRef = function (vector, result) {
  3726. result.copyFrom(vector);
  3727. result.normalize();
  3728. };
  3729. /**
  3730. * Project a Vector3 onto screen space
  3731. * @param vector defines the Vector3 to project
  3732. * @param world defines the world matrix to use
  3733. * @param transform defines the transform (view x projection) matrix to use
  3734. * @param viewport defines the screen viewport to use
  3735. * @returns the new Vector3
  3736. */
  3737. Vector3.Project = function (vector, world, transform, viewport) {
  3738. var cw = viewport.width;
  3739. var ch = viewport.height;
  3740. var cx = viewport.x;
  3741. var cy = viewport.y;
  3742. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3743. 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);
  3744. var matrix = MathTmp.Matrix[0];
  3745. world.multiplyToRef(transform, matrix);
  3746. matrix.multiplyToRef(viewportMatrix, matrix);
  3747. return Vector3.TransformCoordinates(vector, matrix);
  3748. };
  3749. /**
  3750. * Unproject from screen space to object space
  3751. * @param source defines the screen space Vector3 to use
  3752. * @param viewportWidth defines the current width of the viewport
  3753. * @param viewportHeight defines the current height of the viewport
  3754. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3755. * @param transform defines the transform (view x projection) matrix to use
  3756. * @returns the new Vector3
  3757. */
  3758. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3759. var matrix = MathTmp.Matrix[0];
  3760. world.multiplyToRef(transform, matrix);
  3761. matrix.invert();
  3762. source.x = source.x / viewportWidth * 2 - 1;
  3763. source.y = -(source.y / viewportHeight * 2 - 1);
  3764. var vector = Vector3.TransformCoordinates(source, matrix);
  3765. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3766. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3767. vector = vector.scale(1.0 / num);
  3768. }
  3769. return vector;
  3770. };
  3771. /**
  3772. * Unproject from screen space to object space
  3773. * @param source defines the screen space Vector3 to use
  3774. * @param viewportWidth defines the current width of the viewport
  3775. * @param viewportHeight defines the current height of the viewport
  3776. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3777. * @param view defines the view matrix to use
  3778. * @param projection defines the projection matrix to use
  3779. * @returns the new Vector3
  3780. */
  3781. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3782. var result = Vector3.Zero();
  3783. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3784. return result;
  3785. };
  3786. /**
  3787. * Unproject from screen space to object space
  3788. * @param source defines the screen space Vector3 to use
  3789. * @param viewportWidth defines the current width of the viewport
  3790. * @param viewportHeight defines the current height of the viewport
  3791. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3792. * @param view defines the view matrix to use
  3793. * @param projection defines the projection matrix to use
  3794. * @param result defines the Vector3 where to store the result
  3795. */
  3796. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3797. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3798. };
  3799. /**
  3800. * Unproject from screen space to object space
  3801. * @param sourceX defines the screen space x coordinate to use
  3802. * @param sourceY defines the screen space y coordinate to use
  3803. * @param sourceZ defines the screen space z coordinate to use
  3804. * @param viewportWidth defines the current width of the viewport
  3805. * @param viewportHeight defines the current height of the viewport
  3806. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3807. * @param view defines the view matrix to use
  3808. * @param projection defines the projection matrix to use
  3809. * @param result defines the Vector3 where to store the result
  3810. */
  3811. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3812. var matrix = MathTmp.Matrix[0];
  3813. world.multiplyToRef(view, matrix);
  3814. matrix.multiplyToRef(projection, matrix);
  3815. matrix.invert();
  3816. var screenSource = MathTmp.Vector3[0];
  3817. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3818. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3819. screenSource.z = 2 * sourceZ - 1.0;
  3820. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3821. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3822. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3823. result.scaleInPlace(1.0 / num);
  3824. }
  3825. };
  3826. /**
  3827. * Gets the minimal coordinate values between two Vector3
  3828. * @param left defines the first operand
  3829. * @param right defines the second operand
  3830. * @returns the new Vector3
  3831. */
  3832. Vector3.Minimize = function (left, right) {
  3833. var min = left.clone();
  3834. min.minimizeInPlace(right);
  3835. return min;
  3836. };
  3837. /**
  3838. * Gets the maximal coordinate values between two Vector3
  3839. * @param left defines the first operand
  3840. * @param right defines the second operand
  3841. * @returns the new Vector3
  3842. */
  3843. Vector3.Maximize = function (left, right) {
  3844. var max = left.clone();
  3845. max.maximizeInPlace(right);
  3846. return max;
  3847. };
  3848. /**
  3849. * Returns the distance between the vectors "value1" and "value2"
  3850. * @param value1 defines the first operand
  3851. * @param value2 defines the second operand
  3852. * @returns the distance
  3853. */
  3854. Vector3.Distance = function (value1, value2) {
  3855. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3856. };
  3857. /**
  3858. * Returns the squared distance between the vectors "value1" and "value2"
  3859. * @param value1 defines the first operand
  3860. * @param value2 defines the second operand
  3861. * @returns the squared distance
  3862. */
  3863. Vector3.DistanceSquared = function (value1, value2) {
  3864. var x = value1.x - value2.x;
  3865. var y = value1.y - value2.y;
  3866. var z = value1.z - value2.z;
  3867. return (x * x) + (y * y) + (z * z);
  3868. };
  3869. /**
  3870. * Returns a new Vector3 located at the center between "value1" and "value2"
  3871. * @param value1 defines the first operand
  3872. * @param value2 defines the second operand
  3873. * @returns the new Vector3
  3874. */
  3875. Vector3.Center = function (value1, value2) {
  3876. var center = value1.add(value2);
  3877. center.scaleInPlace(0.5);
  3878. return center;
  3879. };
  3880. /**
  3881. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3882. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3883. * to something in order to rotate it from its local system to the given target system
  3884. * Note: axis1, axis2 and axis3 are normalized during this operation
  3885. * @param axis1 defines the first axis
  3886. * @param axis2 defines the second axis
  3887. * @param axis3 defines the third axis
  3888. * @returns a new Vector3
  3889. */
  3890. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3891. var rotation = Vector3.Zero();
  3892. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3893. return rotation;
  3894. };
  3895. /**
  3896. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3897. * @param axis1 defines the first axis
  3898. * @param axis2 defines the second axis
  3899. * @param axis3 defines the third axis
  3900. * @param ref defines the Vector3 where to store the result
  3901. */
  3902. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3903. var quat = MathTmp.Quaternion[0];
  3904. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3905. quat.toEulerAnglesToRef(ref);
  3906. };
  3907. return Vector3;
  3908. }());
  3909. BABYLON.Vector3 = Vector3;
  3910. /**
  3911. * Vector4 class created for EulerAngle class conversion to Quaternion
  3912. */
  3913. var Vector4 = /** @class */ (function () {
  3914. /**
  3915. * Creates a Vector4 object from the given floats.
  3916. * @param x x value of the vector
  3917. * @param y y value of the vector
  3918. * @param z z value of the vector
  3919. * @param w w value of the vector
  3920. */
  3921. function Vector4(
  3922. /** x value of the vector */
  3923. x,
  3924. /** y value of the vector */
  3925. y,
  3926. /** z value of the vector */
  3927. z,
  3928. /** w value of the vector */
  3929. w) {
  3930. this.x = x;
  3931. this.y = y;
  3932. this.z = z;
  3933. this.w = w;
  3934. }
  3935. /**
  3936. * Returns the string with the Vector4 coordinates.
  3937. * @returns a string containing all the vector values
  3938. */
  3939. Vector4.prototype.toString = function () {
  3940. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3941. };
  3942. /**
  3943. * Returns the string "Vector4".
  3944. * @returns "Vector4"
  3945. */
  3946. Vector4.prototype.getClassName = function () {
  3947. return "Vector4";
  3948. };
  3949. /**
  3950. * Returns the Vector4 hash code.
  3951. * @returns a unique hash code
  3952. */
  3953. Vector4.prototype.getHashCode = function () {
  3954. var hash = this.x || 0;
  3955. hash = (hash * 397) ^ (this.y || 0);
  3956. hash = (hash * 397) ^ (this.z || 0);
  3957. hash = (hash * 397) ^ (this.w || 0);
  3958. return hash;
  3959. };
  3960. // Operators
  3961. /**
  3962. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3963. * @returns the resulting array
  3964. */
  3965. Vector4.prototype.asArray = function () {
  3966. var result = new Array();
  3967. this.toArray(result, 0);
  3968. return result;
  3969. };
  3970. /**
  3971. * Populates the given array from the given index with the Vector4 coordinates.
  3972. * @param array array to populate
  3973. * @param index index of the array to start at (default: 0)
  3974. * @returns the Vector4.
  3975. */
  3976. Vector4.prototype.toArray = function (array, index) {
  3977. if (index === undefined) {
  3978. index = 0;
  3979. }
  3980. array[index] = this.x;
  3981. array[index + 1] = this.y;
  3982. array[index + 2] = this.z;
  3983. array[index + 3] = this.w;
  3984. return this;
  3985. };
  3986. /**
  3987. * Adds the given vector to the current Vector4.
  3988. * @param otherVector the vector to add
  3989. * @returns the updated Vector4.
  3990. */
  3991. Vector4.prototype.addInPlace = function (otherVector) {
  3992. this.x += otherVector.x;
  3993. this.y += otherVector.y;
  3994. this.z += otherVector.z;
  3995. this.w += otherVector.w;
  3996. return this;
  3997. };
  3998. /**
  3999. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  4000. * @param otherVector the vector to add
  4001. * @returns the resulting vector
  4002. */
  4003. Vector4.prototype.add = function (otherVector) {
  4004. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  4005. };
  4006. /**
  4007. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  4008. * @param otherVector the vector to add
  4009. * @param result the vector to store the result
  4010. * @returns the current Vector4.
  4011. */
  4012. Vector4.prototype.addToRef = function (otherVector, result) {
  4013. result.x = this.x + otherVector.x;
  4014. result.y = this.y + otherVector.y;
  4015. result.z = this.z + otherVector.z;
  4016. result.w = this.w + otherVector.w;
  4017. return this;
  4018. };
  4019. /**
  4020. * Subtract in place the given vector from the current Vector4.
  4021. * @param otherVector the vector to subtract
  4022. * @returns the updated Vector4.
  4023. */
  4024. Vector4.prototype.subtractInPlace = function (otherVector) {
  4025. this.x -= otherVector.x;
  4026. this.y -= otherVector.y;
  4027. this.z -= otherVector.z;
  4028. this.w -= otherVector.w;
  4029. return this;
  4030. };
  4031. /**
  4032. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4033. * @param otherVector the vector to add
  4034. * @returns the new vector with the result
  4035. */
  4036. Vector4.prototype.subtract = function (otherVector) {
  4037. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4038. };
  4039. /**
  4040. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4041. * @param otherVector the vector to subtract
  4042. * @param result the vector to store the result
  4043. * @returns the current Vector4.
  4044. */
  4045. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4046. result.x = this.x - otherVector.x;
  4047. result.y = this.y - otherVector.y;
  4048. result.z = this.z - otherVector.z;
  4049. result.w = this.w - otherVector.w;
  4050. return this;
  4051. };
  4052. /**
  4053. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4054. */
  4055. /**
  4056. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4057. * @param x value to subtract
  4058. * @param y value to subtract
  4059. * @param z value to subtract
  4060. * @param w value to subtract
  4061. * @returns new vector containing the result
  4062. */
  4063. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4064. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4065. };
  4066. /**
  4067. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4068. * @param x value to subtract
  4069. * @param y value to subtract
  4070. * @param z value to subtract
  4071. * @param w value to subtract
  4072. * @param result the vector to store the result in
  4073. * @returns the current Vector4.
  4074. */
  4075. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4076. result.x = this.x - x;
  4077. result.y = this.y - y;
  4078. result.z = this.z - z;
  4079. result.w = this.w - w;
  4080. return this;
  4081. };
  4082. /**
  4083. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4084. * @returns a new vector with the negated values
  4085. */
  4086. Vector4.prototype.negate = function () {
  4087. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4088. };
  4089. /**
  4090. * Multiplies the current Vector4 coordinates by scale (float).
  4091. * @param scale the number to scale with
  4092. * @returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.scaleInPlace = function (scale) {
  4095. this.x *= scale;
  4096. this.y *= scale;
  4097. this.z *= scale;
  4098. this.w *= scale;
  4099. return this;
  4100. };
  4101. /**
  4102. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4103. * @param scale the number to scale with
  4104. * @returns a new vector with the result
  4105. */
  4106. Vector4.prototype.scale = function (scale) {
  4107. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4108. };
  4109. /**
  4110. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4111. * @param scale the number to scale with
  4112. * @param result a vector to store the result in
  4113. * @returns the current Vector4.
  4114. */
  4115. Vector4.prototype.scaleToRef = function (scale, result) {
  4116. result.x = this.x * scale;
  4117. result.y = this.y * scale;
  4118. result.z = this.z * scale;
  4119. result.w = this.w * scale;
  4120. return this;
  4121. };
  4122. /**
  4123. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4124. * @param scale defines the scale factor
  4125. * @param result defines the Vector4 object where to store the result
  4126. * @returns the unmodified current Vector4
  4127. */
  4128. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4129. result.x += this.x * scale;
  4130. result.y += this.y * scale;
  4131. result.z += this.z * scale;
  4132. result.w += this.w * scale;
  4133. return this;
  4134. };
  4135. /**
  4136. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4137. * @param otherVector the vector to compare against
  4138. * @returns true if they are equal
  4139. */
  4140. Vector4.prototype.equals = function (otherVector) {
  4141. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4142. };
  4143. /**
  4144. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4145. * @param otherVector vector to compare against
  4146. * @param epsilon (Default: very small number)
  4147. * @returns true if they are equal
  4148. */
  4149. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4150. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4151. return otherVector
  4152. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4153. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4154. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4155. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4156. };
  4157. /**
  4158. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4159. * @param x x value to compare against
  4160. * @param y y value to compare against
  4161. * @param z z value to compare against
  4162. * @param w w value to compare against
  4163. * @returns true if equal
  4164. */
  4165. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4166. return this.x === x && this.y === y && this.z === z && this.w === w;
  4167. };
  4168. /**
  4169. * Multiplies in place the current Vector4 by the given one.
  4170. * @param otherVector vector to multiple with
  4171. * @returns the updated Vector4.
  4172. */
  4173. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4174. this.x *= otherVector.x;
  4175. this.y *= otherVector.y;
  4176. this.z *= otherVector.z;
  4177. this.w *= otherVector.w;
  4178. return this;
  4179. };
  4180. /**
  4181. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4182. * @param otherVector vector to multiple with
  4183. * @returns resulting new vector
  4184. */
  4185. Vector4.prototype.multiply = function (otherVector) {
  4186. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4187. };
  4188. /**
  4189. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4190. * @param otherVector vector to multiple with
  4191. * @param result vector to store the result
  4192. * @returns the current Vector4.
  4193. */
  4194. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4195. result.x = this.x * otherVector.x;
  4196. result.y = this.y * otherVector.y;
  4197. result.z = this.z * otherVector.z;
  4198. result.w = this.w * otherVector.w;
  4199. return this;
  4200. };
  4201. /**
  4202. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4203. * @param x x value multiply with
  4204. * @param y y value multiply with
  4205. * @param z z value multiply with
  4206. * @param w w value multiply with
  4207. * @returns resulting new vector
  4208. */
  4209. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4210. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4211. };
  4212. /**
  4213. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4214. * @param otherVector vector to devide with
  4215. * @returns resulting new vector
  4216. */
  4217. Vector4.prototype.divide = function (otherVector) {
  4218. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4219. };
  4220. /**
  4221. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4222. * @param otherVector vector to devide with
  4223. * @param result vector to store the result
  4224. * @returns the current Vector4.
  4225. */
  4226. Vector4.prototype.divideToRef = function (otherVector, result) {
  4227. result.x = this.x / otherVector.x;
  4228. result.y = this.y / otherVector.y;
  4229. result.z = this.z / otherVector.z;
  4230. result.w = this.w / otherVector.w;
  4231. return this;
  4232. };
  4233. /**
  4234. * Divides the current Vector3 coordinates by the given ones.
  4235. * @param otherVector vector to devide with
  4236. * @returns the updated Vector3.
  4237. */
  4238. Vector4.prototype.divideInPlace = function (otherVector) {
  4239. return this.divideToRef(otherVector, this);
  4240. };
  4241. /**
  4242. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4243. * @param other defines the second operand
  4244. * @returns the current updated Vector4
  4245. */
  4246. Vector4.prototype.minimizeInPlace = function (other) {
  4247. if (other.x < this.x) {
  4248. this.x = other.x;
  4249. }
  4250. if (other.y < this.y) {
  4251. this.y = other.y;
  4252. }
  4253. if (other.z < this.z) {
  4254. this.z = other.z;
  4255. }
  4256. if (other.w < this.w) {
  4257. this.w = other.w;
  4258. }
  4259. return this;
  4260. };
  4261. /**
  4262. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4263. * @param other defines the second operand
  4264. * @returns the current updated Vector4
  4265. */
  4266. Vector4.prototype.maximizeInPlace = function (other) {
  4267. if (other.x > this.x) {
  4268. this.x = other.x;
  4269. }
  4270. if (other.y > this.y) {
  4271. this.y = other.y;
  4272. }
  4273. if (other.z > this.z) {
  4274. this.z = other.z;
  4275. }
  4276. if (other.w > this.w) {
  4277. this.w = other.w;
  4278. }
  4279. return this;
  4280. };
  4281. /**
  4282. * Gets a new Vector4 from current Vector4 floored values
  4283. * @returns a new Vector4
  4284. */
  4285. Vector4.prototype.floor = function () {
  4286. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4287. };
  4288. /**
  4289. * Gets a new Vector4 from current Vector3 floored values
  4290. * @returns a new Vector4
  4291. */
  4292. Vector4.prototype.fract = function () {
  4293. 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));
  4294. };
  4295. // Properties
  4296. /**
  4297. * Returns the Vector4 length (float).
  4298. * @returns the length
  4299. */
  4300. Vector4.prototype.length = function () {
  4301. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4302. };
  4303. /**
  4304. * Returns the Vector4 squared length (float).
  4305. * @returns the length squared
  4306. */
  4307. Vector4.prototype.lengthSquared = function () {
  4308. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4309. };
  4310. // Methods
  4311. /**
  4312. * Normalizes in place the Vector4.
  4313. * @returns the updated Vector4.
  4314. */
  4315. Vector4.prototype.normalize = function () {
  4316. var len = this.length();
  4317. if (len === 0) {
  4318. return this;
  4319. }
  4320. var num = 1.0 / len;
  4321. this.x *= num;
  4322. this.y *= num;
  4323. this.z *= num;
  4324. this.w *= num;
  4325. return this;
  4326. };
  4327. /**
  4328. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4329. * @returns this converted to a new vector3
  4330. */
  4331. Vector4.prototype.toVector3 = function () {
  4332. return new Vector3(this.x, this.y, this.z);
  4333. };
  4334. /**
  4335. * Returns a new Vector4 copied from the current one.
  4336. * @returns the new cloned vector
  4337. */
  4338. Vector4.prototype.clone = function () {
  4339. return new Vector4(this.x, this.y, this.z, this.w);
  4340. };
  4341. /**
  4342. * Updates the current Vector4 with the given one coordinates.
  4343. * @param source the source vector to copy from
  4344. * @returns the updated Vector4.
  4345. */
  4346. Vector4.prototype.copyFrom = function (source) {
  4347. this.x = source.x;
  4348. this.y = source.y;
  4349. this.z = source.z;
  4350. this.w = source.w;
  4351. return this;
  4352. };
  4353. /**
  4354. * Updates the current Vector4 coordinates with the given floats.
  4355. * @param x float to copy from
  4356. * @param y float to copy from
  4357. * @param z float to copy from
  4358. * @param w float to copy from
  4359. * @returns the updated Vector4.
  4360. */
  4361. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4362. this.x = x;
  4363. this.y = y;
  4364. this.z = z;
  4365. this.w = w;
  4366. return this;
  4367. };
  4368. /**
  4369. * Updates the current Vector4 coordinates with the given floats.
  4370. * @param x float to set from
  4371. * @param y float to set from
  4372. * @param z float to set from
  4373. * @param w float to set from
  4374. * @returns the updated Vector4.
  4375. */
  4376. Vector4.prototype.set = function (x, y, z, w) {
  4377. return this.copyFromFloats(x, y, z, w);
  4378. };
  4379. // Statics
  4380. /**
  4381. * Returns a new Vector4 set from the starting index of the given array.
  4382. * @param array the array to pull values from
  4383. * @param offset the offset into the array to start at
  4384. * @returns the new vector
  4385. */
  4386. Vector4.FromArray = function (array, offset) {
  4387. if (!offset) {
  4388. offset = 0;
  4389. }
  4390. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4391. };
  4392. /**
  4393. * Updates the given vector "result" from the starting index of the given array.
  4394. * @param array the array to pull values from
  4395. * @param offset the offset into the array to start at
  4396. * @param result the vector to store the result in
  4397. */
  4398. Vector4.FromArrayToRef = function (array, offset, result) {
  4399. result.x = array[offset];
  4400. result.y = array[offset + 1];
  4401. result.z = array[offset + 2];
  4402. result.w = array[offset + 3];
  4403. };
  4404. /**
  4405. * Updates the given vector "result" from the starting index of the given Float32Array.
  4406. * @param array the array to pull values from
  4407. * @param offset the offset into the array to start at
  4408. * @param result the vector to store the result in
  4409. */
  4410. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4411. Vector4.FromArrayToRef(array, offset, result);
  4412. };
  4413. /**
  4414. * Updates the given vector "result" coordinates from the given floats.
  4415. * @param x float to set from
  4416. * @param y float to set from
  4417. * @param z float to set from
  4418. * @param w float to set from
  4419. * @param result the vector to the floats in
  4420. */
  4421. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4422. result.x = x;
  4423. result.y = y;
  4424. result.z = z;
  4425. result.w = w;
  4426. };
  4427. /**
  4428. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4429. * @returns the new vector
  4430. */
  4431. Vector4.Zero = function () {
  4432. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4433. };
  4434. /**
  4435. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4436. * @returns the new vector
  4437. */
  4438. Vector4.One = function () {
  4439. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4440. };
  4441. /**
  4442. * Returns a new normalized Vector4 from the given one.
  4443. * @param vector the vector to normalize
  4444. * @returns the vector
  4445. */
  4446. Vector4.Normalize = function (vector) {
  4447. var result = Vector4.Zero();
  4448. Vector4.NormalizeToRef(vector, result);
  4449. return result;
  4450. };
  4451. /**
  4452. * Updates the given vector "result" from the normalization of the given one.
  4453. * @param vector the vector to normalize
  4454. * @param result the vector to store the result in
  4455. */
  4456. Vector4.NormalizeToRef = function (vector, result) {
  4457. result.copyFrom(vector);
  4458. result.normalize();
  4459. };
  4460. /**
  4461. * Returns a vector with the minimum values from the left and right vectors
  4462. * @param left left vector to minimize
  4463. * @param right right vector to minimize
  4464. * @returns a new vector with the minimum of the left and right vector values
  4465. */
  4466. Vector4.Minimize = function (left, right) {
  4467. var min = left.clone();
  4468. min.minimizeInPlace(right);
  4469. return min;
  4470. };
  4471. /**
  4472. * Returns a vector with the maximum values from the left and right vectors
  4473. * @param left left vector to maximize
  4474. * @param right right vector to maximize
  4475. * @returns a new vector with the maximum of the left and right vector values
  4476. */
  4477. Vector4.Maximize = function (left, right) {
  4478. var max = left.clone();
  4479. max.maximizeInPlace(right);
  4480. return max;
  4481. };
  4482. /**
  4483. * Returns the distance (float) between the vectors "value1" and "value2".
  4484. * @param value1 value to calulate the distance between
  4485. * @param value2 value to calulate the distance between
  4486. * @return the distance between the two vectors
  4487. */
  4488. Vector4.Distance = function (value1, value2) {
  4489. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4490. };
  4491. /**
  4492. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4493. * @param value1 value to calulate the distance between
  4494. * @param value2 value to calulate the distance between
  4495. * @return the distance between the two vectors squared
  4496. */
  4497. Vector4.DistanceSquared = function (value1, value2) {
  4498. var x = value1.x - value2.x;
  4499. var y = value1.y - value2.y;
  4500. var z = value1.z - value2.z;
  4501. var w = value1.w - value2.w;
  4502. return (x * x) + (y * y) + (z * z) + (w * w);
  4503. };
  4504. /**
  4505. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4506. * @param value1 value to calulate the center between
  4507. * @param value2 value to calulate the center between
  4508. * @return the center between the two vectors
  4509. */
  4510. Vector4.Center = function (value1, value2) {
  4511. var center = value1.add(value2);
  4512. center.scaleInPlace(0.5);
  4513. return center;
  4514. };
  4515. /**
  4516. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4517. * This methods computes transformed normalized direction vectors only.
  4518. * @param vector the vector to transform
  4519. * @param transformation the transformation matrix to apply
  4520. * @returns the new vector
  4521. */
  4522. Vector4.TransformNormal = function (vector, transformation) {
  4523. var result = Vector4.Zero();
  4524. Vector4.TransformNormalToRef(vector, transformation, result);
  4525. return result;
  4526. };
  4527. /**
  4528. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4529. * This methods computes transformed normalized direction vectors only.
  4530. * @param vector the vector to transform
  4531. * @param transformation the transformation matrix to apply
  4532. * @param result the vector to store the result in
  4533. */
  4534. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4535. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4536. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4537. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4538. result.x = x;
  4539. result.y = y;
  4540. result.z = z;
  4541. result.w = vector.w;
  4542. };
  4543. /**
  4544. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4545. * This methods computes transformed normalized direction vectors only.
  4546. * @param x value to transform
  4547. * @param y value to transform
  4548. * @param z value to transform
  4549. * @param w value to transform
  4550. * @param transformation the transformation matrix to apply
  4551. * @param result the vector to store the results in
  4552. */
  4553. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4554. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4555. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4556. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4557. result.w = w;
  4558. };
  4559. return Vector4;
  4560. }());
  4561. BABYLON.Vector4 = Vector4;
  4562. /**
  4563. * Size containing widht and height
  4564. */
  4565. var Size = /** @class */ (function () {
  4566. /**
  4567. * Creates a Size object from the given width and height (floats).
  4568. * @param width width of the new size
  4569. * @param height height of the new size
  4570. */
  4571. function Size(width, height) {
  4572. this.width = width;
  4573. this.height = height;
  4574. }
  4575. /**
  4576. * Returns a string with the Size width and height
  4577. * @returns a string with the Size width and height
  4578. */
  4579. Size.prototype.toString = function () {
  4580. return "{W: " + this.width + ", H: " + this.height + "}";
  4581. };
  4582. /**
  4583. * "Size"
  4584. * @returns the string "Size"
  4585. */
  4586. Size.prototype.getClassName = function () {
  4587. return "Size";
  4588. };
  4589. /**
  4590. * Returns the Size hash code.
  4591. * @returns a hash code for a unique width and height
  4592. */
  4593. Size.prototype.getHashCode = function () {
  4594. var hash = this.width || 0;
  4595. hash = (hash * 397) ^ (this.height || 0);
  4596. return hash;
  4597. };
  4598. /**
  4599. * Updates the current size from the given one.
  4600. * @param src the given size
  4601. */
  4602. Size.prototype.copyFrom = function (src) {
  4603. this.width = src.width;
  4604. this.height = src.height;
  4605. };
  4606. /**
  4607. * Updates in place the current Size from the given floats.
  4608. * @param width width of the new size
  4609. * @param height height of the new size
  4610. * @returns the updated Size.
  4611. */
  4612. Size.prototype.copyFromFloats = function (width, height) {
  4613. this.width = width;
  4614. this.height = height;
  4615. return this;
  4616. };
  4617. /**
  4618. * Updates in place the current Size from the given floats.
  4619. * @param width width to set
  4620. * @param height height to set
  4621. * @returns the updated Size.
  4622. */
  4623. Size.prototype.set = function (width, height) {
  4624. return this.copyFromFloats(width, height);
  4625. };
  4626. /**
  4627. * Multiplies the width and height by numbers
  4628. * @param w factor to multiple the width by
  4629. * @param h factor to multiple the height by
  4630. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4631. */
  4632. Size.prototype.multiplyByFloats = function (w, h) {
  4633. return new Size(this.width * w, this.height * h);
  4634. };
  4635. /**
  4636. * Clones the size
  4637. * @returns a new Size copied from the given one.
  4638. */
  4639. Size.prototype.clone = function () {
  4640. return new Size(this.width, this.height);
  4641. };
  4642. /**
  4643. * True if the current Size and the given one width and height are strictly equal.
  4644. * @param other the other size to compare against
  4645. * @returns True if the current Size and the given one width and height are strictly equal.
  4646. */
  4647. Size.prototype.equals = function (other) {
  4648. if (!other) {
  4649. return false;
  4650. }
  4651. return (this.width === other.width) && (this.height === other.height);
  4652. };
  4653. Object.defineProperty(Size.prototype, "surface", {
  4654. /**
  4655. * The surface of the Size : width * height (float).
  4656. */
  4657. get: function () {
  4658. return this.width * this.height;
  4659. },
  4660. enumerable: true,
  4661. configurable: true
  4662. });
  4663. /**
  4664. * Create a new size of zero
  4665. * @returns a new Size set to (0.0, 0.0)
  4666. */
  4667. Size.Zero = function () {
  4668. return new Size(0.0, 0.0);
  4669. };
  4670. /**
  4671. * Sums the width and height of two sizes
  4672. * @param otherSize size to add to this size
  4673. * @returns a new Size set as the addition result of the current Size and the given one.
  4674. */
  4675. Size.prototype.add = function (otherSize) {
  4676. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4677. return r;
  4678. };
  4679. /**
  4680. * Subtracts the width and height of two
  4681. * @param otherSize size to subtract to this size
  4682. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4683. */
  4684. Size.prototype.subtract = function (otherSize) {
  4685. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4686. return r;
  4687. };
  4688. /**
  4689. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4690. * @param start starting size to lerp between
  4691. * @param end end size to lerp between
  4692. * @param amount amount to lerp between the start and end values
  4693. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4694. */
  4695. Size.Lerp = function (start, end, amount) {
  4696. var w = start.width + ((end.width - start.width) * amount);
  4697. var h = start.height + ((end.height - start.height) * amount);
  4698. return new Size(w, h);
  4699. };
  4700. return Size;
  4701. }());
  4702. BABYLON.Size = Size;
  4703. /**
  4704. * Class used to store quaternion data
  4705. * @see https://en.wikipedia.org/wiki/Quaternion
  4706. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4707. */
  4708. var Quaternion = /** @class */ (function () {
  4709. /**
  4710. * Creates a new Quaternion from the given floats
  4711. * @param x defines the first component (0 by default)
  4712. * @param y defines the second component (0 by default)
  4713. * @param z defines the third component (0 by default)
  4714. * @param w defines the fourth component (1.0 by default)
  4715. */
  4716. function Quaternion(
  4717. /** defines the first component (0 by default) */
  4718. x,
  4719. /** defines the second component (0 by default) */
  4720. y,
  4721. /** defines the third component (0 by default) */
  4722. z,
  4723. /** defines the fourth component (1.0 by default) */
  4724. w) {
  4725. if (x === void 0) { x = 0.0; }
  4726. if (y === void 0) { y = 0.0; }
  4727. if (z === void 0) { z = 0.0; }
  4728. if (w === void 0) { w = 1.0; }
  4729. this.x = x;
  4730. this.y = y;
  4731. this.z = z;
  4732. this.w = w;
  4733. }
  4734. /**
  4735. * Gets a string representation for the current quaternion
  4736. * @returns a string with the Quaternion coordinates
  4737. */
  4738. Quaternion.prototype.toString = function () {
  4739. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4740. };
  4741. /**
  4742. * Gets the class name of the quaternion
  4743. * @returns the string "Quaternion"
  4744. */
  4745. Quaternion.prototype.getClassName = function () {
  4746. return "Quaternion";
  4747. };
  4748. /**
  4749. * Gets a hash code for this quaternion
  4750. * @returns the quaternion hash code
  4751. */
  4752. Quaternion.prototype.getHashCode = function () {
  4753. var hash = this.x || 0;
  4754. hash = (hash * 397) ^ (this.y || 0);
  4755. hash = (hash * 397) ^ (this.z || 0);
  4756. hash = (hash * 397) ^ (this.w || 0);
  4757. return hash;
  4758. };
  4759. /**
  4760. * Copy the quaternion to an array
  4761. * @returns a new array populated with 4 elements from the quaternion coordinates
  4762. */
  4763. Quaternion.prototype.asArray = function () {
  4764. return [this.x, this.y, this.z, this.w];
  4765. };
  4766. /**
  4767. * Check if two quaternions are equals
  4768. * @param otherQuaternion defines the second operand
  4769. * @return true if the current quaternion and the given one coordinates are strictly equals
  4770. */
  4771. Quaternion.prototype.equals = function (otherQuaternion) {
  4772. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4773. };
  4774. /**
  4775. * Clone the current quaternion
  4776. * @returns a new quaternion copied from the current one
  4777. */
  4778. Quaternion.prototype.clone = function () {
  4779. return new Quaternion(this.x, this.y, this.z, this.w);
  4780. };
  4781. /**
  4782. * Copy a quaternion to the current one
  4783. * @param other defines the other quaternion
  4784. * @returns the updated current quaternion
  4785. */
  4786. Quaternion.prototype.copyFrom = function (other) {
  4787. this.x = other.x;
  4788. this.y = other.y;
  4789. this.z = other.z;
  4790. this.w = other.w;
  4791. return this;
  4792. };
  4793. /**
  4794. * Updates the current quaternion with the given float coordinates
  4795. * @param x defines the x coordinate
  4796. * @param y defines the y coordinate
  4797. * @param z defines the z coordinate
  4798. * @param w defines the w coordinate
  4799. * @returns the updated current quaternion
  4800. */
  4801. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4802. this.x = x;
  4803. this.y = y;
  4804. this.z = z;
  4805. this.w = w;
  4806. return this;
  4807. };
  4808. /**
  4809. * Updates the current quaternion from the given float coordinates
  4810. * @param x defines the x coordinate
  4811. * @param y defines the y coordinate
  4812. * @param z defines the z coordinate
  4813. * @param w defines the w coordinate
  4814. * @returns the updated current quaternion
  4815. */
  4816. Quaternion.prototype.set = function (x, y, z, w) {
  4817. return this.copyFromFloats(x, y, z, w);
  4818. };
  4819. /**
  4820. * Adds two quaternions
  4821. * @param other defines the second operand
  4822. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4823. */
  4824. Quaternion.prototype.add = function (other) {
  4825. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4826. };
  4827. /**
  4828. * Add a quaternion to the current one
  4829. * @param other defines the quaternion to add
  4830. * @returns the current quaternion
  4831. */
  4832. Quaternion.prototype.addInPlace = function (other) {
  4833. this.x += other.x;
  4834. this.y += other.y;
  4835. this.z += other.z;
  4836. this.w += other.w;
  4837. return this;
  4838. };
  4839. /**
  4840. * Subtract two quaternions
  4841. * @param other defines the second operand
  4842. * @returns a new quaternion as the subtraction result of the given one from the current one
  4843. */
  4844. Quaternion.prototype.subtract = function (other) {
  4845. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4846. };
  4847. /**
  4848. * Multiplies the current quaternion by a scale factor
  4849. * @param value defines the scale factor
  4850. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4851. */
  4852. Quaternion.prototype.scale = function (value) {
  4853. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4854. };
  4855. /**
  4856. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4857. * @param scale defines the scale factor
  4858. * @param result defines the Quaternion object where to store the result
  4859. * @returns the unmodified current quaternion
  4860. */
  4861. Quaternion.prototype.scaleToRef = function (scale, result) {
  4862. result.x = this.x * scale;
  4863. result.y = this.y * scale;
  4864. result.z = this.z * scale;
  4865. result.w = this.w * scale;
  4866. return this;
  4867. };
  4868. /**
  4869. * Multiplies in place the current quaternion by a scale factor
  4870. * @param value defines the scale factor
  4871. * @returns the current modified quaternion
  4872. */
  4873. Quaternion.prototype.scaleInPlace = function (value) {
  4874. this.x *= value;
  4875. this.y *= value;
  4876. this.z *= value;
  4877. this.w *= value;
  4878. return this;
  4879. };
  4880. /**
  4881. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4882. * @param scale defines the scale factor
  4883. * @param result defines the Quaternion object where to store the result
  4884. * @returns the unmodified current quaternion
  4885. */
  4886. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4887. result.x += this.x * scale;
  4888. result.y += this.y * scale;
  4889. result.z += this.z * scale;
  4890. result.w += this.w * scale;
  4891. return this;
  4892. };
  4893. /**
  4894. * Multiplies two quaternions
  4895. * @param q1 defines the second operand
  4896. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4897. */
  4898. Quaternion.prototype.multiply = function (q1) {
  4899. var result = new Quaternion(0, 0, 0, 1.0);
  4900. this.multiplyToRef(q1, result);
  4901. return result;
  4902. };
  4903. /**
  4904. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4905. * @param q1 defines the second operand
  4906. * @param result defines the target quaternion
  4907. * @returns the current quaternion
  4908. */
  4909. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4910. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4911. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4912. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4913. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4914. result.copyFromFloats(x, y, z, w);
  4915. return this;
  4916. };
  4917. /**
  4918. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4919. * @param q1 defines the second operand
  4920. * @returns the currentupdated quaternion
  4921. */
  4922. Quaternion.prototype.multiplyInPlace = function (q1) {
  4923. this.multiplyToRef(q1, this);
  4924. return this;
  4925. };
  4926. /**
  4927. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4928. * @param ref defines the target quaternion
  4929. * @returns the current quaternion
  4930. */
  4931. Quaternion.prototype.conjugateToRef = function (ref) {
  4932. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4933. return this;
  4934. };
  4935. /**
  4936. * Conjugates in place (1-q) the current quaternion
  4937. * @returns the current updated quaternion
  4938. */
  4939. Quaternion.prototype.conjugateInPlace = function () {
  4940. this.x *= -1;
  4941. this.y *= -1;
  4942. this.z *= -1;
  4943. return this;
  4944. };
  4945. /**
  4946. * Conjugates in place (1-q) the current quaternion
  4947. * @returns a new quaternion
  4948. */
  4949. Quaternion.prototype.conjugate = function () {
  4950. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4951. return result;
  4952. };
  4953. /**
  4954. * Gets length of current quaternion
  4955. * @returns the quaternion length (float)
  4956. */
  4957. Quaternion.prototype.length = function () {
  4958. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4959. };
  4960. /**
  4961. * Normalize in place the current quaternion
  4962. * @returns the current updated quaternion
  4963. */
  4964. Quaternion.prototype.normalize = function () {
  4965. var length = 1.0 / this.length();
  4966. this.x *= length;
  4967. this.y *= length;
  4968. this.z *= length;
  4969. this.w *= length;
  4970. return this;
  4971. };
  4972. /**
  4973. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4974. * @param order is a reserved parameter and is ignore for now
  4975. * @returns a new Vector3 containing the Euler angles
  4976. */
  4977. Quaternion.prototype.toEulerAngles = function (order) {
  4978. if (order === void 0) { order = "YZX"; }
  4979. var result = Vector3.Zero();
  4980. this.toEulerAnglesToRef(result, order);
  4981. return result;
  4982. };
  4983. /**
  4984. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4985. * @param result defines the vector which will be filled with the Euler angles
  4986. * @param order is a reserved parameter and is ignore for now
  4987. * @returns the current unchanged quaternion
  4988. */
  4989. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4990. if (order === void 0) { order = "YZX"; }
  4991. var qz = this.z;
  4992. var qx = this.x;
  4993. var qy = this.y;
  4994. var qw = this.w;
  4995. var sqw = qw * qw;
  4996. var sqz = qz * qz;
  4997. var sqx = qx * qx;
  4998. var sqy = qy * qy;
  4999. var zAxisY = qy * qz - qx * qw;
  5000. var limit = .4999999;
  5001. if (zAxisY < -limit) {
  5002. result.y = 2 * Math.atan2(qy, qw);
  5003. result.x = Math.PI / 2;
  5004. result.z = 0;
  5005. }
  5006. else if (zAxisY > limit) {
  5007. result.y = 2 * Math.atan2(qy, qw);
  5008. result.x = -Math.PI / 2;
  5009. result.z = 0;
  5010. }
  5011. else {
  5012. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  5013. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  5014. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  5015. }
  5016. return this;
  5017. };
  5018. /**
  5019. * Updates the given rotation matrix with the current quaternion values
  5020. * @param result defines the target matrix
  5021. * @returns the current unchanged quaternion
  5022. */
  5023. Quaternion.prototype.toRotationMatrix = function (result) {
  5024. var xx = this.x * this.x;
  5025. var yy = this.y * this.y;
  5026. var zz = this.z * this.z;
  5027. var xy = this.x * this.y;
  5028. var zw = this.z * this.w;
  5029. var zx = this.z * this.x;
  5030. var yw = this.y * this.w;
  5031. var yz = this.y * this.z;
  5032. var xw = this.x * this.w;
  5033. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5034. result.m[1] = 2.0 * (xy + zw);
  5035. result.m[2] = 2.0 * (zx - yw);
  5036. result.m[3] = 0;
  5037. result.m[4] = 2.0 * (xy - zw);
  5038. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5039. result.m[6] = 2.0 * (yz + xw);
  5040. result.m[7] = 0;
  5041. result.m[8] = 2.0 * (zx + yw);
  5042. result.m[9] = 2.0 * (yz - xw);
  5043. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5044. result.m[11] = 0;
  5045. result.m[12] = 0;
  5046. result.m[13] = 0;
  5047. result.m[14] = 0;
  5048. result.m[15] = 1.0;
  5049. result._markAsUpdated();
  5050. return this;
  5051. };
  5052. /**
  5053. * Updates the current quaternion from the given rotation matrix values
  5054. * @param matrix defines the source matrix
  5055. * @returns the current updated quaternion
  5056. */
  5057. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5058. Quaternion.FromRotationMatrixToRef(matrix, this);
  5059. return this;
  5060. };
  5061. // Statics
  5062. /**
  5063. * Creates a new quaternion from a rotation matrix
  5064. * @param matrix defines the source matrix
  5065. * @returns a new quaternion created from the given rotation matrix values
  5066. */
  5067. Quaternion.FromRotationMatrix = function (matrix) {
  5068. var result = new Quaternion();
  5069. Quaternion.FromRotationMatrixToRef(matrix, result);
  5070. return result;
  5071. };
  5072. /**
  5073. * Updates the given quaternion with the given rotation matrix values
  5074. * @param matrix defines the source matrix
  5075. * @param result defines the target quaternion
  5076. */
  5077. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5078. var data = matrix.m;
  5079. var m11 = data[0], m12 = data[4], m13 = data[8];
  5080. var m21 = data[1], m22 = data[5], m23 = data[9];
  5081. var m31 = data[2], m32 = data[6], m33 = data[10];
  5082. var trace = m11 + m22 + m33;
  5083. var s;
  5084. if (trace > 0) {
  5085. s = 0.5 / Math.sqrt(trace + 1.0);
  5086. result.w = 0.25 / s;
  5087. result.x = (m32 - m23) * s;
  5088. result.y = (m13 - m31) * s;
  5089. result.z = (m21 - m12) * s;
  5090. }
  5091. else if (m11 > m22 && m11 > m33) {
  5092. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5093. result.w = (m32 - m23) / s;
  5094. result.x = 0.25 * s;
  5095. result.y = (m12 + m21) / s;
  5096. result.z = (m13 + m31) / s;
  5097. }
  5098. else if (m22 > m33) {
  5099. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5100. result.w = (m13 - m31) / s;
  5101. result.x = (m12 + m21) / s;
  5102. result.y = 0.25 * s;
  5103. result.z = (m23 + m32) / s;
  5104. }
  5105. else {
  5106. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5107. result.w = (m21 - m12) / s;
  5108. result.x = (m13 + m31) / s;
  5109. result.y = (m23 + m32) / s;
  5110. result.z = 0.25 * s;
  5111. }
  5112. };
  5113. /**
  5114. * Returns the dot product (float) between the quaternions "left" and "right"
  5115. * @param left defines the left operand
  5116. * @param right defines the right operand
  5117. * @returns the dot product
  5118. */
  5119. Quaternion.Dot = function (left, right) {
  5120. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5121. };
  5122. /**
  5123. * Checks if the two quaternions are close to each other
  5124. * @param quat0 defines the first quaternion to check
  5125. * @param quat1 defines the second quaternion to check
  5126. * @returns true if the two quaternions are close to each other
  5127. */
  5128. Quaternion.AreClose = function (quat0, quat1) {
  5129. var dot = Quaternion.Dot(quat0, quat1);
  5130. return dot >= 0;
  5131. };
  5132. /**
  5133. * Creates an empty quaternion
  5134. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5135. */
  5136. Quaternion.Zero = function () {
  5137. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5138. };
  5139. /**
  5140. * Inverse a given quaternion
  5141. * @param q defines the source quaternion
  5142. * @returns a new quaternion as the inverted current quaternion
  5143. */
  5144. Quaternion.Inverse = function (q) {
  5145. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5146. };
  5147. /**
  5148. * Creates an identity quaternion
  5149. * @returns the identity quaternion
  5150. */
  5151. Quaternion.Identity = function () {
  5152. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5153. };
  5154. /**
  5155. * Gets a boolean indicating if the given quaternion is identity
  5156. * @param quaternion defines the quaternion to check
  5157. * @returns true if the quaternion is identity
  5158. */
  5159. Quaternion.IsIdentity = function (quaternion) {
  5160. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5161. };
  5162. /**
  5163. * Creates a quaternion from a rotation around an axis
  5164. * @param axis defines the axis to use
  5165. * @param angle defines the angle to use
  5166. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5167. */
  5168. Quaternion.RotationAxis = function (axis, angle) {
  5169. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5170. };
  5171. /**
  5172. * Creates a rotation around an axis and stores it into the given quaternion
  5173. * @param axis defines the axis to use
  5174. * @param angle defines the angle to use
  5175. * @param result defines the target quaternion
  5176. * @returns the target quaternion
  5177. */
  5178. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5179. var sin = Math.sin(angle / 2);
  5180. axis.normalize();
  5181. result.w = Math.cos(angle / 2);
  5182. result.x = axis.x * sin;
  5183. result.y = axis.y * sin;
  5184. result.z = axis.z * sin;
  5185. return result;
  5186. };
  5187. /**
  5188. * Creates a new quaternion from data stored into an array
  5189. * @param array defines the data source
  5190. * @param offset defines the offset in the source array where the data starts
  5191. * @returns a new quaternion
  5192. */
  5193. Quaternion.FromArray = function (array, offset) {
  5194. if (!offset) {
  5195. offset = 0;
  5196. }
  5197. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5198. };
  5199. /**
  5200. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5201. * @param yaw defines the rotation around Y axis
  5202. * @param pitch defines the rotation around X axis
  5203. * @param roll defines the rotation around Z axis
  5204. * @returns the new quaternion
  5205. */
  5206. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5207. var q = new Quaternion();
  5208. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5209. return q;
  5210. };
  5211. /**
  5212. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5213. * @param yaw defines the rotation around Y axis
  5214. * @param pitch defines the rotation around X axis
  5215. * @param roll defines the rotation around Z axis
  5216. * @param result defines the target quaternion
  5217. */
  5218. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5219. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5220. var halfRoll = roll * 0.5;
  5221. var halfPitch = pitch * 0.5;
  5222. var halfYaw = yaw * 0.5;
  5223. var sinRoll = Math.sin(halfRoll);
  5224. var cosRoll = Math.cos(halfRoll);
  5225. var sinPitch = Math.sin(halfPitch);
  5226. var cosPitch = Math.cos(halfPitch);
  5227. var sinYaw = Math.sin(halfYaw);
  5228. var cosYaw = Math.cos(halfYaw);
  5229. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5230. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5231. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5232. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5233. };
  5234. /**
  5235. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5236. * @param alpha defines the rotation around first axis
  5237. * @param beta defines the rotation around second axis
  5238. * @param gamma defines the rotation around third axis
  5239. * @returns the new quaternion
  5240. */
  5241. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5242. var result = new Quaternion();
  5243. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5244. return result;
  5245. };
  5246. /**
  5247. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5248. * @param alpha defines the rotation around first axis
  5249. * @param beta defines the rotation around second axis
  5250. * @param gamma defines the rotation around third axis
  5251. * @param result defines the target quaternion
  5252. */
  5253. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5254. // Produces a quaternion from Euler angles in the z-x-z orientation
  5255. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5256. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5257. var halfBeta = beta * 0.5;
  5258. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5259. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5260. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5261. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5262. };
  5263. /**
  5264. * 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)
  5265. * @param axis1 defines the first axis
  5266. * @param axis2 defines the second axis
  5267. * @param axis3 defines the third axis
  5268. * @returns the new quaternion
  5269. */
  5270. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5271. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5272. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5273. return quat;
  5274. };
  5275. /**
  5276. * 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
  5277. * @param axis1 defines the first axis
  5278. * @param axis2 defines the second axis
  5279. * @param axis3 defines the third axis
  5280. * @param ref defines the target quaternion
  5281. */
  5282. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5283. var rotMat = MathTmp.Matrix[0];
  5284. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5285. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5286. };
  5287. /**
  5288. * Interpolates between two quaternions
  5289. * @param left defines first quaternion
  5290. * @param right defines second quaternion
  5291. * @param amount defines the gradient to use
  5292. * @returns the new interpolated quaternion
  5293. */
  5294. Quaternion.Slerp = function (left, right, amount) {
  5295. var result = Quaternion.Identity();
  5296. Quaternion.SlerpToRef(left, right, amount, result);
  5297. return result;
  5298. };
  5299. /**
  5300. * Interpolates between two quaternions and stores it into a target quaternion
  5301. * @param left defines first quaternion
  5302. * @param right defines second quaternion
  5303. * @param amount defines the gradient to use
  5304. * @param result defines the target quaternion
  5305. */
  5306. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5307. var num2;
  5308. var num3;
  5309. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5310. var flag = false;
  5311. if (num4 < 0) {
  5312. flag = true;
  5313. num4 = -num4;
  5314. }
  5315. if (num4 > 0.999999) {
  5316. num3 = 1 - amount;
  5317. num2 = flag ? -amount : amount;
  5318. }
  5319. else {
  5320. var num5 = Math.acos(num4);
  5321. var num6 = (1.0 / Math.sin(num5));
  5322. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5323. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5324. }
  5325. result.x = (num3 * left.x) + (num2 * right.x);
  5326. result.y = (num3 * left.y) + (num2 * right.y);
  5327. result.z = (num3 * left.z) + (num2 * right.z);
  5328. result.w = (num3 * left.w) + (num2 * right.w);
  5329. };
  5330. /**
  5331. * Interpolate between two quaternions using Hermite interpolation
  5332. * @param value1 defines first quaternion
  5333. * @param tangent1 defines the incoming tangent
  5334. * @param value2 defines second quaternion
  5335. * @param tangent2 defines the outgoing tangent
  5336. * @param amount defines the target quaternion
  5337. * @returns the new interpolated quaternion
  5338. */
  5339. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5340. var squared = amount * amount;
  5341. var cubed = amount * squared;
  5342. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5343. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5344. var part3 = (cubed - (2.0 * squared)) + amount;
  5345. var part4 = cubed - squared;
  5346. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5347. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5348. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5349. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5350. return new Quaternion(x, y, z, w);
  5351. };
  5352. return Quaternion;
  5353. }());
  5354. BABYLON.Quaternion = Quaternion;
  5355. /**
  5356. * Class used to store matrix data (4x4)
  5357. */
  5358. var Matrix = /** @class */ (function () {
  5359. /**
  5360. * Creates an empty matrix (filled with zeros)
  5361. */
  5362. function Matrix() {
  5363. this._isIdentity = false;
  5364. this._isIdentityDirty = true;
  5365. /**
  5366. * Gets or sets the internal data of the matrix
  5367. */
  5368. this.m = new Float32Array(16);
  5369. this._markAsUpdated();
  5370. }
  5371. /** @hidden */
  5372. Matrix.prototype._markAsUpdated = function () {
  5373. this.updateFlag = Matrix._updateFlagSeed++;
  5374. this._isIdentityDirty = true;
  5375. };
  5376. // Properties
  5377. /**
  5378. * Check if the current matrix is indentity
  5379. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5380. * @returns true is the matrix is the identity matrix
  5381. */
  5382. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5383. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5384. if (this._isIdentityDirty) {
  5385. this._isIdentityDirty = false;
  5386. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5387. this._isIdentity = false;
  5388. }
  5389. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5390. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5391. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5392. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5393. this._isIdentity = false;
  5394. }
  5395. else {
  5396. this._isIdentity = true;
  5397. }
  5398. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5399. this._isIdentity = false;
  5400. }
  5401. }
  5402. return this._isIdentity;
  5403. };
  5404. /**
  5405. * Gets the determinant of the matrix
  5406. * @returns the matrix determinant
  5407. */
  5408. Matrix.prototype.determinant = function () {
  5409. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5410. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5411. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5412. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5413. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5414. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5415. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5416. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5417. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5418. };
  5419. // Methods
  5420. /**
  5421. * Returns the matrix as a Float32Array
  5422. * @returns the matrix underlying array
  5423. */
  5424. Matrix.prototype.toArray = function () {
  5425. return this.m;
  5426. };
  5427. /**
  5428. * Returns the matrix as a Float32Array
  5429. * @returns the matrix underlying array.
  5430. */
  5431. Matrix.prototype.asArray = function () {
  5432. return this.toArray();
  5433. };
  5434. /**
  5435. * Inverts the current matrix in place
  5436. * @returns the current inverted matrix
  5437. */
  5438. Matrix.prototype.invert = function () {
  5439. this.invertToRef(this);
  5440. return this;
  5441. };
  5442. /**
  5443. * Sets all the matrix elements to zero
  5444. * @returns the current matrix
  5445. */
  5446. Matrix.prototype.reset = function () {
  5447. for (var index = 0; index < 16; index++) {
  5448. this.m[index] = 0.0;
  5449. }
  5450. this._markAsUpdated();
  5451. return this;
  5452. };
  5453. /**
  5454. * Adds the current matrix with a second one
  5455. * @param other defines the matrix to add
  5456. * @returns a new matrix as the addition of the current matrix and the given one
  5457. */
  5458. Matrix.prototype.add = function (other) {
  5459. var result = new Matrix();
  5460. this.addToRef(other, result);
  5461. return result;
  5462. };
  5463. /**
  5464. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5465. * @param other defines the matrix to add
  5466. * @param result defines the target matrix
  5467. * @returns the current matrix
  5468. */
  5469. Matrix.prototype.addToRef = function (other, result) {
  5470. for (var index = 0; index < 16; index++) {
  5471. result.m[index] = this.m[index] + other.m[index];
  5472. }
  5473. result._markAsUpdated();
  5474. return this;
  5475. };
  5476. /**
  5477. * Adds in place the given matrix to the current matrix
  5478. * @param other defines the second operand
  5479. * @returns the current updated matrix
  5480. */
  5481. Matrix.prototype.addToSelf = function (other) {
  5482. for (var index = 0; index < 16; index++) {
  5483. this.m[index] += other.m[index];
  5484. }
  5485. this._markAsUpdated();
  5486. return this;
  5487. };
  5488. /**
  5489. * Sets the given matrix to the current inverted Matrix
  5490. * @param other defines the target matrix
  5491. * @returns the unmodified current matrix
  5492. */
  5493. Matrix.prototype.invertToRef = function (other) {
  5494. var l1 = this.m[0];
  5495. var l2 = this.m[1];
  5496. var l3 = this.m[2];
  5497. var l4 = this.m[3];
  5498. var l5 = this.m[4];
  5499. var l6 = this.m[5];
  5500. var l7 = this.m[6];
  5501. var l8 = this.m[7];
  5502. var l9 = this.m[8];
  5503. var l10 = this.m[9];
  5504. var l11 = this.m[10];
  5505. var l12 = this.m[11];
  5506. var l13 = this.m[12];
  5507. var l14 = this.m[13];
  5508. var l15 = this.m[14];
  5509. var l16 = this.m[15];
  5510. var l17 = (l11 * l16) - (l12 * l15);
  5511. var l18 = (l10 * l16) - (l12 * l14);
  5512. var l19 = (l10 * l15) - (l11 * l14);
  5513. var l20 = (l9 * l16) - (l12 * l13);
  5514. var l21 = (l9 * l15) - (l11 * l13);
  5515. var l22 = (l9 * l14) - (l10 * l13);
  5516. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5517. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5518. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5519. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5520. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5521. var l28 = (l7 * l16) - (l8 * l15);
  5522. var l29 = (l6 * l16) - (l8 * l14);
  5523. var l30 = (l6 * l15) - (l7 * l14);
  5524. var l31 = (l5 * l16) - (l8 * l13);
  5525. var l32 = (l5 * l15) - (l7 * l13);
  5526. var l33 = (l5 * l14) - (l6 * l13);
  5527. var l34 = (l7 * l12) - (l8 * l11);
  5528. var l35 = (l6 * l12) - (l8 * l10);
  5529. var l36 = (l6 * l11) - (l7 * l10);
  5530. var l37 = (l5 * l12) - (l8 * l9);
  5531. var l38 = (l5 * l11) - (l7 * l9);
  5532. var l39 = (l5 * l10) - (l6 * l9);
  5533. other.m[0] = l23 * l27;
  5534. other.m[4] = l24 * l27;
  5535. other.m[8] = l25 * l27;
  5536. other.m[12] = l26 * l27;
  5537. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5538. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5539. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5540. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5541. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5542. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5543. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5544. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5545. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5546. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5547. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5548. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5549. other._markAsUpdated();
  5550. return this;
  5551. };
  5552. /**
  5553. * Inserts the translation vector (using 3 floats) in the current matrix
  5554. * @param x defines the 1st component of the translation
  5555. * @param y defines the 2nd component of the translation
  5556. * @param z defines the 3rd component of the translation
  5557. * @returns the current updated matrix
  5558. */
  5559. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5560. this.m[12] = x;
  5561. this.m[13] = y;
  5562. this.m[14] = z;
  5563. this._markAsUpdated();
  5564. return this;
  5565. };
  5566. /**
  5567. * Inserts the translation vector in the current matrix
  5568. * @param vector3 defines the translation to insert
  5569. * @returns the current updated matrix
  5570. */
  5571. Matrix.prototype.setTranslation = function (vector3) {
  5572. this.m[12] = vector3.x;
  5573. this.m[13] = vector3.y;
  5574. this.m[14] = vector3.z;
  5575. this._markAsUpdated();
  5576. return this;
  5577. };
  5578. /**
  5579. * Gets the translation value of the current matrix
  5580. * @returns a new Vector3 as the extracted translation from the matrix
  5581. */
  5582. Matrix.prototype.getTranslation = function () {
  5583. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5584. };
  5585. /**
  5586. * Fill a Vector3 with the extracted translation from the matrix
  5587. * @param result defines the Vector3 where to store the translation
  5588. * @returns the current matrix
  5589. */
  5590. Matrix.prototype.getTranslationToRef = function (result) {
  5591. result.x = this.m[12];
  5592. result.y = this.m[13];
  5593. result.z = this.m[14];
  5594. return this;
  5595. };
  5596. /**
  5597. * Remove rotation and scaling part from the matrix
  5598. * @returns the updated matrix
  5599. */
  5600. Matrix.prototype.removeRotationAndScaling = function () {
  5601. this.setRowFromFloats(0, 1, 0, 0, 0);
  5602. this.setRowFromFloats(1, 0, 1, 0, 0);
  5603. this.setRowFromFloats(2, 0, 0, 1, 0);
  5604. return this;
  5605. };
  5606. /**
  5607. * Multiply two matrices
  5608. * @param other defines the second operand
  5609. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5610. */
  5611. Matrix.prototype.multiply = function (other) {
  5612. var result = new Matrix();
  5613. this.multiplyToRef(other, result);
  5614. return result;
  5615. };
  5616. /**
  5617. * Copy the current matrix from the given one
  5618. * @param other defines the source matrix
  5619. * @returns the current updated matrix
  5620. */
  5621. Matrix.prototype.copyFrom = function (other) {
  5622. for (var index = 0; index < 16; index++) {
  5623. this.m[index] = other.m[index];
  5624. }
  5625. this._markAsUpdated();
  5626. return this;
  5627. };
  5628. /**
  5629. * Populates the given array from the starting index with the current matrix values
  5630. * @param array defines the target array
  5631. * @param offset defines the offset in the target array where to start storing values
  5632. * @returns the current matrix
  5633. */
  5634. Matrix.prototype.copyToArray = function (array, offset) {
  5635. if (offset === void 0) { offset = 0; }
  5636. for (var index = 0; index < 16; index++) {
  5637. array[offset + index] = this.m[index];
  5638. }
  5639. return this;
  5640. };
  5641. /**
  5642. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5643. * @param other defines the second operand
  5644. * @param result defines the matrix where to store the multiplication
  5645. * @returns the current matrix
  5646. */
  5647. Matrix.prototype.multiplyToRef = function (other, result) {
  5648. this.multiplyToArray(other, result.m, 0);
  5649. result._markAsUpdated();
  5650. return this;
  5651. };
  5652. /**
  5653. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5654. * @param other defines the second operand
  5655. * @param result defines the array where to store the multiplication
  5656. * @param offset defines the offset in the target array where to start storing values
  5657. * @returns the current matrix
  5658. */
  5659. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5660. var tm0 = this.m[0];
  5661. var tm1 = this.m[1];
  5662. var tm2 = this.m[2];
  5663. var tm3 = this.m[3];
  5664. var tm4 = this.m[4];
  5665. var tm5 = this.m[5];
  5666. var tm6 = this.m[6];
  5667. var tm7 = this.m[7];
  5668. var tm8 = this.m[8];
  5669. var tm9 = this.m[9];
  5670. var tm10 = this.m[10];
  5671. var tm11 = this.m[11];
  5672. var tm12 = this.m[12];
  5673. var tm13 = this.m[13];
  5674. var tm14 = this.m[14];
  5675. var tm15 = this.m[15];
  5676. var om0 = other.m[0];
  5677. var om1 = other.m[1];
  5678. var om2 = other.m[2];
  5679. var om3 = other.m[3];
  5680. var om4 = other.m[4];
  5681. var om5 = other.m[5];
  5682. var om6 = other.m[6];
  5683. var om7 = other.m[7];
  5684. var om8 = other.m[8];
  5685. var om9 = other.m[9];
  5686. var om10 = other.m[10];
  5687. var om11 = other.m[11];
  5688. var om12 = other.m[12];
  5689. var om13 = other.m[13];
  5690. var om14 = other.m[14];
  5691. var om15 = other.m[15];
  5692. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5693. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5694. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5695. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5696. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5697. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5698. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5699. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5700. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5701. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5702. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5703. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5704. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5705. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5706. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5707. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5708. return this;
  5709. };
  5710. /**
  5711. * Check equality between this matrix and a second one
  5712. * @param value defines the second matrix to compare
  5713. * @returns true is the current matrix and the given one values are strictly equal
  5714. */
  5715. Matrix.prototype.equals = function (value) {
  5716. return value &&
  5717. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5718. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5719. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5720. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5721. };
  5722. /**
  5723. * Clone the current matrix
  5724. * @returns a new matrix from the current matrix
  5725. */
  5726. Matrix.prototype.clone = function () {
  5727. 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]);
  5728. };
  5729. /**
  5730. * Returns the name of the current matrix class
  5731. * @returns the string "Matrix"
  5732. */
  5733. Matrix.prototype.getClassName = function () {
  5734. return "Matrix";
  5735. };
  5736. /**
  5737. * Gets the hash code of the current matrix
  5738. * @returns the hash code
  5739. */
  5740. Matrix.prototype.getHashCode = function () {
  5741. var hash = this.m[0] || 0;
  5742. for (var i = 1; i < 16; i++) {
  5743. hash = (hash * 397) ^ (this.m[i] || 0);
  5744. }
  5745. return hash;
  5746. };
  5747. /**
  5748. * Decomposes the current Matrix into a translation, rotation and scaling components
  5749. * @param scale defines the scale vector3 given as a reference to update
  5750. * @param rotation defines the rotation quaternion given as a reference to update
  5751. * @param translation defines the translation vector3 given as a reference to update
  5752. * @returns true if operation was successful
  5753. */
  5754. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5755. if (translation) {
  5756. translation.x = this.m[12];
  5757. translation.y = this.m[13];
  5758. translation.z = this.m[14];
  5759. }
  5760. scale = scale || MathTmp.Vector3[0];
  5761. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5762. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5763. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5764. if (this.determinant() <= 0) {
  5765. scale.y *= -1;
  5766. }
  5767. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5768. if (rotation) {
  5769. rotation.x = 0;
  5770. rotation.y = 0;
  5771. rotation.z = 0;
  5772. rotation.w = 1;
  5773. }
  5774. return false;
  5775. }
  5776. if (rotation) {
  5777. 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]);
  5778. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5779. }
  5780. return true;
  5781. };
  5782. /**
  5783. * Gets specific row of the matrix
  5784. * @param index defines the number of the row to get
  5785. * @returns the index-th row of the current matrix as a new Vector4
  5786. */
  5787. Matrix.prototype.getRow = function (index) {
  5788. if (index < 0 || index > 3) {
  5789. return null;
  5790. }
  5791. var i = index * 4;
  5792. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5793. };
  5794. /**
  5795. * Sets the index-th row of the current matrix to the vector4 values
  5796. * @param index defines the number of the row to set
  5797. * @param row defines the target vector4
  5798. * @returns the updated current matrix
  5799. */
  5800. Matrix.prototype.setRow = function (index, row) {
  5801. if (index < 0 || index > 3) {
  5802. return this;
  5803. }
  5804. var i = index * 4;
  5805. this.m[i + 0] = row.x;
  5806. this.m[i + 1] = row.y;
  5807. this.m[i + 2] = row.z;
  5808. this.m[i + 3] = row.w;
  5809. this._markAsUpdated();
  5810. return this;
  5811. };
  5812. /**
  5813. * Compute the transpose of the matrix
  5814. * @returns the new transposed matrix
  5815. */
  5816. Matrix.prototype.transpose = function () {
  5817. return Matrix.Transpose(this);
  5818. };
  5819. /**
  5820. * Compute the transpose of the matrix and store it in a given matrix
  5821. * @param result defines the target matrix
  5822. * @returns the current matrix
  5823. */
  5824. Matrix.prototype.transposeToRef = function (result) {
  5825. Matrix.TransposeToRef(this, result);
  5826. return this;
  5827. };
  5828. /**
  5829. * Sets the index-th row of the current matrix with the given 4 x float values
  5830. * @param index defines the row index
  5831. * @param x defines the x component to set
  5832. * @param y defines the y component to set
  5833. * @param z defines the z component to set
  5834. * @param w defines the w component to set
  5835. * @returns the updated current matrix
  5836. */
  5837. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5838. if (index < 0 || index > 3) {
  5839. return this;
  5840. }
  5841. var i = index * 4;
  5842. this.m[i + 0] = x;
  5843. this.m[i + 1] = y;
  5844. this.m[i + 2] = z;
  5845. this.m[i + 3] = w;
  5846. this._markAsUpdated();
  5847. return this;
  5848. };
  5849. /**
  5850. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5851. * @param scale defines the scale factor
  5852. * @returns a new matrix
  5853. */
  5854. Matrix.prototype.scale = function (scale) {
  5855. var result = new Matrix();
  5856. this.scaleToRef(scale, result);
  5857. return result;
  5858. };
  5859. /**
  5860. * Scale the current matrix values by a factor to a given result matrix
  5861. * @param scale defines the scale factor
  5862. * @param result defines the matrix to store the result
  5863. * @returns the current matrix
  5864. */
  5865. Matrix.prototype.scaleToRef = function (scale, result) {
  5866. for (var index = 0; index < 16; index++) {
  5867. result.m[index] = this.m[index] * scale;
  5868. }
  5869. result._markAsUpdated();
  5870. return this;
  5871. };
  5872. /**
  5873. * Scale the current matrix values by a factor and add the result to a given matrix
  5874. * @param scale defines the scale factor
  5875. * @param result defines the Matrix to store the result
  5876. * @returns the current matrix
  5877. */
  5878. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5879. for (var index = 0; index < 16; index++) {
  5880. result.m[index] += this.m[index] * scale;
  5881. }
  5882. result._markAsUpdated();
  5883. return this;
  5884. };
  5885. /**
  5886. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5887. * @param ref matrix to store the result
  5888. */
  5889. Matrix.prototype.toNormalMatrix = function (ref) {
  5890. this.invertToRef(ref);
  5891. ref.transpose();
  5892. var m = ref.m;
  5893. 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);
  5894. };
  5895. /**
  5896. * Gets only rotation part of the current matrix
  5897. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5898. */
  5899. Matrix.prototype.getRotationMatrix = function () {
  5900. var result = Matrix.Identity();
  5901. this.getRotationMatrixToRef(result);
  5902. return result;
  5903. };
  5904. /**
  5905. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5906. * @param result defines the target matrix to store data to
  5907. * @returns the current matrix
  5908. */
  5909. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5910. var m = this.m;
  5911. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5912. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5913. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5914. if (this.determinant() <= 0) {
  5915. sy *= -1;
  5916. }
  5917. if (sx === 0 || sy === 0 || sz === 0) {
  5918. Matrix.IdentityToRef(result);
  5919. }
  5920. else {
  5921. 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);
  5922. }
  5923. return this;
  5924. };
  5925. // Statics
  5926. /**
  5927. * Creates a matrix from an array
  5928. * @param array defines the source array
  5929. * @param offset defines an offset in the source array
  5930. * @returns a new Matrix set from the starting index of the given array
  5931. */
  5932. Matrix.FromArray = function (array, offset) {
  5933. var result = new Matrix();
  5934. if (!offset) {
  5935. offset = 0;
  5936. }
  5937. Matrix.FromArrayToRef(array, offset, result);
  5938. return result;
  5939. };
  5940. /**
  5941. * Copy the content of an array into a given matrix
  5942. * @param array defines the source array
  5943. * @param offset defines an offset in the source array
  5944. * @param result defines the target matrix
  5945. */
  5946. Matrix.FromArrayToRef = function (array, offset, result) {
  5947. for (var index = 0; index < 16; index++) {
  5948. result.m[index] = array[index + offset];
  5949. }
  5950. result._markAsUpdated();
  5951. };
  5952. /**
  5953. * Stores an array into a matrix after having multiplied each component by a given factor
  5954. * @param array defines the source array
  5955. * @param offset defines the offset in the source array
  5956. * @param scale defines the scaling factor
  5957. * @param result defines the target matrix
  5958. */
  5959. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5960. for (var index = 0; index < 16; index++) {
  5961. result.m[index] = array[index + offset] * scale;
  5962. }
  5963. result._markAsUpdated();
  5964. };
  5965. /**
  5966. * Stores a list of values (16) inside a given matrix
  5967. * @param initialM11 defines 1st value of 1st row
  5968. * @param initialM12 defines 2nd value of 1st row
  5969. * @param initialM13 defines 3rd value of 1st row
  5970. * @param initialM14 defines 4th value of 1st row
  5971. * @param initialM21 defines 1st value of 2nd row
  5972. * @param initialM22 defines 2nd value of 2nd row
  5973. * @param initialM23 defines 3rd value of 2nd row
  5974. * @param initialM24 defines 4th value of 2nd row
  5975. * @param initialM31 defines 1st value of 3rd row
  5976. * @param initialM32 defines 2nd value of 3rd row
  5977. * @param initialM33 defines 3rd value of 3rd row
  5978. * @param initialM34 defines 4th value of 3rd row
  5979. * @param initialM41 defines 1st value of 4th row
  5980. * @param initialM42 defines 2nd value of 4th row
  5981. * @param initialM43 defines 3rd value of 4th row
  5982. * @param initialM44 defines 4th value of 4th row
  5983. * @param result defines the target matrix
  5984. */
  5985. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5986. result.m[0] = initialM11;
  5987. result.m[1] = initialM12;
  5988. result.m[2] = initialM13;
  5989. result.m[3] = initialM14;
  5990. result.m[4] = initialM21;
  5991. result.m[5] = initialM22;
  5992. result.m[6] = initialM23;
  5993. result.m[7] = initialM24;
  5994. result.m[8] = initialM31;
  5995. result.m[9] = initialM32;
  5996. result.m[10] = initialM33;
  5997. result.m[11] = initialM34;
  5998. result.m[12] = initialM41;
  5999. result.m[13] = initialM42;
  6000. result.m[14] = initialM43;
  6001. result.m[15] = initialM44;
  6002. result._markAsUpdated();
  6003. };
  6004. Object.defineProperty(Matrix, "IdentityReadOnly", {
  6005. /**
  6006. * Gets an identity matrix that must not be updated
  6007. */
  6008. get: function () {
  6009. return Matrix._identityReadOnly;
  6010. },
  6011. enumerable: true,
  6012. configurable: true
  6013. });
  6014. /**
  6015. * Creates new matrix from a list of values (16)
  6016. * @param initialM11 defines 1st value of 1st row
  6017. * @param initialM12 defines 2nd value of 1st row
  6018. * @param initialM13 defines 3rd value of 1st row
  6019. * @param initialM14 defines 4th value of 1st row
  6020. * @param initialM21 defines 1st value of 2nd row
  6021. * @param initialM22 defines 2nd value of 2nd row
  6022. * @param initialM23 defines 3rd value of 2nd row
  6023. * @param initialM24 defines 4th value of 2nd row
  6024. * @param initialM31 defines 1st value of 3rd row
  6025. * @param initialM32 defines 2nd value of 3rd row
  6026. * @param initialM33 defines 3rd value of 3rd row
  6027. * @param initialM34 defines 4th value of 3rd row
  6028. * @param initialM41 defines 1st value of 4th row
  6029. * @param initialM42 defines 2nd value of 4th row
  6030. * @param initialM43 defines 3rd value of 4th row
  6031. * @param initialM44 defines 4th value of 4th row
  6032. * @returns the new matrix
  6033. */
  6034. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6035. var result = new Matrix();
  6036. result.m[0] = initialM11;
  6037. result.m[1] = initialM12;
  6038. result.m[2] = initialM13;
  6039. result.m[3] = initialM14;
  6040. result.m[4] = initialM21;
  6041. result.m[5] = initialM22;
  6042. result.m[6] = initialM23;
  6043. result.m[7] = initialM24;
  6044. result.m[8] = initialM31;
  6045. result.m[9] = initialM32;
  6046. result.m[10] = initialM33;
  6047. result.m[11] = initialM34;
  6048. result.m[12] = initialM41;
  6049. result.m[13] = initialM42;
  6050. result.m[14] = initialM43;
  6051. result.m[15] = initialM44;
  6052. return result;
  6053. };
  6054. /**
  6055. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6056. * @param scale defines the scale vector3
  6057. * @param rotation defines the rotation quaternion
  6058. * @param translation defines the translation vector3
  6059. * @returns a new matrix
  6060. */
  6061. Matrix.Compose = function (scale, rotation, translation) {
  6062. var result = Matrix.Identity();
  6063. Matrix.ComposeToRef(scale, rotation, translation, result);
  6064. return result;
  6065. };
  6066. /**
  6067. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6068. * @param scale defines the scale vector3
  6069. * @param rotation defines the rotation quaternion
  6070. * @param translation defines the translation vector3
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6074. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6075. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6076. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6077. result.setTranslation(translation);
  6078. };
  6079. /**
  6080. * Creates a new identity matrix
  6081. * @returns a new identity matrix
  6082. */
  6083. Matrix.Identity = function () {
  6084. 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);
  6085. };
  6086. /**
  6087. * Creates a new identity matrix and stores the result in a given matrix
  6088. * @param result defines the target matrix
  6089. */
  6090. Matrix.IdentityToRef = function (result) {
  6091. 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);
  6092. };
  6093. /**
  6094. * Creates a new zero matrix
  6095. * @returns a new zero matrix
  6096. */
  6097. Matrix.Zero = function () {
  6098. 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);
  6099. };
  6100. /**
  6101. * Creates a new rotation matrix for "angle" radians around the X axis
  6102. * @param angle defines the angle (in radians) to use
  6103. * @return the new matrix
  6104. */
  6105. Matrix.RotationX = function (angle) {
  6106. var result = new Matrix();
  6107. Matrix.RotationXToRef(angle, result);
  6108. return result;
  6109. };
  6110. /**
  6111. * Creates a new matrix as the invert of a given matrix
  6112. * @param source defines the source matrix
  6113. * @returns the new matrix
  6114. */
  6115. Matrix.Invert = function (source) {
  6116. var result = new Matrix();
  6117. source.invertToRef(result);
  6118. return result;
  6119. };
  6120. /**
  6121. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6122. * @param angle defines the angle (in radians) to use
  6123. * @param result defines the target matrix
  6124. */
  6125. Matrix.RotationXToRef = function (angle, result) {
  6126. var s = Math.sin(angle);
  6127. var c = Math.cos(angle);
  6128. result.m[0] = 1.0;
  6129. result.m[15] = 1.0;
  6130. result.m[5] = c;
  6131. result.m[10] = c;
  6132. result.m[9] = -s;
  6133. result.m[6] = s;
  6134. result.m[1] = 0.0;
  6135. result.m[2] = 0.0;
  6136. result.m[3] = 0.0;
  6137. result.m[4] = 0.0;
  6138. result.m[7] = 0.0;
  6139. result.m[8] = 0.0;
  6140. result.m[11] = 0.0;
  6141. result.m[12] = 0.0;
  6142. result.m[13] = 0.0;
  6143. result.m[14] = 0.0;
  6144. result._markAsUpdated();
  6145. };
  6146. /**
  6147. * Creates a new rotation matrix for "angle" radians around the Y axis
  6148. * @param angle defines the angle (in radians) to use
  6149. * @return the new matrix
  6150. */
  6151. Matrix.RotationY = function (angle) {
  6152. var result = new Matrix();
  6153. Matrix.RotationYToRef(angle, result);
  6154. return result;
  6155. };
  6156. /**
  6157. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6158. * @param angle defines the angle (in radians) to use
  6159. * @param result defines the target matrix
  6160. */
  6161. Matrix.RotationYToRef = function (angle, result) {
  6162. var s = Math.sin(angle);
  6163. var c = Math.cos(angle);
  6164. result.m[5] = 1.0;
  6165. result.m[15] = 1.0;
  6166. result.m[0] = c;
  6167. result.m[2] = -s;
  6168. result.m[8] = s;
  6169. result.m[10] = c;
  6170. result.m[1] = 0.0;
  6171. result.m[3] = 0.0;
  6172. result.m[4] = 0.0;
  6173. result.m[6] = 0.0;
  6174. result.m[7] = 0.0;
  6175. result.m[9] = 0.0;
  6176. result.m[11] = 0.0;
  6177. result.m[12] = 0.0;
  6178. result.m[13] = 0.0;
  6179. result.m[14] = 0.0;
  6180. result._markAsUpdated();
  6181. };
  6182. /**
  6183. * Creates a new rotation matrix for "angle" radians around the Z axis
  6184. * @param angle defines the angle (in radians) to use
  6185. * @return the new matrix
  6186. */
  6187. Matrix.RotationZ = function (angle) {
  6188. var result = new Matrix();
  6189. Matrix.RotationZToRef(angle, result);
  6190. return result;
  6191. };
  6192. /**
  6193. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6194. * @param angle defines the angle (in radians) to use
  6195. * @param result defines the target matrix
  6196. */
  6197. Matrix.RotationZToRef = function (angle, result) {
  6198. var s = Math.sin(angle);
  6199. var c = Math.cos(angle);
  6200. result.m[10] = 1.0;
  6201. result.m[15] = 1.0;
  6202. result.m[0] = c;
  6203. result.m[1] = s;
  6204. result.m[4] = -s;
  6205. result.m[5] = c;
  6206. result.m[2] = 0.0;
  6207. result.m[3] = 0.0;
  6208. result.m[6] = 0.0;
  6209. result.m[7] = 0.0;
  6210. result.m[8] = 0.0;
  6211. result.m[9] = 0.0;
  6212. result.m[11] = 0.0;
  6213. result.m[12] = 0.0;
  6214. result.m[13] = 0.0;
  6215. result.m[14] = 0.0;
  6216. result._markAsUpdated();
  6217. };
  6218. /**
  6219. * Creates a new rotation matrix for "angle" radians around the given axis
  6220. * @param axis defines the axis to use
  6221. * @param angle defines the angle (in radians) to use
  6222. * @return the new matrix
  6223. */
  6224. Matrix.RotationAxis = function (axis, angle) {
  6225. var result = Matrix.Zero();
  6226. Matrix.RotationAxisToRef(axis, angle, result);
  6227. return result;
  6228. };
  6229. /**
  6230. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6231. * @param axis defines the axis to use
  6232. * @param angle defines the angle (in radians) to use
  6233. * @param result defines the target matrix
  6234. */
  6235. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6236. var s = Math.sin(-angle);
  6237. var c = Math.cos(-angle);
  6238. var c1 = 1 - c;
  6239. axis.normalize();
  6240. result.m[0] = (axis.x * axis.x) * c1 + c;
  6241. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6242. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6243. result.m[3] = 0.0;
  6244. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6245. result.m[5] = (axis.y * axis.y) * c1 + c;
  6246. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6247. result.m[7] = 0.0;
  6248. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6249. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6250. result.m[10] = (axis.z * axis.z) * c1 + c;
  6251. result.m[11] = 0.0;
  6252. result.m[15] = 1.0;
  6253. result._markAsUpdated();
  6254. };
  6255. /**
  6256. * Creates a rotation matrix
  6257. * @param yaw defines the yaw angle in radians (Y axis)
  6258. * @param pitch defines the pitch angle in radians (X axis)
  6259. * @param roll defines the roll angle in radians (X axis)
  6260. * @returns the new rotation matrix
  6261. */
  6262. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6263. var result = new Matrix();
  6264. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6265. return result;
  6266. };
  6267. /**
  6268. * Creates a rotation matrix and stores it in a given matrix
  6269. * @param yaw defines the yaw angle in radians (Y axis)
  6270. * @param pitch defines the pitch angle in radians (X axis)
  6271. * @param roll defines the roll angle in radians (X axis)
  6272. * @param result defines the target matrix
  6273. */
  6274. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6275. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6276. this._tempQuaternion.toRotationMatrix(result);
  6277. };
  6278. /**
  6279. * Creates a scaling matrix
  6280. * @param x defines the scale factor on X axis
  6281. * @param y defines the scale factor on Y axis
  6282. * @param z defines the scale factor on Z axis
  6283. * @returns the new matrix
  6284. */
  6285. Matrix.Scaling = function (x, y, z) {
  6286. var result = Matrix.Zero();
  6287. Matrix.ScalingToRef(x, y, z, result);
  6288. return result;
  6289. };
  6290. /**
  6291. * Creates a scaling matrix and stores it in a given matrix
  6292. * @param x defines the scale factor on X axis
  6293. * @param y defines the scale factor on Y axis
  6294. * @param z defines the scale factor on Z axis
  6295. * @param result defines the target matrix
  6296. */
  6297. Matrix.ScalingToRef = function (x, y, z, result) {
  6298. result.m[0] = x;
  6299. result.m[1] = 0.0;
  6300. result.m[2] = 0.0;
  6301. result.m[3] = 0.0;
  6302. result.m[4] = 0.0;
  6303. result.m[5] = y;
  6304. result.m[6] = 0.0;
  6305. result.m[7] = 0.0;
  6306. result.m[8] = 0.0;
  6307. result.m[9] = 0.0;
  6308. result.m[10] = z;
  6309. result.m[11] = 0.0;
  6310. result.m[12] = 0.0;
  6311. result.m[13] = 0.0;
  6312. result.m[14] = 0.0;
  6313. result.m[15] = 1.0;
  6314. result._markAsUpdated();
  6315. };
  6316. /**
  6317. * Creates a translation matrix
  6318. * @param x defines the translation on X axis
  6319. * @param y defines the translation on Y axis
  6320. * @param z defines the translationon Z axis
  6321. * @returns the new matrix
  6322. */
  6323. Matrix.Translation = function (x, y, z) {
  6324. var result = Matrix.Identity();
  6325. Matrix.TranslationToRef(x, y, z, result);
  6326. return result;
  6327. };
  6328. /**
  6329. * Creates a translation matrix and stores it in a given matrix
  6330. * @param x defines the translation on X axis
  6331. * @param y defines the translation on Y axis
  6332. * @param z defines the translationon Z axis
  6333. * @param result defines the target matrix
  6334. */
  6335. Matrix.TranslationToRef = function (x, y, z, result) {
  6336. 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);
  6337. };
  6338. /**
  6339. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6340. * @param startValue defines the start value
  6341. * @param endValue defines the end value
  6342. * @param gradient defines the gradient factor
  6343. * @returns the new matrix
  6344. */
  6345. Matrix.Lerp = function (startValue, endValue, gradient) {
  6346. var result = Matrix.Zero();
  6347. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6348. return result;
  6349. };
  6350. /**
  6351. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6352. * @param startValue defines the start value
  6353. * @param endValue defines the end value
  6354. * @param gradient defines the gradient factor
  6355. * @param result defines the Matrix object where to store data
  6356. */
  6357. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6358. for (var index = 0; index < 16; index++) {
  6359. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6360. }
  6361. result._markAsUpdated();
  6362. };
  6363. /**
  6364. * Builds a new matrix whose values are computed by:
  6365. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6366. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6367. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6368. * @param startValue defines the first matrix
  6369. * @param endValue defines the second matrix
  6370. * @param gradient defines the gradient between the two matrices
  6371. * @returns the new matrix
  6372. */
  6373. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6374. var result = Matrix.Zero();
  6375. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6376. return result;
  6377. };
  6378. /**
  6379. * Update a matrix to values which are computed by:
  6380. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6381. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6382. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6383. * @param startValue defines the first matrix
  6384. * @param endValue defines the second matrix
  6385. * @param gradient defines the gradient between the two matrices
  6386. * @param result defines the target matrix
  6387. */
  6388. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6389. var startScale = MathTmp.Vector3[0];
  6390. var startRotation = MathTmp.Quaternion[0];
  6391. var startTranslation = MathTmp.Vector3[1];
  6392. startValue.decompose(startScale, startRotation, startTranslation);
  6393. var endScale = MathTmp.Vector3[2];
  6394. var endRotation = MathTmp.Quaternion[1];
  6395. var endTranslation = MathTmp.Vector3[3];
  6396. endValue.decompose(endScale, endRotation, endTranslation);
  6397. var resultScale = MathTmp.Vector3[4];
  6398. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6399. var resultRotation = MathTmp.Quaternion[2];
  6400. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6401. var resultTranslation = MathTmp.Vector3[5];
  6402. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6403. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6404. };
  6405. /**
  6406. * 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"
  6407. * This function works in left handed mode
  6408. * @param eye defines the final position of the entity
  6409. * @param target defines where the entity should look at
  6410. * @param up defines the up vector for the entity
  6411. * @returns the new matrix
  6412. */
  6413. Matrix.LookAtLH = function (eye, target, up) {
  6414. var result = Matrix.Zero();
  6415. Matrix.LookAtLHToRef(eye, target, up, result);
  6416. return result;
  6417. };
  6418. /**
  6419. * 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".
  6420. * This function works in left handed mode
  6421. * @param eye defines the final position of the entity
  6422. * @param target defines where the entity should look at
  6423. * @param up defines the up vector for the entity
  6424. * @param result defines the target matrix
  6425. */
  6426. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6427. // Z axis
  6428. target.subtractToRef(eye, this._zAxis);
  6429. this._zAxis.normalize();
  6430. // X axis
  6431. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6432. if (this._xAxis.lengthSquared() === 0) {
  6433. this._xAxis.x = 1.0;
  6434. }
  6435. else {
  6436. this._xAxis.normalize();
  6437. }
  6438. // Y axis
  6439. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6440. this._yAxis.normalize();
  6441. // Eye angles
  6442. var ex = -Vector3.Dot(this._xAxis, eye);
  6443. var ey = -Vector3.Dot(this._yAxis, eye);
  6444. var ez = -Vector3.Dot(this._zAxis, eye);
  6445. 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);
  6446. };
  6447. /**
  6448. * 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"
  6449. * This function works in right handed mode
  6450. * @param eye defines the final position of the entity
  6451. * @param target defines where the entity should look at
  6452. * @param up defines the up vector for the entity
  6453. * @returns the new matrix
  6454. */
  6455. Matrix.LookAtRH = function (eye, target, up) {
  6456. var result = Matrix.Zero();
  6457. Matrix.LookAtRHToRef(eye, target, up, result);
  6458. return result;
  6459. };
  6460. /**
  6461. * 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".
  6462. * This function works in right handed mode
  6463. * @param eye defines the final position of the entity
  6464. * @param target defines where the entity should look at
  6465. * @param up defines the up vector for the entity
  6466. * @param result defines the target matrix
  6467. */
  6468. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6469. // Z axis
  6470. eye.subtractToRef(target, this._zAxis);
  6471. this._zAxis.normalize();
  6472. // X axis
  6473. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6474. if (this._xAxis.lengthSquared() === 0) {
  6475. this._xAxis.x = 1.0;
  6476. }
  6477. else {
  6478. this._xAxis.normalize();
  6479. }
  6480. // Y axis
  6481. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6482. this._yAxis.normalize();
  6483. // Eye angles
  6484. var ex = -Vector3.Dot(this._xAxis, eye);
  6485. var ey = -Vector3.Dot(this._yAxis, eye);
  6486. var ez = -Vector3.Dot(this._zAxis, eye);
  6487. 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);
  6488. };
  6489. /**
  6490. * Create a left-handed orthographic projection matrix
  6491. * @param width defines the viewport width
  6492. * @param height defines the viewport height
  6493. * @param znear defines the near clip plane
  6494. * @param zfar defines the far clip plane
  6495. * @returns a new matrix as a left-handed orthographic projection matrix
  6496. */
  6497. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6498. var matrix = Matrix.Zero();
  6499. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6500. return matrix;
  6501. };
  6502. /**
  6503. * Store a left-handed orthographic projection to a given matrix
  6504. * @param width defines the viewport width
  6505. * @param height defines the viewport height
  6506. * @param znear defines the near clip plane
  6507. * @param zfar defines the far clip plane
  6508. * @param result defines the target matrix
  6509. */
  6510. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6511. var n = znear;
  6512. var f = zfar;
  6513. var a = 2.0 / width;
  6514. var b = 2.0 / height;
  6515. var c = 2.0 / (f - n);
  6516. var d = -(f + n) / (f - n);
  6517. 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);
  6518. };
  6519. /**
  6520. * Create a left-handed orthographic projection matrix
  6521. * @param left defines the viewport left coordinate
  6522. * @param right defines the viewport right coordinate
  6523. * @param bottom defines the viewport bottom coordinate
  6524. * @param top defines the viewport top coordinate
  6525. * @param znear defines the near clip plane
  6526. * @param zfar defines the far clip plane
  6527. * @returns a new matrix as a left-handed orthographic projection matrix
  6528. */
  6529. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6530. var matrix = Matrix.Zero();
  6531. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6532. return matrix;
  6533. };
  6534. /**
  6535. * Stores a left-handed orthographic projection into a given matrix
  6536. * @param left defines the viewport left coordinate
  6537. * @param right defines the viewport right coordinate
  6538. * @param bottom defines the viewport bottom coordinate
  6539. * @param top defines the viewport top coordinate
  6540. * @param znear defines the near clip plane
  6541. * @param zfar defines the far clip plane
  6542. * @param result defines the target matrix
  6543. */
  6544. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6545. var n = znear;
  6546. var f = zfar;
  6547. var a = 2.0 / (right - left);
  6548. var b = 2.0 / (top - bottom);
  6549. var c = 2.0 / (f - n);
  6550. var d = -(f + n) / (f - n);
  6551. var i0 = (left + right) / (left - right);
  6552. var i1 = (top + bottom) / (bottom - top);
  6553. 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);
  6554. };
  6555. /**
  6556. * Creates a right-handed orthographic projection matrix
  6557. * @param left defines the viewport left coordinate
  6558. * @param right defines the viewport right coordinate
  6559. * @param bottom defines the viewport bottom coordinate
  6560. * @param top defines the viewport top coordinate
  6561. * @param znear defines the near clip plane
  6562. * @param zfar defines the far clip plane
  6563. * @returns a new matrix as a right-handed orthographic projection matrix
  6564. */
  6565. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6566. var matrix = Matrix.Zero();
  6567. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6568. return matrix;
  6569. };
  6570. /**
  6571. * Stores a right-handed orthographic projection into a given matrix
  6572. * @param left defines the viewport left coordinate
  6573. * @param right defines the viewport right coordinate
  6574. * @param bottom defines the viewport bottom coordinate
  6575. * @param top defines the viewport top coordinate
  6576. * @param znear defines the near clip plane
  6577. * @param zfar defines the far clip plane
  6578. * @param result defines the target matrix
  6579. */
  6580. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6581. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6582. result.m[10] *= -1.0;
  6583. };
  6584. /**
  6585. * Creates a left-handed perspective projection matrix
  6586. * @param width defines the viewport width
  6587. * @param height defines the viewport height
  6588. * @param znear defines the near clip plane
  6589. * @param zfar defines the far clip plane
  6590. * @returns a new matrix as a left-handed perspective projection matrix
  6591. */
  6592. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6593. var matrix = Matrix.Zero();
  6594. var n = znear;
  6595. var f = zfar;
  6596. var a = 2.0 * n / width;
  6597. var b = 2.0 * n / height;
  6598. var c = (f + n) / (f - n);
  6599. var d = -2.0 * f * n / (f - n);
  6600. 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);
  6601. return matrix;
  6602. };
  6603. /**
  6604. * Creates a left-handed perspective projection matrix
  6605. * @param fov defines the horizontal field of view
  6606. * @param aspect defines the aspect ratio
  6607. * @param znear defines the near clip plane
  6608. * @param zfar defines the far clip plane
  6609. * @returns a new matrix as a left-handed perspective projection matrix
  6610. */
  6611. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6612. var matrix = Matrix.Zero();
  6613. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6614. return matrix;
  6615. };
  6616. /**
  6617. * Stores a left-handed perspective projection into a given matrix
  6618. * @param fov defines the horizontal field of view
  6619. * @param aspect defines the aspect ratio
  6620. * @param znear defines the near clip plane
  6621. * @param zfar defines the far clip plane
  6622. * @param result defines the target matrix
  6623. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6624. */
  6625. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6626. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6627. var n = znear;
  6628. var f = zfar;
  6629. var t = 1.0 / (Math.tan(fov * 0.5));
  6630. var a = isVerticalFovFixed ? (t / aspect) : t;
  6631. var b = isVerticalFovFixed ? t : (t * aspect);
  6632. var c = (f + n) / (f - n);
  6633. var d = -2.0 * f * n / (f - n);
  6634. 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);
  6635. };
  6636. /**
  6637. * Creates a right-handed perspective projection matrix
  6638. * @param fov defines the horizontal field of view
  6639. * @param aspect defines the aspect ratio
  6640. * @param znear defines the near clip plane
  6641. * @param zfar defines the far clip plane
  6642. * @returns a new matrix as a right-handed perspective projection matrix
  6643. */
  6644. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6645. var matrix = Matrix.Zero();
  6646. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6647. return matrix;
  6648. };
  6649. /**
  6650. * Stores a right-handed perspective projection into a given matrix
  6651. * @param fov defines the horizontal field of view
  6652. * @param aspect defines the aspect ratio
  6653. * @param znear defines the near clip plane
  6654. * @param zfar defines the far clip plane
  6655. * @param result defines the target matrix
  6656. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6657. */
  6658. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6659. //alternatively this could be expressed as:
  6660. // m = PerspectiveFovLHToRef
  6661. // m[10] *= -1.0;
  6662. // m[11] *= -1.0;
  6663. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6664. var n = znear;
  6665. var f = zfar;
  6666. var t = 1.0 / (Math.tan(fov * 0.5));
  6667. var a = isVerticalFovFixed ? (t / aspect) : t;
  6668. var b = isVerticalFovFixed ? t : (t * aspect);
  6669. var c = -(f + n) / (f - n);
  6670. var d = -2 * f * n / (f - n);
  6671. 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);
  6672. };
  6673. /**
  6674. * Stores a perspective projection for WebVR info a given matrix
  6675. * @param fov defines the field of view
  6676. * @param znear defines the near clip plane
  6677. * @param zfar defines the far clip plane
  6678. * @param result defines the target matrix
  6679. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6680. */
  6681. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6682. if (rightHanded === void 0) { rightHanded = false; }
  6683. var rightHandedFactor = rightHanded ? -1 : 1;
  6684. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6685. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6686. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6687. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6688. var xScale = 2.0 / (leftTan + rightTan);
  6689. var yScale = 2.0 / (upTan + downTan);
  6690. result.m[0] = xScale;
  6691. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6692. result.m[5] = yScale;
  6693. result.m[6] = result.m[7] = 0.0;
  6694. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6695. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6696. result.m[10] = -zfar / (znear - zfar);
  6697. result.m[11] = 1.0 * rightHandedFactor;
  6698. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6699. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6700. result._markAsUpdated();
  6701. };
  6702. /**
  6703. * Computes a complete transformation matrix
  6704. * @param viewport defines the viewport to use
  6705. * @param world defines the world matrix
  6706. * @param view defines the view matrix
  6707. * @param projection defines the projection matrix
  6708. * @param zmin defines the near clip plane
  6709. * @param zmax defines the far clip plane
  6710. * @returns the transformation matrix
  6711. */
  6712. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6713. var cw = viewport.width;
  6714. var ch = viewport.height;
  6715. var cx = viewport.x;
  6716. var cy = viewport.y;
  6717. 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);
  6718. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6719. };
  6720. /**
  6721. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6722. * @param matrix defines the matrix to use
  6723. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6724. */
  6725. Matrix.GetAsMatrix2x2 = function (matrix) {
  6726. return new Float32Array([
  6727. matrix.m[0], matrix.m[1],
  6728. matrix.m[4], matrix.m[5]
  6729. ]);
  6730. };
  6731. /**
  6732. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6733. * @param matrix defines the matrix to use
  6734. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6735. */
  6736. Matrix.GetAsMatrix3x3 = function (matrix) {
  6737. return new Float32Array([
  6738. matrix.m[0], matrix.m[1], matrix.m[2],
  6739. matrix.m[4], matrix.m[5], matrix.m[6],
  6740. matrix.m[8], matrix.m[9], matrix.m[10]
  6741. ]);
  6742. };
  6743. /**
  6744. * Compute the transpose of a given matrix
  6745. * @param matrix defines the matrix to transpose
  6746. * @returns the new matrix
  6747. */
  6748. Matrix.Transpose = function (matrix) {
  6749. var result = new Matrix();
  6750. Matrix.TransposeToRef(matrix, result);
  6751. return result;
  6752. };
  6753. /**
  6754. * Compute the transpose of a matrix and store it in a target matrix
  6755. * @param matrix defines the matrix to transpose
  6756. * @param result defines the target matrix
  6757. */
  6758. Matrix.TransposeToRef = function (matrix, result) {
  6759. result.m[0] = matrix.m[0];
  6760. result.m[1] = matrix.m[4];
  6761. result.m[2] = matrix.m[8];
  6762. result.m[3] = matrix.m[12];
  6763. result.m[4] = matrix.m[1];
  6764. result.m[5] = matrix.m[5];
  6765. result.m[6] = matrix.m[9];
  6766. result.m[7] = matrix.m[13];
  6767. result.m[8] = matrix.m[2];
  6768. result.m[9] = matrix.m[6];
  6769. result.m[10] = matrix.m[10];
  6770. result.m[11] = matrix.m[14];
  6771. result.m[12] = matrix.m[3];
  6772. result.m[13] = matrix.m[7];
  6773. result.m[14] = matrix.m[11];
  6774. result.m[15] = matrix.m[15];
  6775. };
  6776. /**
  6777. * Computes a reflection matrix from a plane
  6778. * @param plane defines the reflection plane
  6779. * @returns a new matrix
  6780. */
  6781. Matrix.Reflection = function (plane) {
  6782. var matrix = new Matrix();
  6783. Matrix.ReflectionToRef(plane, matrix);
  6784. return matrix;
  6785. };
  6786. /**
  6787. * Computes a reflection matrix from a plane
  6788. * @param plane defines the reflection plane
  6789. * @param result defines the target matrix
  6790. */
  6791. Matrix.ReflectionToRef = function (plane, result) {
  6792. plane.normalize();
  6793. var x = plane.normal.x;
  6794. var y = plane.normal.y;
  6795. var z = plane.normal.z;
  6796. var temp = -2 * x;
  6797. var temp2 = -2 * y;
  6798. var temp3 = -2 * z;
  6799. result.m[0] = (temp * x) + 1;
  6800. result.m[1] = temp2 * x;
  6801. result.m[2] = temp3 * x;
  6802. result.m[3] = 0.0;
  6803. result.m[4] = temp * y;
  6804. result.m[5] = (temp2 * y) + 1;
  6805. result.m[6] = temp3 * y;
  6806. result.m[7] = 0.0;
  6807. result.m[8] = temp * z;
  6808. result.m[9] = temp2 * z;
  6809. result.m[10] = (temp3 * z) + 1;
  6810. result.m[11] = 0.0;
  6811. result.m[12] = temp * plane.d;
  6812. result.m[13] = temp2 * plane.d;
  6813. result.m[14] = temp3 * plane.d;
  6814. result.m[15] = 1.0;
  6815. result._markAsUpdated();
  6816. };
  6817. /**
  6818. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6819. * @param xaxis defines the value of the 1st axis
  6820. * @param yaxis defines the value of the 2nd axis
  6821. * @param zaxis defines the value of the 3rd axis
  6822. * @param result defines the target matrix
  6823. */
  6824. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6825. result.m[0] = xaxis.x;
  6826. result.m[1] = xaxis.y;
  6827. result.m[2] = xaxis.z;
  6828. result.m[3] = 0.0;
  6829. result.m[4] = yaxis.x;
  6830. result.m[5] = yaxis.y;
  6831. result.m[6] = yaxis.z;
  6832. result.m[7] = 0.0;
  6833. result.m[8] = zaxis.x;
  6834. result.m[9] = zaxis.y;
  6835. result.m[10] = zaxis.z;
  6836. result.m[11] = 0.0;
  6837. result.m[12] = 0.0;
  6838. result.m[13] = 0.0;
  6839. result.m[14] = 0.0;
  6840. result.m[15] = 1.0;
  6841. result._markAsUpdated();
  6842. };
  6843. /**
  6844. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6845. * @param quat defines the quaternion to use
  6846. * @param result defines the target matrix
  6847. */
  6848. Matrix.FromQuaternionToRef = function (quat, result) {
  6849. var xx = quat.x * quat.x;
  6850. var yy = quat.y * quat.y;
  6851. var zz = quat.z * quat.z;
  6852. var xy = quat.x * quat.y;
  6853. var zw = quat.z * quat.w;
  6854. var zx = quat.z * quat.x;
  6855. var yw = quat.y * quat.w;
  6856. var yz = quat.y * quat.z;
  6857. var xw = quat.x * quat.w;
  6858. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6859. result.m[1] = 2.0 * (xy + zw);
  6860. result.m[2] = 2.0 * (zx - yw);
  6861. result.m[3] = 0.0;
  6862. result.m[4] = 2.0 * (xy - zw);
  6863. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6864. result.m[6] = 2.0 * (yz + xw);
  6865. result.m[7] = 0.0;
  6866. result.m[8] = 2.0 * (zx + yw);
  6867. result.m[9] = 2.0 * (yz - xw);
  6868. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6869. result.m[11] = 0.0;
  6870. result.m[12] = 0.0;
  6871. result.m[13] = 0.0;
  6872. result.m[14] = 0.0;
  6873. result.m[15] = 1.0;
  6874. result._markAsUpdated();
  6875. };
  6876. Matrix._tempQuaternion = new Quaternion();
  6877. Matrix._xAxis = Vector3.Zero();
  6878. Matrix._yAxis = Vector3.Zero();
  6879. Matrix._zAxis = Vector3.Zero();
  6880. Matrix._updateFlagSeed = 0;
  6881. Matrix._identityReadOnly = Matrix.Identity();
  6882. return Matrix;
  6883. }());
  6884. BABYLON.Matrix = Matrix;
  6885. /**
  6886. * Represens a plane by the equation ax + by + cz + d = 0
  6887. */
  6888. var Plane = /** @class */ (function () {
  6889. /**
  6890. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6891. * @param a a component of the plane
  6892. * @param b b component of the plane
  6893. * @param c c component of the plane
  6894. * @param d d component of the plane
  6895. */
  6896. function Plane(a, b, c, d) {
  6897. this.normal = new Vector3(a, b, c);
  6898. this.d = d;
  6899. }
  6900. /**
  6901. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6902. */
  6903. Plane.prototype.asArray = function () {
  6904. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6905. };
  6906. // Methods
  6907. /**
  6908. * @returns a new plane copied from the current Plane.
  6909. */
  6910. Plane.prototype.clone = function () {
  6911. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6912. };
  6913. /**
  6914. * @returns the string "Plane".
  6915. */
  6916. Plane.prototype.getClassName = function () {
  6917. return "Plane";
  6918. };
  6919. /**
  6920. * @returns the Plane hash code.
  6921. */
  6922. Plane.prototype.getHashCode = function () {
  6923. var hash = this.normal.getHashCode();
  6924. hash = (hash * 397) ^ (this.d || 0);
  6925. return hash;
  6926. };
  6927. /**
  6928. * Normalize the current Plane in place.
  6929. * @returns the updated Plane.
  6930. */
  6931. Plane.prototype.normalize = function () {
  6932. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6933. var magnitude = 0.0;
  6934. if (norm !== 0) {
  6935. magnitude = 1.0 / norm;
  6936. }
  6937. this.normal.x *= magnitude;
  6938. this.normal.y *= magnitude;
  6939. this.normal.z *= magnitude;
  6940. this.d *= magnitude;
  6941. return this;
  6942. };
  6943. /**
  6944. * Applies a transformation the plane and returns the result
  6945. * @param transformation the transformation matrix to be applied to the plane
  6946. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6947. */
  6948. Plane.prototype.transform = function (transformation) {
  6949. var transposedMatrix = Matrix.Transpose(transformation);
  6950. var x = this.normal.x;
  6951. var y = this.normal.y;
  6952. var z = this.normal.z;
  6953. var d = this.d;
  6954. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6955. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6956. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6957. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6958. return new Plane(normalX, normalY, normalZ, finalD);
  6959. };
  6960. /**
  6961. * Calcualtte the dot product between the point and the plane normal
  6962. * @param point point to calculate the dot product with
  6963. * @returns the dot product (float) of the point coordinates and the plane normal.
  6964. */
  6965. Plane.prototype.dotCoordinate = function (point) {
  6966. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6967. };
  6968. /**
  6969. * Updates the current Plane from the plane defined by the three given points.
  6970. * @param point1 one of the points used to contruct the plane
  6971. * @param point2 one of the points used to contruct the plane
  6972. * @param point3 one of the points used to contruct the plane
  6973. * @returns the updated Plane.
  6974. */
  6975. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6976. var x1 = point2.x - point1.x;
  6977. var y1 = point2.y - point1.y;
  6978. var z1 = point2.z - point1.z;
  6979. var x2 = point3.x - point1.x;
  6980. var y2 = point3.y - point1.y;
  6981. var z2 = point3.z - point1.z;
  6982. var yz = (y1 * z2) - (z1 * y2);
  6983. var xz = (z1 * x2) - (x1 * z2);
  6984. var xy = (x1 * y2) - (y1 * x2);
  6985. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6986. var invPyth;
  6987. if (pyth !== 0) {
  6988. invPyth = 1.0 / pyth;
  6989. }
  6990. else {
  6991. invPyth = 0.0;
  6992. }
  6993. this.normal.x = yz * invPyth;
  6994. this.normal.y = xz * invPyth;
  6995. this.normal.z = xy * invPyth;
  6996. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6997. return this;
  6998. };
  6999. /**
  7000. * Checks if the plane is facing a given direction
  7001. * @param direction the direction to check if the plane is facing
  7002. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  7003. * @returns True is the vector "direction" is the same side than the plane normal.
  7004. */
  7005. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  7006. var dot = Vector3.Dot(this.normal, direction);
  7007. return (dot <= epsilon);
  7008. };
  7009. /**
  7010. * Calculates the distance to a point
  7011. * @param point point to calculate distance to
  7012. * @returns the signed distance (float) from the given point to the Plane.
  7013. */
  7014. Plane.prototype.signedDistanceTo = function (point) {
  7015. return Vector3.Dot(point, this.normal) + this.d;
  7016. };
  7017. // Statics
  7018. /**
  7019. * Creates a plane from an array
  7020. * @param array the array to create a plane from
  7021. * @returns a new Plane from the given array.
  7022. */
  7023. Plane.FromArray = function (array) {
  7024. return new Plane(array[0], array[1], array[2], array[3]);
  7025. };
  7026. /**
  7027. * Creates a plane from three points
  7028. * @param point1 point used to create the plane
  7029. * @param point2 point used to create the plane
  7030. * @param point3 point used to create the plane
  7031. * @returns a new Plane defined by the three given points.
  7032. */
  7033. Plane.FromPoints = function (point1, point2, point3) {
  7034. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7035. result.copyFromPoints(point1, point2, point3);
  7036. return result;
  7037. };
  7038. /**
  7039. * Creates a plane from an origin point and a normal
  7040. * @param origin origin of the plane to be constructed
  7041. * @param normal normal of the plane to be constructed
  7042. * @returns a new Plane the normal vector to this plane at the given origin point.
  7043. * Note : the vector "normal" is updated because normalized.
  7044. */
  7045. Plane.FromPositionAndNormal = function (origin, normal) {
  7046. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7047. normal.normalize();
  7048. result.normal = normal;
  7049. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7050. return result;
  7051. };
  7052. /**
  7053. * Calculates the distance from a plane and a point
  7054. * @param origin origin of the plane to be constructed
  7055. * @param normal normal of the plane to be constructed
  7056. * @param point point to calculate distance to
  7057. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7058. */
  7059. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7060. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7061. return Vector3.Dot(point, normal) + d;
  7062. };
  7063. return Plane;
  7064. }());
  7065. BABYLON.Plane = Plane;
  7066. /**
  7067. * Class used to represent a viewport on screen
  7068. */
  7069. var Viewport = /** @class */ (function () {
  7070. /**
  7071. * Creates a Viewport object located at (x, y) and sized (width, height)
  7072. * @param x defines viewport left coordinate
  7073. * @param y defines viewport top coordinate
  7074. * @param width defines the viewport width
  7075. * @param height defines the viewport height
  7076. */
  7077. function Viewport(
  7078. /** viewport left coordinate */
  7079. x,
  7080. /** viewport top coordinate */
  7081. y,
  7082. /**viewport width */
  7083. width,
  7084. /** viewport height */
  7085. height) {
  7086. this.x = x;
  7087. this.y = y;
  7088. this.width = width;
  7089. this.height = height;
  7090. }
  7091. /**
  7092. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7093. * @param renderWidthOrEngine defines either an engine or the rendering width
  7094. * @param renderHeight defines the rendering height
  7095. * @returns a new Viewport
  7096. */
  7097. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7098. if (renderWidthOrEngine.getRenderWidth) {
  7099. var engine = renderWidthOrEngine;
  7100. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7101. }
  7102. var renderWidth = renderWidthOrEngine;
  7103. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7104. };
  7105. /**
  7106. * Returns a new Viewport copied from the current one
  7107. * @returns a new Viewport
  7108. */
  7109. Viewport.prototype.clone = function () {
  7110. return new Viewport(this.x, this.y, this.width, this.height);
  7111. };
  7112. return Viewport;
  7113. }());
  7114. BABYLON.Viewport = Viewport;
  7115. /**
  7116. * Reprasents a camera frustum
  7117. */
  7118. var Frustum = /** @class */ (function () {
  7119. function Frustum() {
  7120. }
  7121. /**
  7122. * Gets the planes representing the frustum
  7123. * @param transform matrix to be applied to the returned planes
  7124. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7125. */
  7126. Frustum.GetPlanes = function (transform) {
  7127. var frustumPlanes = [];
  7128. for (var index = 0; index < 6; index++) {
  7129. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7130. }
  7131. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7132. return frustumPlanes;
  7133. };
  7134. /**
  7135. * Gets the near frustum plane transformed by the transform matrix
  7136. * @param transform transformation matrix to be applied to the resulting frustum plane
  7137. * @param frustumPlane the resuling frustum plane
  7138. */
  7139. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7140. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7141. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7142. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7143. frustumPlane.d = transform.m[15] + transform.m[14];
  7144. frustumPlane.normalize();
  7145. };
  7146. /**
  7147. * Gets the far frustum plane transformed by the transform matrix
  7148. * @param transform transformation matrix to be applied to the resulting frustum plane
  7149. * @param frustumPlane the resuling frustum plane
  7150. */
  7151. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7152. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7153. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7154. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7155. frustumPlane.d = transform.m[15] - transform.m[14];
  7156. frustumPlane.normalize();
  7157. };
  7158. /**
  7159. * Gets the left frustum plane transformed by the transform matrix
  7160. * @param transform transformation matrix to be applied to the resulting frustum plane
  7161. * @param frustumPlane the resuling frustum plane
  7162. */
  7163. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7164. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7165. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7166. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7167. frustumPlane.d = transform.m[15] + transform.m[12];
  7168. frustumPlane.normalize();
  7169. };
  7170. /**
  7171. * Gets the right frustum plane transformed by the transform matrix
  7172. * @param transform transformation matrix to be applied to the resulting frustum plane
  7173. * @param frustumPlane the resuling frustum plane
  7174. */
  7175. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7176. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7177. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7178. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7179. frustumPlane.d = transform.m[15] - transform.m[12];
  7180. frustumPlane.normalize();
  7181. };
  7182. /**
  7183. * Gets the top frustum plane transformed by the transform matrix
  7184. * @param transform transformation matrix to be applied to the resulting frustum plane
  7185. * @param frustumPlane the resuling frustum plane
  7186. */
  7187. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7188. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7189. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7190. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7191. frustumPlane.d = transform.m[15] - transform.m[13];
  7192. frustumPlane.normalize();
  7193. };
  7194. /**
  7195. * Gets the bottom frustum plane transformed by the transform matrix
  7196. * @param transform transformation matrix to be applied to the resulting frustum plane
  7197. * @param frustumPlane the resuling frustum plane
  7198. */
  7199. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7200. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7201. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7202. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7203. frustumPlane.d = transform.m[15] + transform.m[13];
  7204. frustumPlane.normalize();
  7205. };
  7206. /**
  7207. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7208. * @param transform transformation matrix to be applied to the resulting frustum planes
  7209. * @param frustumPlanes the resuling frustum planes
  7210. */
  7211. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7212. // Near
  7213. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7214. // Far
  7215. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7216. // Left
  7217. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7218. // Right
  7219. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7220. // Top
  7221. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7222. // Bottom
  7223. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7224. };
  7225. return Frustum;
  7226. }());
  7227. BABYLON.Frustum = Frustum;
  7228. /** Defines supported spaces */
  7229. var Space;
  7230. (function (Space) {
  7231. /** Local (object) space */
  7232. Space[Space["LOCAL"] = 0] = "LOCAL";
  7233. /** World space */
  7234. Space[Space["WORLD"] = 1] = "WORLD";
  7235. /** Bone space */
  7236. Space[Space["BONE"] = 2] = "BONE";
  7237. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7238. /** Defines the 3 main axes */
  7239. var Axis = /** @class */ (function () {
  7240. function Axis() {
  7241. }
  7242. /** X axis */
  7243. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7244. /** Y axis */
  7245. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7246. /** Z axis */
  7247. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7248. return Axis;
  7249. }());
  7250. BABYLON.Axis = Axis;
  7251. /** Class used to represent a Bezier curve */
  7252. var BezierCurve = /** @class */ (function () {
  7253. function BezierCurve() {
  7254. }
  7255. /**
  7256. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7257. * @param t defines the time
  7258. * @param x1 defines the left coordinate on X axis
  7259. * @param y1 defines the left coordinate on Y axis
  7260. * @param x2 defines the right coordinate on X axis
  7261. * @param y2 defines the right coordinate on Y axis
  7262. * @returns the interpolated value
  7263. */
  7264. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7265. // Extract X (which is equal to time here)
  7266. var f0 = 1 - 3 * x2 + 3 * x1;
  7267. var f1 = 3 * x2 - 6 * x1;
  7268. var f2 = 3 * x1;
  7269. var refinedT = t;
  7270. for (var i = 0; i < 5; i++) {
  7271. var refinedT2 = refinedT * refinedT;
  7272. var refinedT3 = refinedT2 * refinedT;
  7273. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7274. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7275. refinedT -= (x - t) * slope;
  7276. refinedT = Math.min(1, Math.max(0, refinedT));
  7277. }
  7278. // Resolve cubic bezier for the given x
  7279. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7280. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7281. Math.pow(refinedT, 3);
  7282. };
  7283. return BezierCurve;
  7284. }());
  7285. BABYLON.BezierCurve = BezierCurve;
  7286. /**
  7287. * Defines potential orientation for back face culling
  7288. */
  7289. var Orientation;
  7290. (function (Orientation) {
  7291. /**
  7292. * Clockwise
  7293. */
  7294. Orientation[Orientation["CW"] = 0] = "CW";
  7295. /** Counter clockwise */
  7296. Orientation[Orientation["CCW"] = 1] = "CCW";
  7297. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7298. /**
  7299. * Defines angle representation
  7300. */
  7301. var Angle = /** @class */ (function () {
  7302. /**
  7303. * Creates an Angle object of "radians" radians (float).
  7304. */
  7305. function Angle(radians) {
  7306. this._radians = radians;
  7307. if (this._radians < 0.0) {
  7308. this._radians += (2.0 * Math.PI);
  7309. }
  7310. }
  7311. /**
  7312. * Get value in degrees
  7313. * @returns the Angle value in degrees (float)
  7314. */
  7315. Angle.prototype.degrees = function () {
  7316. return this._radians * 180.0 / Math.PI;
  7317. };
  7318. /**
  7319. * Get value in radians
  7320. * @returns the Angle value in radians (float)
  7321. */
  7322. Angle.prototype.radians = function () {
  7323. return this._radians;
  7324. };
  7325. /**
  7326. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7327. * @param a defines first vector
  7328. * @param b defines second vector
  7329. * @returns a new Angle
  7330. */
  7331. Angle.BetweenTwoPoints = function (a, b) {
  7332. var delta = b.subtract(a);
  7333. var theta = Math.atan2(delta.y, delta.x);
  7334. return new Angle(theta);
  7335. };
  7336. /**
  7337. * Gets a new Angle object from the given float in radians
  7338. * @param radians defines the angle value in radians
  7339. * @returns a new Angle
  7340. */
  7341. Angle.FromRadians = function (radians) {
  7342. return new Angle(radians);
  7343. };
  7344. /**
  7345. * Gets a new Angle object from the given float in degrees
  7346. * @param degrees defines the angle value in degrees
  7347. * @returns a new Angle
  7348. */
  7349. Angle.FromDegrees = function (degrees) {
  7350. return new Angle(degrees * Math.PI / 180.0);
  7351. };
  7352. return Angle;
  7353. }());
  7354. BABYLON.Angle = Angle;
  7355. /**
  7356. * This represents an arc in a 2d space.
  7357. */
  7358. var Arc2 = /** @class */ (function () {
  7359. /**
  7360. * Creates an Arc object from the three given points : start, middle and end.
  7361. * @param startPoint Defines the start point of the arc
  7362. * @param midPoint Defines the midlle point of the arc
  7363. * @param endPoint Defines the end point of the arc
  7364. */
  7365. function Arc2(
  7366. /** Defines the start point of the arc */
  7367. startPoint,
  7368. /** Defines the mid point of the arc */
  7369. midPoint,
  7370. /** Defines the end point of the arc */
  7371. endPoint) {
  7372. this.startPoint = startPoint;
  7373. this.midPoint = midPoint;
  7374. this.endPoint = endPoint;
  7375. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7376. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7377. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7378. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7379. 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);
  7380. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7381. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7382. var a1 = this.startAngle.degrees();
  7383. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7384. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7385. // angles correction
  7386. if (a2 - a1 > +180.0) {
  7387. a2 -= 360.0;
  7388. }
  7389. if (a2 - a1 < -180.0) {
  7390. a2 += 360.0;
  7391. }
  7392. if (a3 - a2 > +180.0) {
  7393. a3 -= 360.0;
  7394. }
  7395. if (a3 - a2 < -180.0) {
  7396. a3 += 360.0;
  7397. }
  7398. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7399. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7400. }
  7401. return Arc2;
  7402. }());
  7403. BABYLON.Arc2 = Arc2;
  7404. /**
  7405. * Represents a 2D path made up of multiple 2D points
  7406. */
  7407. var Path2 = /** @class */ (function () {
  7408. /**
  7409. * Creates a Path2 object from the starting 2D coordinates x and y.
  7410. * @param x the starting points x value
  7411. * @param y the starting points y value
  7412. */
  7413. function Path2(x, y) {
  7414. this._points = new Array();
  7415. this._length = 0.0;
  7416. /**
  7417. * If the path start and end point are the same
  7418. */
  7419. this.closed = false;
  7420. this._points.push(new Vector2(x, y));
  7421. }
  7422. /**
  7423. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7424. * @param x the added points x value
  7425. * @param y the added points y value
  7426. * @returns the updated Path2.
  7427. */
  7428. Path2.prototype.addLineTo = function (x, y) {
  7429. if (this.closed) {
  7430. return this;
  7431. }
  7432. var newPoint = new Vector2(x, y);
  7433. var previousPoint = this._points[this._points.length - 1];
  7434. this._points.push(newPoint);
  7435. this._length += newPoint.subtract(previousPoint).length();
  7436. return this;
  7437. };
  7438. /**
  7439. * 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.
  7440. * @param midX middle point x value
  7441. * @param midY middle point y value
  7442. * @param endX end point x value
  7443. * @param endY end point y value
  7444. * @param numberOfSegments (default: 36)
  7445. * @returns the updated Path2.
  7446. */
  7447. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7448. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7449. if (this.closed) {
  7450. return this;
  7451. }
  7452. var startPoint = this._points[this._points.length - 1];
  7453. var midPoint = new Vector2(midX, midY);
  7454. var endPoint = new Vector2(endX, endY);
  7455. var arc = new Arc2(startPoint, midPoint, endPoint);
  7456. var increment = arc.angle.radians() / numberOfSegments;
  7457. if (arc.orientation === Orientation.CW) {
  7458. increment *= -1;
  7459. }
  7460. var currentAngle = arc.startAngle.radians() + increment;
  7461. for (var i = 0; i < numberOfSegments; i++) {
  7462. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7463. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7464. this.addLineTo(x, y);
  7465. currentAngle += increment;
  7466. }
  7467. return this;
  7468. };
  7469. /**
  7470. * Closes the Path2.
  7471. * @returns the Path2.
  7472. */
  7473. Path2.prototype.close = function () {
  7474. this.closed = true;
  7475. return this;
  7476. };
  7477. /**
  7478. * Gets the sum of the distance between each sequential point in the path
  7479. * @returns the Path2 total length (float).
  7480. */
  7481. Path2.prototype.length = function () {
  7482. var result = this._length;
  7483. if (!this.closed) {
  7484. var lastPoint = this._points[this._points.length - 1];
  7485. var firstPoint = this._points[0];
  7486. result += (firstPoint.subtract(lastPoint).length());
  7487. }
  7488. return result;
  7489. };
  7490. /**
  7491. * Gets the points which construct the path
  7492. * @returns the Path2 internal array of points.
  7493. */
  7494. Path2.prototype.getPoints = function () {
  7495. return this._points;
  7496. };
  7497. /**
  7498. * Retreives the point at the distance aways from the starting point
  7499. * @param normalizedLengthPosition the length along the path to retreive the point from
  7500. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7501. */
  7502. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7503. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7504. return Vector2.Zero();
  7505. }
  7506. var lengthPosition = normalizedLengthPosition * this.length();
  7507. var previousOffset = 0;
  7508. for (var i = 0; i < this._points.length; i++) {
  7509. var j = (i + 1) % this._points.length;
  7510. var a = this._points[i];
  7511. var b = this._points[j];
  7512. var bToA = b.subtract(a);
  7513. var nextOffset = (bToA.length() + previousOffset);
  7514. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7515. var dir = bToA.normalize();
  7516. var localOffset = lengthPosition - previousOffset;
  7517. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7518. }
  7519. previousOffset = nextOffset;
  7520. }
  7521. return Vector2.Zero();
  7522. };
  7523. /**
  7524. * Creates a new path starting from an x and y position
  7525. * @param x starting x value
  7526. * @param y starting y value
  7527. * @returns a new Path2 starting at the coordinates (x, y).
  7528. */
  7529. Path2.StartingAt = function (x, y) {
  7530. return new Path2(x, y);
  7531. };
  7532. return Path2;
  7533. }());
  7534. BABYLON.Path2 = Path2;
  7535. /**
  7536. * Represents a 3D path made up of multiple 3D points
  7537. */
  7538. var Path3D = /** @class */ (function () {
  7539. /**
  7540. * new Path3D(path, normal, raw)
  7541. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7542. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7543. * @param path an array of Vector3, the curve axis of the Path3D
  7544. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7545. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7546. */
  7547. function Path3D(
  7548. /**
  7549. * an array of Vector3, the curve axis of the Path3D
  7550. */
  7551. path, firstNormal, raw) {
  7552. if (firstNormal === void 0) { firstNormal = null; }
  7553. this.path = path;
  7554. this._curve = new Array();
  7555. this._distances = new Array();
  7556. this._tangents = new Array();
  7557. this._normals = new Array();
  7558. this._binormals = new Array();
  7559. for (var p = 0; p < path.length; p++) {
  7560. this._curve[p] = path[p].clone(); // hard copy
  7561. }
  7562. this._raw = raw || false;
  7563. this._compute(firstNormal);
  7564. }
  7565. /**
  7566. * Returns the Path3D array of successive Vector3 designing its curve.
  7567. * @returns the Path3D array of successive Vector3 designing its curve.
  7568. */
  7569. Path3D.prototype.getCurve = function () {
  7570. return this._curve;
  7571. };
  7572. /**
  7573. * Returns an array populated with tangent vectors on each Path3D curve point.
  7574. * @returns an array populated with tangent vectors on each Path3D curve point.
  7575. */
  7576. Path3D.prototype.getTangents = function () {
  7577. return this._tangents;
  7578. };
  7579. /**
  7580. * Returns an array populated with normal vectors on each Path3D curve point.
  7581. * @returns an array populated with normal vectors on each Path3D curve point.
  7582. */
  7583. Path3D.prototype.getNormals = function () {
  7584. return this._normals;
  7585. };
  7586. /**
  7587. * Returns an array populated with binormal vectors on each Path3D curve point.
  7588. * @returns an array populated with binormal vectors on each Path3D curve point.
  7589. */
  7590. Path3D.prototype.getBinormals = function () {
  7591. return this._binormals;
  7592. };
  7593. /**
  7594. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7595. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7596. */
  7597. Path3D.prototype.getDistances = function () {
  7598. return this._distances;
  7599. };
  7600. /**
  7601. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7602. * @param path path which all values are copied into the curves points
  7603. * @param firstNormal which should be projected onto the curve
  7604. * @returns the same object updated.
  7605. */
  7606. Path3D.prototype.update = function (path, firstNormal) {
  7607. if (firstNormal === void 0) { firstNormal = null; }
  7608. for (var p = 0; p < path.length; p++) {
  7609. this._curve[p].x = path[p].x;
  7610. this._curve[p].y = path[p].y;
  7611. this._curve[p].z = path[p].z;
  7612. }
  7613. this._compute(firstNormal);
  7614. return this;
  7615. };
  7616. // private function compute() : computes tangents, normals and binormals
  7617. Path3D.prototype._compute = function (firstNormal) {
  7618. var l = this._curve.length;
  7619. // first and last tangents
  7620. this._tangents[0] = this._getFirstNonNullVector(0);
  7621. if (!this._raw) {
  7622. this._tangents[0].normalize();
  7623. }
  7624. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7625. if (!this._raw) {
  7626. this._tangents[l - 1].normalize();
  7627. }
  7628. // normals and binormals at first point : arbitrary vector with _normalVector()
  7629. var tg0 = this._tangents[0];
  7630. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7631. this._normals[0] = pp0;
  7632. if (!this._raw) {
  7633. this._normals[0].normalize();
  7634. }
  7635. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7636. if (!this._raw) {
  7637. this._binormals[0].normalize();
  7638. }
  7639. this._distances[0] = 0.0;
  7640. // normals and binormals : next points
  7641. var prev; // previous vector (segment)
  7642. var cur; // current vector (segment)
  7643. var curTang; // current tangent
  7644. // previous normal
  7645. var prevBinor; // previous binormal
  7646. for (var i = 1; i < l; i++) {
  7647. // tangents
  7648. prev = this._getLastNonNullVector(i);
  7649. if (i < l - 1) {
  7650. cur = this._getFirstNonNullVector(i);
  7651. this._tangents[i] = prev.add(cur);
  7652. this._tangents[i].normalize();
  7653. }
  7654. this._distances[i] = this._distances[i - 1] + prev.length();
  7655. // normals and binormals
  7656. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7657. curTang = this._tangents[i];
  7658. prevBinor = this._binormals[i - 1];
  7659. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7660. if (!this._raw) {
  7661. this._normals[i].normalize();
  7662. }
  7663. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7664. if (!this._raw) {
  7665. this._binormals[i].normalize();
  7666. }
  7667. }
  7668. };
  7669. // private function getFirstNonNullVector(index)
  7670. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7671. Path3D.prototype._getFirstNonNullVector = function (index) {
  7672. var i = 1;
  7673. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7674. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7675. i++;
  7676. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7677. }
  7678. return nNVector;
  7679. };
  7680. // private function getLastNonNullVector(index)
  7681. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7682. Path3D.prototype._getLastNonNullVector = function (index) {
  7683. var i = 1;
  7684. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7685. while (nLVector.length() === 0 && index > i + 1) {
  7686. i++;
  7687. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7688. }
  7689. return nLVector;
  7690. };
  7691. // private function normalVector(v0, vt, va) :
  7692. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7693. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7694. Path3D.prototype._normalVector = function (v0, vt, va) {
  7695. var normal0;
  7696. var tgl = vt.length();
  7697. if (tgl === 0.0) {
  7698. tgl = 1.0;
  7699. }
  7700. if (va === undefined || va === null) {
  7701. var point;
  7702. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7703. point = new Vector3(0.0, -1.0, 0.0);
  7704. }
  7705. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7706. point = new Vector3(1.0, 0.0, 0.0);
  7707. }
  7708. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7709. point = new Vector3(0.0, 0.0, 1.0);
  7710. }
  7711. else {
  7712. point = Vector3.Zero();
  7713. }
  7714. normal0 = Vector3.Cross(vt, point);
  7715. }
  7716. else {
  7717. normal0 = Vector3.Cross(vt, va);
  7718. Vector3.CrossToRef(normal0, vt, normal0);
  7719. }
  7720. normal0.normalize();
  7721. return normal0;
  7722. };
  7723. return Path3D;
  7724. }());
  7725. BABYLON.Path3D = Path3D;
  7726. /**
  7727. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7728. * A Curve3 is designed from a series of successive Vector3.
  7729. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7730. */
  7731. var Curve3 = /** @class */ (function () {
  7732. /**
  7733. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7734. * A Curve3 is designed from a series of successive Vector3.
  7735. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7736. * @param points points which make up the curve
  7737. */
  7738. function Curve3(points) {
  7739. this._length = 0.0;
  7740. this._points = points;
  7741. this._length = this._computeLength(points);
  7742. }
  7743. /**
  7744. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7745. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7746. * @param v1 (Vector3) the control point
  7747. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7748. * @param nbPoints (integer) the wanted number of points in the curve
  7749. * @returns the created Curve3
  7750. */
  7751. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7752. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7753. var bez = new Array();
  7754. var equation = function (t, val0, val1, val2) {
  7755. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7756. return res;
  7757. };
  7758. for (var i = 0; i <= nbPoints; i++) {
  7759. 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)));
  7760. }
  7761. return new Curve3(bez);
  7762. };
  7763. /**
  7764. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7765. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7766. * @param v1 (Vector3) the first control point
  7767. * @param v2 (Vector3) the second control point
  7768. * @param v3 (Vector3) the end point of the Cubic Bezier
  7769. * @param nbPoints (integer) the wanted number of points in the curve
  7770. * @returns the created Curve3
  7771. */
  7772. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7773. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7774. var bez = new Array();
  7775. var equation = function (t, val0, val1, val2, val3) {
  7776. 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;
  7777. return res;
  7778. };
  7779. for (var i = 0; i <= nbPoints; i++) {
  7780. 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)));
  7781. }
  7782. return new Curve3(bez);
  7783. };
  7784. /**
  7785. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7786. * @param p1 (Vector3) the origin point of the Hermite Spline
  7787. * @param t1 (Vector3) the tangent vector at the origin point
  7788. * @param p2 (Vector3) the end point of the Hermite Spline
  7789. * @param t2 (Vector3) the tangent vector at the end point
  7790. * @param nbPoints (integer) the wanted number of points in the curve
  7791. * @returns the created Curve3
  7792. */
  7793. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7794. var hermite = new Array();
  7795. var step = 1.0 / nbPoints;
  7796. for (var i = 0; i <= nbPoints; i++) {
  7797. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7798. }
  7799. return new Curve3(hermite);
  7800. };
  7801. /**
  7802. * Returns a Curve3 object along a CatmullRom Spline curve :
  7803. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7804. * @param nbPoints (integer) the wanted number of points between each curve control points
  7805. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7806. * @returns the created Curve3
  7807. */
  7808. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7809. var catmullRom = new Array();
  7810. var step = 1.0 / nbPoints;
  7811. var amount = 0.0;
  7812. if (closed) {
  7813. var pointsCount = points.length;
  7814. for (var i = 0; i < pointsCount; i++) {
  7815. amount = 0;
  7816. for (var c = 0; c < nbPoints; c++) {
  7817. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7818. amount += step;
  7819. }
  7820. }
  7821. catmullRom.push(catmullRom[0]);
  7822. }
  7823. else {
  7824. var totalPoints = new Array();
  7825. totalPoints.push(points[0].clone());
  7826. Array.prototype.push.apply(totalPoints, points);
  7827. totalPoints.push(points[points.length - 1].clone());
  7828. for (var i = 0; i < totalPoints.length - 3; i++) {
  7829. amount = 0;
  7830. for (var c = 0; c < nbPoints; c++) {
  7831. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7832. amount += step;
  7833. }
  7834. }
  7835. i--;
  7836. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7837. }
  7838. return new Curve3(catmullRom);
  7839. };
  7840. /**
  7841. * @returns the Curve3 stored array of successive Vector3
  7842. */
  7843. Curve3.prototype.getPoints = function () {
  7844. return this._points;
  7845. };
  7846. /**
  7847. * @returns the computed length (float) of the curve.
  7848. */
  7849. Curve3.prototype.length = function () {
  7850. return this._length;
  7851. };
  7852. /**
  7853. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7854. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7855. * curveA and curveB keep unchanged.
  7856. * @param curve the curve to continue from this curve
  7857. * @returns the newly constructed curve
  7858. */
  7859. Curve3.prototype.continue = function (curve) {
  7860. var lastPoint = this._points[this._points.length - 1];
  7861. var continuedPoints = this._points.slice();
  7862. var curvePoints = curve.getPoints();
  7863. for (var i = 1; i < curvePoints.length; i++) {
  7864. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7865. }
  7866. var continuedCurve = new Curve3(continuedPoints);
  7867. return continuedCurve;
  7868. };
  7869. Curve3.prototype._computeLength = function (path) {
  7870. var l = 0;
  7871. for (var i = 1; i < path.length; i++) {
  7872. l += (path[i].subtract(path[i - 1])).length();
  7873. }
  7874. return l;
  7875. };
  7876. return Curve3;
  7877. }());
  7878. BABYLON.Curve3 = Curve3;
  7879. // Vertex formats
  7880. /**
  7881. * Contains position and normal vectors for a vertex
  7882. */
  7883. var PositionNormalVertex = /** @class */ (function () {
  7884. /**
  7885. * Creates a PositionNormalVertex
  7886. * @param position the position of the vertex (defaut: 0,0,0)
  7887. * @param normal the normal of the vertex (defaut: 0,1,0)
  7888. */
  7889. function PositionNormalVertex(
  7890. /** the position of the vertex (defaut: 0,0,0) */
  7891. position,
  7892. /** the normal of the vertex (defaut: 0,1,0) */
  7893. normal) {
  7894. if (position === void 0) { position = Vector3.Zero(); }
  7895. if (normal === void 0) { normal = Vector3.Up(); }
  7896. this.position = position;
  7897. this.normal = normal;
  7898. }
  7899. /**
  7900. * Clones the PositionNormalVertex
  7901. * @returns the cloned PositionNormalVertex
  7902. */
  7903. PositionNormalVertex.prototype.clone = function () {
  7904. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7905. };
  7906. return PositionNormalVertex;
  7907. }());
  7908. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7909. /**
  7910. * Contains position, normal and uv vectors for a vertex
  7911. */
  7912. var PositionNormalTextureVertex = /** @class */ (function () {
  7913. /**
  7914. * Creates a PositionNormalTextureVertex
  7915. * @param position the position of the vertex (defaut: 0,0,0)
  7916. * @param normal the normal of the vertex (defaut: 0,1,0)
  7917. * @param uv the uv of the vertex (default: 0,0)
  7918. */
  7919. function PositionNormalTextureVertex(
  7920. /** the position of the vertex (defaut: 0,0,0) */
  7921. position,
  7922. /** the normal of the vertex (defaut: 0,1,0) */
  7923. normal,
  7924. /** the uv of the vertex (default: 0,0) */
  7925. uv) {
  7926. if (position === void 0) { position = Vector3.Zero(); }
  7927. if (normal === void 0) { normal = Vector3.Up(); }
  7928. if (uv === void 0) { uv = Vector2.Zero(); }
  7929. this.position = position;
  7930. this.normal = normal;
  7931. this.uv = uv;
  7932. }
  7933. /**
  7934. * Clones the PositionNormalTextureVertex
  7935. * @returns the cloned PositionNormalTextureVertex
  7936. */
  7937. PositionNormalTextureVertex.prototype.clone = function () {
  7938. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7939. };
  7940. return PositionNormalTextureVertex;
  7941. }());
  7942. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7943. // Temporary pre-allocated objects for engine internal use
  7944. // usage in any internal function :
  7945. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7946. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7947. /**
  7948. * @hidden
  7949. */
  7950. var Tmp = /** @class */ (function () {
  7951. function Tmp() {
  7952. }
  7953. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7954. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7955. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7956. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7957. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7958. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7959. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7960. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7961. Matrix.Zero(), Matrix.Zero(),
  7962. Matrix.Zero(), Matrix.Zero(),
  7963. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7964. return Tmp;
  7965. }());
  7966. BABYLON.Tmp = Tmp;
  7967. /**
  7968. * @hidden
  7969. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7970. */
  7971. var MathTmp = /** @class */ (function () {
  7972. function MathTmp() {
  7973. }
  7974. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7975. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7976. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7977. return MathTmp;
  7978. }());
  7979. })(BABYLON || (BABYLON = {}));
  7980. //# sourceMappingURL=babylon.math.js.map
  7981. var BABYLON;
  7982. (function (BABYLON) {
  7983. /**
  7984. * Scalar computation library
  7985. */
  7986. var Scalar = /** @class */ (function () {
  7987. function Scalar() {
  7988. }
  7989. /**
  7990. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7991. * @param a number
  7992. * @param b number
  7993. * @param epsilon (default = 1.401298E-45)
  7994. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7995. */
  7996. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7997. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7998. var num = a - b;
  7999. return -epsilon <= num && num <= epsilon;
  8000. };
  8001. /**
  8002. * Returns a string : the upper case translation of the number i to hexadecimal.
  8003. * @param i number
  8004. * @returns the upper case translation of the number i to hexadecimal.
  8005. */
  8006. Scalar.ToHex = function (i) {
  8007. var str = i.toString(16);
  8008. if (i <= 15) {
  8009. return ("0" + str).toUpperCase();
  8010. }
  8011. return str.toUpperCase();
  8012. };
  8013. /**
  8014. * Returns -1 if value is negative and +1 is value is positive.
  8015. * @param value the value
  8016. * @returns the value itself if it's equal to zero.
  8017. */
  8018. Scalar.Sign = function (value) {
  8019. value = +value; // convert to a number
  8020. if (value === 0 || isNaN(value)) {
  8021. return value;
  8022. }
  8023. return value > 0 ? 1 : -1;
  8024. };
  8025. /**
  8026. * Returns the value itself if it's between min and max.
  8027. * Returns min if the value is lower than min.
  8028. * Returns max if the value is greater than max.
  8029. * @param value the value to clmap
  8030. * @param min the min value to clamp to (default: 0)
  8031. * @param max the max value to clamp to (default: 1)
  8032. * @returns the clamped value
  8033. */
  8034. Scalar.Clamp = function (value, min, max) {
  8035. if (min === void 0) { min = 0; }
  8036. if (max === void 0) { max = 1; }
  8037. return Math.min(max, Math.max(min, value));
  8038. };
  8039. /**
  8040. * the log2 of value.
  8041. * @param value the value to compute log2 of
  8042. * @returns the log2 of value.
  8043. */
  8044. Scalar.Log2 = function (value) {
  8045. return Math.log(value) * Math.LOG2E;
  8046. };
  8047. /**
  8048. * Loops the value, so that it is never larger than length and never smaller than 0.
  8049. *
  8050. * This is similar to the modulo operator but it works with floating point numbers.
  8051. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8052. * With t = 5 and length = 2.5, the result would be 0.0.
  8053. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8054. * @param value the value
  8055. * @param length the length
  8056. * @returns the looped value
  8057. */
  8058. Scalar.Repeat = function (value, length) {
  8059. return value - Math.floor(value / length) * length;
  8060. };
  8061. /**
  8062. * Normalize the value between 0.0 and 1.0 using min and max values
  8063. * @param value value to normalize
  8064. * @param min max to normalize between
  8065. * @param max min to normalize between
  8066. * @returns the normalized value
  8067. */
  8068. Scalar.Normalize = function (value, min, max) {
  8069. return (value - min) / (max - min);
  8070. };
  8071. /**
  8072. * Denormalize the value from 0.0 and 1.0 using min and max values
  8073. * @param normalized value to denormalize
  8074. * @param min max to denormalize between
  8075. * @param max min to denormalize between
  8076. * @returns the denormalized value
  8077. */
  8078. Scalar.Denormalize = function (normalized, min, max) {
  8079. return (normalized * (max - min) + min);
  8080. };
  8081. /**
  8082. * Calculates the shortest difference between two given angles given in degrees.
  8083. * @param current current angle in degrees
  8084. * @param target target angle in degrees
  8085. * @returns the delta
  8086. */
  8087. Scalar.DeltaAngle = function (current, target) {
  8088. var num = Scalar.Repeat(target - current, 360.0);
  8089. if (num > 180.0) {
  8090. num -= 360.0;
  8091. }
  8092. return num;
  8093. };
  8094. /**
  8095. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8096. * @param tx value
  8097. * @param length length
  8098. * @returns The returned value will move back and forth between 0 and length
  8099. */
  8100. Scalar.PingPong = function (tx, length) {
  8101. var t = Scalar.Repeat(tx, length * 2.0);
  8102. return length - Math.abs(t - length);
  8103. };
  8104. /**
  8105. * Interpolates between min and max with smoothing at the limits.
  8106. *
  8107. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8108. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8109. * @param from from
  8110. * @param to to
  8111. * @param tx value
  8112. * @returns the smooth stepped value
  8113. */
  8114. Scalar.SmoothStep = function (from, to, tx) {
  8115. var t = Scalar.Clamp(tx);
  8116. t = -2.0 * t * t * t + 3.0 * t * t;
  8117. return to * t + from * (1.0 - t);
  8118. };
  8119. /**
  8120. * Moves a value current towards target.
  8121. *
  8122. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8123. * Negative values of maxDelta pushes the value away from target.
  8124. * @param current current value
  8125. * @param target target value
  8126. * @param maxDelta max distance to move
  8127. * @returns resulting value
  8128. */
  8129. Scalar.MoveTowards = function (current, target, maxDelta) {
  8130. var result = 0;
  8131. if (Math.abs(target - current) <= maxDelta) {
  8132. result = target;
  8133. }
  8134. else {
  8135. result = current + Scalar.Sign(target - current) * maxDelta;
  8136. }
  8137. return result;
  8138. };
  8139. /**
  8140. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8141. *
  8142. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8143. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8144. * @param current current value
  8145. * @param target target value
  8146. * @param maxDelta max distance to move
  8147. * @returns resulting angle
  8148. */
  8149. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8150. var num = Scalar.DeltaAngle(current, target);
  8151. var result = 0;
  8152. if (-maxDelta < num && num < maxDelta) {
  8153. result = target;
  8154. }
  8155. else {
  8156. target = current + num;
  8157. result = Scalar.MoveTowards(current, target, maxDelta);
  8158. }
  8159. return result;
  8160. };
  8161. /**
  8162. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8163. * @param start start value
  8164. * @param end target value
  8165. * @param amount amount to lerp between
  8166. * @returns the lerped value
  8167. */
  8168. Scalar.Lerp = function (start, end, amount) {
  8169. return start + ((end - start) * amount);
  8170. };
  8171. /**
  8172. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8173. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8174. * @param start start value
  8175. * @param end target value
  8176. * @param amount amount to lerp between
  8177. * @returns the lerped value
  8178. */
  8179. Scalar.LerpAngle = function (start, end, amount) {
  8180. var num = Scalar.Repeat(end - start, 360.0);
  8181. if (num > 180.0) {
  8182. num -= 360.0;
  8183. }
  8184. return start + num * Scalar.Clamp(amount);
  8185. };
  8186. /**
  8187. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8188. * @param a start value
  8189. * @param b target value
  8190. * @param value value between a and b
  8191. * @returns the inverseLerp value
  8192. */
  8193. Scalar.InverseLerp = function (a, b, value) {
  8194. var result = 0;
  8195. if (a != b) {
  8196. result = Scalar.Clamp((value - a) / (b - a));
  8197. }
  8198. else {
  8199. result = 0.0;
  8200. }
  8201. return result;
  8202. };
  8203. /**
  8204. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8205. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  8206. * @param value1 spline value
  8207. * @param tangent1 spline value
  8208. * @param value2 spline value
  8209. * @param tangent2 spline value
  8210. * @param amount input value
  8211. * @returns hermite result
  8212. */
  8213. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8214. var squared = amount * amount;
  8215. var cubed = amount * squared;
  8216. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8217. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8218. var part3 = (cubed - (2.0 * squared)) + amount;
  8219. var part4 = cubed - squared;
  8220. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8221. };
  8222. /**
  8223. * Returns a random float number between and min and max values
  8224. * @param min min value of random
  8225. * @param max max value of random
  8226. * @returns random value
  8227. */
  8228. Scalar.RandomRange = function (min, max) {
  8229. if (min === max) {
  8230. return min;
  8231. }
  8232. return ((Math.random() * (max - min)) + min);
  8233. };
  8234. /**
  8235. * This function returns percentage of a number in a given range.
  8236. *
  8237. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8238. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8239. * @param number to convert to percentage
  8240. * @param min min range
  8241. * @param max max range
  8242. * @returns the percentage
  8243. */
  8244. Scalar.RangeToPercent = function (number, min, max) {
  8245. return ((number - min) / (max - min));
  8246. };
  8247. /**
  8248. * This function returns number that corresponds to the percentage in a given range.
  8249. *
  8250. * PercentToRange(0.34,0,100) will return 34.
  8251. * @param percent to convert to number
  8252. * @param min min range
  8253. * @param max max range
  8254. * @returns the number
  8255. */
  8256. Scalar.PercentToRange = function (percent, min, max) {
  8257. return ((max - min) * percent + min);
  8258. };
  8259. /**
  8260. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8261. * @param angle The angle to normalize in radian.
  8262. * @return The converted angle.
  8263. */
  8264. Scalar.NormalizeRadians = function (angle) {
  8265. // More precise but slower version kept for reference.
  8266. // angle = angle % Tools.TwoPi;
  8267. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8268. //if (angle > Math.PI) {
  8269. // angle -= Tools.TwoPi;
  8270. //}
  8271. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8272. return angle;
  8273. };
  8274. /**
  8275. * Two pi constants convenient for computation.
  8276. */
  8277. Scalar.TwoPi = Math.PI * 2;
  8278. return Scalar;
  8279. }());
  8280. BABYLON.Scalar = Scalar;
  8281. })(BABYLON || (BABYLON = {}));
  8282. //# sourceMappingURL=babylon.math.scalar.js.map
  8283. //# sourceMappingURL=babylon.mixins.js.map
  8284. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8285. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8286. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8287. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8288. //# sourceMappingURL=babylon.webgl2.js.map
  8289. var BABYLON;
  8290. (function (BABYLON) {
  8291. var __decoratorInitialStore = {};
  8292. var __mergedStore = {};
  8293. var _copySource = function (creationFunction, source, instanciate) {
  8294. var destination = creationFunction();
  8295. // Tags
  8296. if (BABYLON.Tags) {
  8297. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8298. }
  8299. var classStore = getMergedStore(destination);
  8300. // Properties
  8301. for (var property in classStore) {
  8302. var propertyDescriptor = classStore[property];
  8303. var sourceProperty = source[property];
  8304. var propertyType = propertyDescriptor.type;
  8305. if (sourceProperty !== undefined && sourceProperty !== null) {
  8306. switch (propertyType) {
  8307. case 0: // Value
  8308. case 6: // Mesh reference
  8309. case 11: // Camera reference
  8310. destination[property] = sourceProperty;
  8311. break;
  8312. case 1: // Texture
  8313. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8314. break;
  8315. case 2: // Color3
  8316. case 3: // FresnelParameters
  8317. case 4: // Vector2
  8318. case 5: // Vector3
  8319. case 7: // Color Curves
  8320. case 10: // Quaternion
  8321. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8322. break;
  8323. }
  8324. }
  8325. }
  8326. return destination;
  8327. };
  8328. function getDirectStore(target) {
  8329. var classKey = target.getClassName();
  8330. if (!__decoratorInitialStore[classKey]) {
  8331. __decoratorInitialStore[classKey] = {};
  8332. }
  8333. return __decoratorInitialStore[classKey];
  8334. }
  8335. /**
  8336. * Return the list of properties flagged as serializable
  8337. * @param target: host object
  8338. */
  8339. function getMergedStore(target) {
  8340. var classKey = target.getClassName();
  8341. if (__mergedStore[classKey]) {
  8342. return __mergedStore[classKey];
  8343. }
  8344. __mergedStore[classKey] = {};
  8345. var store = __mergedStore[classKey];
  8346. var currentTarget = target;
  8347. var currentKey = classKey;
  8348. while (currentKey) {
  8349. var initialStore = __decoratorInitialStore[currentKey];
  8350. for (var property in initialStore) {
  8351. store[property] = initialStore[property];
  8352. }
  8353. var parent_1 = void 0;
  8354. var done = false;
  8355. do {
  8356. parent_1 = Object.getPrototypeOf(currentTarget);
  8357. if (!parent_1.getClassName) {
  8358. done = true;
  8359. break;
  8360. }
  8361. if (parent_1.getClassName() !== currentKey) {
  8362. break;
  8363. }
  8364. currentTarget = parent_1;
  8365. } while (parent_1);
  8366. if (done) {
  8367. break;
  8368. }
  8369. currentKey = parent_1.getClassName();
  8370. currentTarget = parent_1;
  8371. }
  8372. return store;
  8373. }
  8374. function generateSerializableMember(type, sourceName) {
  8375. return function (target, propertyKey) {
  8376. var classStore = getDirectStore(target);
  8377. if (!classStore[propertyKey]) {
  8378. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8379. }
  8380. };
  8381. }
  8382. function generateExpandMember(setCallback, targetKey) {
  8383. if (targetKey === void 0) { targetKey = null; }
  8384. return function (target, propertyKey) {
  8385. var key = targetKey || ("_" + propertyKey);
  8386. Object.defineProperty(target, propertyKey, {
  8387. get: function () {
  8388. return this[key];
  8389. },
  8390. set: function (value) {
  8391. if (this[key] === value) {
  8392. return;
  8393. }
  8394. this[key] = value;
  8395. target[setCallback].apply(this);
  8396. },
  8397. enumerable: true,
  8398. configurable: true
  8399. });
  8400. };
  8401. }
  8402. function expandToProperty(callback, targetKey) {
  8403. if (targetKey === void 0) { targetKey = null; }
  8404. return generateExpandMember(callback, targetKey);
  8405. }
  8406. BABYLON.expandToProperty = expandToProperty;
  8407. function serialize(sourceName) {
  8408. return generateSerializableMember(0, sourceName); // value member
  8409. }
  8410. BABYLON.serialize = serialize;
  8411. function serializeAsTexture(sourceName) {
  8412. return generateSerializableMember(1, sourceName); // texture member
  8413. }
  8414. BABYLON.serializeAsTexture = serializeAsTexture;
  8415. function serializeAsColor3(sourceName) {
  8416. return generateSerializableMember(2, sourceName); // color3 member
  8417. }
  8418. BABYLON.serializeAsColor3 = serializeAsColor3;
  8419. function serializeAsFresnelParameters(sourceName) {
  8420. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8421. }
  8422. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8423. function serializeAsVector2(sourceName) {
  8424. return generateSerializableMember(4, sourceName); // vector2 member
  8425. }
  8426. BABYLON.serializeAsVector2 = serializeAsVector2;
  8427. function serializeAsVector3(sourceName) {
  8428. return generateSerializableMember(5, sourceName); // vector3 member
  8429. }
  8430. BABYLON.serializeAsVector3 = serializeAsVector3;
  8431. function serializeAsMeshReference(sourceName) {
  8432. return generateSerializableMember(6, sourceName); // mesh reference member
  8433. }
  8434. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8435. function serializeAsColorCurves(sourceName) {
  8436. return generateSerializableMember(7, sourceName); // color curves
  8437. }
  8438. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8439. function serializeAsColor4(sourceName) {
  8440. return generateSerializableMember(8, sourceName); // color 4
  8441. }
  8442. BABYLON.serializeAsColor4 = serializeAsColor4;
  8443. function serializeAsImageProcessingConfiguration(sourceName) {
  8444. return generateSerializableMember(9, sourceName); // image processing
  8445. }
  8446. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8447. function serializeAsQuaternion(sourceName) {
  8448. return generateSerializableMember(10, sourceName); // quaternion member
  8449. }
  8450. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8451. /**
  8452. * Decorator used to define property that can be serialized as reference to a camera
  8453. * @param sourceName defines the name of the property to decorate
  8454. */
  8455. function serializeAsCameraReference(sourceName) {
  8456. return generateSerializableMember(11, sourceName); // camera reference member
  8457. }
  8458. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8459. /**
  8460. * Class used to help serialization objects
  8461. */
  8462. var SerializationHelper = /** @class */ (function () {
  8463. function SerializationHelper() {
  8464. }
  8465. /**
  8466. * Static function used to serialized a specific entity
  8467. * @param entity defines the entity to serialize
  8468. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  8469. * @returns a JSON compatible object representing the serialization of the entity
  8470. */
  8471. SerializationHelper.Serialize = function (entity, serializationObject) {
  8472. if (!serializationObject) {
  8473. serializationObject = {};
  8474. }
  8475. // Tags
  8476. if (BABYLON.Tags) {
  8477. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8478. }
  8479. var serializedProperties = getMergedStore(entity);
  8480. // Properties
  8481. for (var property in serializedProperties) {
  8482. var propertyDescriptor = serializedProperties[property];
  8483. var targetPropertyName = propertyDescriptor.sourceName || property;
  8484. var propertyType = propertyDescriptor.type;
  8485. var sourceProperty = entity[property];
  8486. if (sourceProperty !== undefined && sourceProperty !== null) {
  8487. switch (propertyType) {
  8488. case 0: // Value
  8489. serializationObject[targetPropertyName] = sourceProperty;
  8490. break;
  8491. case 1: // Texture
  8492. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8493. break;
  8494. case 2: // Color3
  8495. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8496. break;
  8497. case 3: // FresnelParameters
  8498. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8499. break;
  8500. case 4: // Vector2
  8501. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8502. break;
  8503. case 5: // Vector3
  8504. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8505. break;
  8506. case 6: // Mesh reference
  8507. serializationObject[targetPropertyName] = sourceProperty.id;
  8508. break;
  8509. case 7: // Color Curves
  8510. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8511. break;
  8512. case 8: // Color 4
  8513. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8514. break;
  8515. case 9: // Image Processing
  8516. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8517. break;
  8518. case 10: // Quaternion
  8519. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8520. break;
  8521. case 11: // Camera reference
  8522. serializationObject[targetPropertyName] = sourceProperty.id;
  8523. break;
  8524. }
  8525. }
  8526. }
  8527. return serializationObject;
  8528. };
  8529. /**
  8530. * Creates a new entity from a serialization data object
  8531. * @param creationFunction defines a function used to instanciated the new entity
  8532. * @param source defines the source serialization data
  8533. * @param scene defines the hosting scene
  8534. * @param rootUrl defines the root url for resources
  8535. * @returns a new entity
  8536. */
  8537. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8538. if (rootUrl === void 0) { rootUrl = null; }
  8539. var destination = creationFunction();
  8540. if (!rootUrl) {
  8541. rootUrl = "";
  8542. }
  8543. // Tags
  8544. if (BABYLON.Tags) {
  8545. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8546. }
  8547. var classStore = getMergedStore(destination);
  8548. // Properties
  8549. for (var property in classStore) {
  8550. var propertyDescriptor = classStore[property];
  8551. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8552. var propertyType = propertyDescriptor.type;
  8553. if (sourceProperty !== undefined && sourceProperty !== null) {
  8554. var dest = destination;
  8555. switch (propertyType) {
  8556. case 0: // Value
  8557. dest[property] = sourceProperty;
  8558. break;
  8559. case 1: // Texture
  8560. if (scene) {
  8561. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8562. }
  8563. break;
  8564. case 2: // Color3
  8565. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8566. break;
  8567. case 3: // FresnelParameters
  8568. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8569. break;
  8570. case 4: // Vector2
  8571. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8572. break;
  8573. case 5: // Vector3
  8574. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8575. break;
  8576. case 6: // Mesh reference
  8577. if (scene) {
  8578. dest[property] = scene.getLastMeshByID(sourceProperty);
  8579. }
  8580. break;
  8581. case 7: // Color Curves
  8582. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8583. break;
  8584. case 8: // Color 4
  8585. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8586. break;
  8587. case 9: // Image Processing
  8588. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8589. break;
  8590. case 10: // Quaternion
  8591. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8592. break;
  8593. case 11: // Camera reference
  8594. if (scene) {
  8595. dest[property] = scene.getCameraByID(sourceProperty);
  8596. }
  8597. break;
  8598. }
  8599. }
  8600. }
  8601. return destination;
  8602. };
  8603. /**
  8604. * Clones an object
  8605. * @param creationFunction defines the function used to instanciate the new object
  8606. * @param source defines the source object
  8607. * @returns the cloned object
  8608. */
  8609. SerializationHelper.Clone = function (creationFunction, source) {
  8610. return _copySource(creationFunction, source, false);
  8611. };
  8612. /**
  8613. * Instanciates a new object based on a source one (some data will be shared between both object)
  8614. * @param creationFunction defines the function used to instanciate the new object
  8615. * @param source defines the source object
  8616. * @returns the new object
  8617. */
  8618. SerializationHelper.Instanciate = function (creationFunction, source) {
  8619. return _copySource(creationFunction, source, true);
  8620. };
  8621. return SerializationHelper;
  8622. }());
  8623. BABYLON.SerializationHelper = SerializationHelper;
  8624. })(BABYLON || (BABYLON = {}));
  8625. //# sourceMappingURL=babylon.decorators.js.map
  8626. var BABYLON;
  8627. (function (BABYLON) {
  8628. /**
  8629. * Wrapper class for promise with external resolve and reject.
  8630. */
  8631. var Deferred = /** @class */ (function () {
  8632. /**
  8633. * Constructor for this deferred object.
  8634. */
  8635. function Deferred() {
  8636. var _this = this;
  8637. this.promise = new Promise(function (resolve, reject) {
  8638. _this._resolve = resolve;
  8639. _this._reject = reject;
  8640. });
  8641. }
  8642. Object.defineProperty(Deferred.prototype, "resolve", {
  8643. /**
  8644. * The resolve method of the promise associated with this deferred object.
  8645. */
  8646. get: function () {
  8647. return this._resolve;
  8648. },
  8649. enumerable: true,
  8650. configurable: true
  8651. });
  8652. Object.defineProperty(Deferred.prototype, "reject", {
  8653. /**
  8654. * The reject method of the promise associated with this deferred object.
  8655. */
  8656. get: function () {
  8657. return this._reject;
  8658. },
  8659. enumerable: true,
  8660. configurable: true
  8661. });
  8662. return Deferred;
  8663. }());
  8664. BABYLON.Deferred = Deferred;
  8665. })(BABYLON || (BABYLON = {}));
  8666. //# sourceMappingURL=babylon.deferred.js.map
  8667. var BABYLON;
  8668. (function (BABYLON) {
  8669. /**
  8670. * A class serves as a medium between the observable and its observers
  8671. */
  8672. var EventState = /** @class */ (function () {
  8673. /**
  8674. * Create a new EventState
  8675. * @param mask defines the mask associated with this state
  8676. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8677. * @param target defines the original target of the state
  8678. * @param currentTarget defines the current target of the state
  8679. */
  8680. function EventState(mask, skipNextObservers, target, currentTarget) {
  8681. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8682. this.initalize(mask, skipNextObservers, target, currentTarget);
  8683. }
  8684. /**
  8685. * Initialize the current event state
  8686. * @param mask defines the mask associated with this state
  8687. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8688. * @param target defines the original target of the state
  8689. * @param currentTarget defines the current target of the state
  8690. * @returns the current event state
  8691. */
  8692. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8693. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8694. this.mask = mask;
  8695. this.skipNextObservers = skipNextObservers;
  8696. this.target = target;
  8697. this.currentTarget = currentTarget;
  8698. return this;
  8699. };
  8700. return EventState;
  8701. }());
  8702. BABYLON.EventState = EventState;
  8703. /**
  8704. * Represent an Observer registered to a given Observable object.
  8705. */
  8706. var Observer = /** @class */ (function () {
  8707. /**
  8708. * Creates a new observer
  8709. * @param callback defines the callback to call when the observer is notified
  8710. * @param mask defines the mask of the observer (used to filter notifications)
  8711. * @param scope defines the current scope used to restore the JS context
  8712. */
  8713. function Observer(
  8714. /**
  8715. * Defines the callback to call when the observer is notified
  8716. */
  8717. callback,
  8718. /**
  8719. * Defines the mask of the observer (used to filter notifications)
  8720. */
  8721. mask,
  8722. /**
  8723. * Defines the current scope used to restore the JS context
  8724. */
  8725. scope) {
  8726. if (scope === void 0) { scope = null; }
  8727. this.callback = callback;
  8728. this.mask = mask;
  8729. this.scope = scope;
  8730. /** @hidden */
  8731. this._willBeUnregistered = false;
  8732. /**
  8733. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8734. */
  8735. this.unregisterOnNextCall = false;
  8736. }
  8737. return Observer;
  8738. }());
  8739. BABYLON.Observer = Observer;
  8740. /**
  8741. * Represent a list of observers registered to multiple Observables object.
  8742. */
  8743. var MultiObserver = /** @class */ (function () {
  8744. function MultiObserver() {
  8745. }
  8746. /**
  8747. * Release associated resources
  8748. */
  8749. MultiObserver.prototype.dispose = function () {
  8750. if (this._observers && this._observables) {
  8751. for (var index = 0; index < this._observers.length; index++) {
  8752. this._observables[index].remove(this._observers[index]);
  8753. }
  8754. }
  8755. this._observers = null;
  8756. this._observables = null;
  8757. };
  8758. /**
  8759. * Raise a callback when one of the observable will notify
  8760. * @param observables defines a list of observables to watch
  8761. * @param callback defines the callback to call on notification
  8762. * @param mask defines the mask used to filter notifications
  8763. * @param scope defines the current scope used to restore the JS context
  8764. * @returns the new MultiObserver
  8765. */
  8766. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8767. if (mask === void 0) { mask = -1; }
  8768. if (scope === void 0) { scope = null; }
  8769. var result = new MultiObserver();
  8770. result._observers = new Array();
  8771. result._observables = observables;
  8772. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8773. var observable = observables_1[_i];
  8774. var observer = observable.add(callback, mask, false, scope);
  8775. if (observer) {
  8776. result._observers.push(observer);
  8777. }
  8778. }
  8779. return result;
  8780. };
  8781. return MultiObserver;
  8782. }());
  8783. BABYLON.MultiObserver = MultiObserver;
  8784. /**
  8785. * The Observable class is a simple implementation of the Observable pattern.
  8786. *
  8787. * 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.
  8788. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8789. * 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).
  8790. * 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.
  8791. */
  8792. var Observable = /** @class */ (function () {
  8793. /**
  8794. * Creates a new observable
  8795. * @param onObserverAdded defines a callback to call when a new observer is added
  8796. */
  8797. function Observable(onObserverAdded) {
  8798. this._observers = new Array();
  8799. this._eventState = new EventState(0);
  8800. if (onObserverAdded) {
  8801. this._onObserverAdded = onObserverAdded;
  8802. }
  8803. }
  8804. /**
  8805. * Create a new Observer with the specified callback
  8806. * @param callback the callback that will be executed for that Observer
  8807. * @param mask the mask used to filter observers
  8808. * @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.
  8809. * @param scope optional scope for the callback to be called from
  8810. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8811. * @returns the new observer created for the callback
  8812. */
  8813. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8814. if (mask === void 0) { mask = -1; }
  8815. if (insertFirst === void 0) { insertFirst = false; }
  8816. if (scope === void 0) { scope = null; }
  8817. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8818. if (!callback) {
  8819. return null;
  8820. }
  8821. var observer = new Observer(callback, mask, scope);
  8822. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8823. if (insertFirst) {
  8824. this._observers.unshift(observer);
  8825. }
  8826. else {
  8827. this._observers.push(observer);
  8828. }
  8829. if (this._onObserverAdded) {
  8830. this._onObserverAdded(observer);
  8831. }
  8832. return observer;
  8833. };
  8834. /**
  8835. * Create a new Observer with the specified callback and unregisters after the next notification
  8836. * @param callback the callback that will be executed for that Observer
  8837. * @returns the new observer created for the callback
  8838. */
  8839. Observable.prototype.addOnce = function (callback) {
  8840. return this.add(callback, undefined, undefined, undefined, true);
  8841. };
  8842. /**
  8843. * Remove an Observer from the Observable object
  8844. * @param observer the instance of the Observer to remove
  8845. * @returns false if it doesn't belong to this Observable
  8846. */
  8847. Observable.prototype.remove = function (observer) {
  8848. if (!observer) {
  8849. return false;
  8850. }
  8851. var index = this._observers.indexOf(observer);
  8852. if (index !== -1) {
  8853. this._deferUnregister(observer);
  8854. return true;
  8855. }
  8856. return false;
  8857. };
  8858. /**
  8859. * Remove a callback from the Observable object
  8860. * @param callback the callback to remove
  8861. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8862. * @returns false if it doesn't belong to this Observable
  8863. */
  8864. Observable.prototype.removeCallback = function (callback, scope) {
  8865. for (var index = 0; index < this._observers.length; index++) {
  8866. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8867. this._deferUnregister(this._observers[index]);
  8868. return true;
  8869. }
  8870. }
  8871. return false;
  8872. };
  8873. Observable.prototype._deferUnregister = function (observer) {
  8874. var _this = this;
  8875. observer.unregisterOnNextCall = false;
  8876. observer._willBeUnregistered = true;
  8877. BABYLON.Tools.SetImmediate(function () {
  8878. _this._remove(observer);
  8879. });
  8880. };
  8881. // This should only be called when not iterating over _observers to avoid callback skipping.
  8882. // Removes an observer from the _observer Array.
  8883. Observable.prototype._remove = function (observer) {
  8884. if (!observer) {
  8885. return false;
  8886. }
  8887. var index = this._observers.indexOf(observer);
  8888. if (index !== -1) {
  8889. this._observers.splice(index, 1);
  8890. return true;
  8891. }
  8892. return false;
  8893. };
  8894. /**
  8895. * Notify all Observers by calling their respective callback with the given data
  8896. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8897. * @param eventData defines the data to send to all observers
  8898. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8899. * @param target defines the original target of the state
  8900. * @param currentTarget defines the current target of the state
  8901. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8902. */
  8903. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8904. if (mask === void 0) { mask = -1; }
  8905. if (!this._observers.length) {
  8906. return true;
  8907. }
  8908. var state = this._eventState;
  8909. state.mask = mask;
  8910. state.target = target;
  8911. state.currentTarget = currentTarget;
  8912. state.skipNextObservers = false;
  8913. state.lastReturnValue = eventData;
  8914. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8915. var obs = _a[_i];
  8916. if (obs._willBeUnregistered) {
  8917. continue;
  8918. }
  8919. if (obs.mask & mask) {
  8920. if (obs.scope) {
  8921. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8922. }
  8923. else {
  8924. state.lastReturnValue = obs.callback(eventData, state);
  8925. }
  8926. if (obs.unregisterOnNextCall) {
  8927. this._deferUnregister(obs);
  8928. }
  8929. }
  8930. if (state.skipNextObservers) {
  8931. return false;
  8932. }
  8933. }
  8934. return true;
  8935. };
  8936. /**
  8937. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8938. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8939. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8940. * and it is crucial that all callbacks will be executed.
  8941. * The order of the callbacks is kept, callbacks are not executed parallel.
  8942. *
  8943. * @param eventData The data to be sent to each callback
  8944. * @param mask is used to filter observers defaults to -1
  8945. * @param target defines the callback target (see EventState)
  8946. * @param currentTarget defines he current object in the bubbling phase
  8947. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8948. */
  8949. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8950. var _this = this;
  8951. if (mask === void 0) { mask = -1; }
  8952. // create an empty promise
  8953. var p = Promise.resolve(eventData);
  8954. // no observers? return this promise.
  8955. if (!this._observers.length) {
  8956. return p;
  8957. }
  8958. var state = this._eventState;
  8959. state.mask = mask;
  8960. state.target = target;
  8961. state.currentTarget = currentTarget;
  8962. state.skipNextObservers = false;
  8963. // execute one callback after another (not using Promise.all, the order is important)
  8964. this._observers.forEach(function (obs) {
  8965. if (state.skipNextObservers) {
  8966. return;
  8967. }
  8968. if (obs._willBeUnregistered) {
  8969. return;
  8970. }
  8971. if (obs.mask & mask) {
  8972. if (obs.scope) {
  8973. p = p.then(function (lastReturnedValue) {
  8974. state.lastReturnValue = lastReturnedValue;
  8975. return obs.callback.apply(obs.scope, [eventData, state]);
  8976. });
  8977. }
  8978. else {
  8979. p = p.then(function (lastReturnedValue) {
  8980. state.lastReturnValue = lastReturnedValue;
  8981. return obs.callback(eventData, state);
  8982. });
  8983. }
  8984. if (obs.unregisterOnNextCall) {
  8985. _this._deferUnregister(obs);
  8986. }
  8987. }
  8988. });
  8989. // return the eventData
  8990. return p.then(function () { return eventData; });
  8991. };
  8992. /**
  8993. * Notify a specific observer
  8994. * @param observer defines the observer to notify
  8995. * @param eventData defines the data to be sent to each callback
  8996. * @param mask is used to filter observers defaults to -1
  8997. */
  8998. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8999. if (mask === void 0) { mask = -1; }
  9000. var state = this._eventState;
  9001. state.mask = mask;
  9002. state.skipNextObservers = false;
  9003. observer.callback(eventData, state);
  9004. };
  9005. /**
  9006. * Gets a boolean indicating if the observable has at least one observer
  9007. * @returns true is the Observable has at least one Observer registered
  9008. */
  9009. Observable.prototype.hasObservers = function () {
  9010. return this._observers.length > 0;
  9011. };
  9012. /**
  9013. * Clear the list of observers
  9014. */
  9015. Observable.prototype.clear = function () {
  9016. this._observers = new Array();
  9017. this._onObserverAdded = null;
  9018. };
  9019. /**
  9020. * Clone the current observable
  9021. * @returns a new observable
  9022. */
  9023. Observable.prototype.clone = function () {
  9024. var result = new Observable();
  9025. result._observers = this._observers.slice(0);
  9026. return result;
  9027. };
  9028. /**
  9029. * Does this observable handles observer registered with a given mask
  9030. * @param mask defines the mask to be tested
  9031. * @return whether or not one observer registered with the given mask is handeled
  9032. **/
  9033. Observable.prototype.hasSpecificMask = function (mask) {
  9034. if (mask === void 0) { mask = -1; }
  9035. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  9036. var obs = _a[_i];
  9037. if (obs.mask & mask || obs.mask === mask) {
  9038. return true;
  9039. }
  9040. }
  9041. return false;
  9042. };
  9043. return Observable;
  9044. }());
  9045. BABYLON.Observable = Observable;
  9046. })(BABYLON || (BABYLON = {}));
  9047. //# sourceMappingURL=babylon.observable.js.map
  9048. var BABYLON;
  9049. (function (BABYLON) {
  9050. /**
  9051. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9052. */
  9053. var SmartArray = /** @class */ (function () {
  9054. /**
  9055. * Instantiates a Smart Array.
  9056. * @param capacity defines the default capacity of the array.
  9057. */
  9058. function SmartArray(capacity) {
  9059. /**
  9060. * The active length of the array.
  9061. */
  9062. this.length = 0;
  9063. this.data = new Array(capacity);
  9064. this._id = SmartArray._GlobalId++;
  9065. }
  9066. /**
  9067. * Pushes a value at the end of the active data.
  9068. * @param value defines the object to push in the array.
  9069. */
  9070. SmartArray.prototype.push = function (value) {
  9071. this.data[this.length++] = value;
  9072. if (this.length > this.data.length) {
  9073. this.data.length *= 2;
  9074. }
  9075. };
  9076. /**
  9077. * Iterates over the active data and apply the lambda to them.
  9078. * @param func defines the action to apply on each value.
  9079. */
  9080. SmartArray.prototype.forEach = function (func) {
  9081. for (var index = 0; index < this.length; index++) {
  9082. func(this.data[index]);
  9083. }
  9084. };
  9085. /**
  9086. * Sorts the full sets of data.
  9087. * @param compareFn defines the comparison function to apply.
  9088. */
  9089. SmartArray.prototype.sort = function (compareFn) {
  9090. this.data.sort(compareFn);
  9091. };
  9092. /**
  9093. * Resets the active data to an empty array.
  9094. */
  9095. SmartArray.prototype.reset = function () {
  9096. this.length = 0;
  9097. };
  9098. /**
  9099. * Releases all the data from the array as well as the array.
  9100. */
  9101. SmartArray.prototype.dispose = function () {
  9102. this.reset();
  9103. if (this.data) {
  9104. this.data.length = 0;
  9105. this.data = [];
  9106. }
  9107. };
  9108. /**
  9109. * Concats the active data with a given array.
  9110. * @param array defines the data to concatenate with.
  9111. */
  9112. SmartArray.prototype.concat = function (array) {
  9113. if (array.length === 0) {
  9114. return;
  9115. }
  9116. if (this.length + array.length > this.data.length) {
  9117. this.data.length = (this.length + array.length) * 2;
  9118. }
  9119. for (var index = 0; index < array.length; index++) {
  9120. this.data[this.length++] = (array.data || array)[index];
  9121. }
  9122. };
  9123. /**
  9124. * Returns the position of a value in the active data.
  9125. * @param value defines the value to find the index for
  9126. * @returns the index if found in the active data otherwise -1
  9127. */
  9128. SmartArray.prototype.indexOf = function (value) {
  9129. var position = this.data.indexOf(value);
  9130. if (position >= this.length) {
  9131. return -1;
  9132. }
  9133. return position;
  9134. };
  9135. /**
  9136. * Returns whether an element is part of the active data.
  9137. * @param value defines the value to look for
  9138. * @returns true if found in the active data otherwise false
  9139. */
  9140. SmartArray.prototype.contains = function (value) {
  9141. return this.indexOf(value) !== -1;
  9142. };
  9143. // Statics
  9144. SmartArray._GlobalId = 0;
  9145. return SmartArray;
  9146. }());
  9147. BABYLON.SmartArray = SmartArray;
  9148. /**
  9149. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9150. * The data in this array can only be present once
  9151. */
  9152. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9153. __extends(SmartArrayNoDuplicate, _super);
  9154. function SmartArrayNoDuplicate() {
  9155. var _this = _super !== null && _super.apply(this, arguments) || this;
  9156. _this._duplicateId = 0;
  9157. return _this;
  9158. }
  9159. /**
  9160. * Pushes a value at the end of the active data.
  9161. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9162. * @param value defines the object to push in the array.
  9163. */
  9164. SmartArrayNoDuplicate.prototype.push = function (value) {
  9165. _super.prototype.push.call(this, value);
  9166. if (!value.__smartArrayFlags) {
  9167. value.__smartArrayFlags = {};
  9168. }
  9169. value.__smartArrayFlags[this._id] = this._duplicateId;
  9170. };
  9171. /**
  9172. * Pushes a value at the end of the active data.
  9173. * If the data is already present, it won t be added again
  9174. * @param value defines the object to push in the array.
  9175. * @returns true if added false if it was already present
  9176. */
  9177. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9178. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9179. return false;
  9180. }
  9181. this.push(value);
  9182. return true;
  9183. };
  9184. /**
  9185. * Resets the active data to an empty array.
  9186. */
  9187. SmartArrayNoDuplicate.prototype.reset = function () {
  9188. _super.prototype.reset.call(this);
  9189. this._duplicateId++;
  9190. };
  9191. /**
  9192. * Concats the active data with a given array.
  9193. * This ensures no dupplicate will be present in the result.
  9194. * @param array defines the data to concatenate with.
  9195. */
  9196. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9197. if (array.length === 0) {
  9198. return;
  9199. }
  9200. if (this.length + array.length > this.data.length) {
  9201. this.data.length = (this.length + array.length) * 2;
  9202. }
  9203. for (var index = 0; index < array.length; index++) {
  9204. var item = (array.data || array)[index];
  9205. this.pushNoDuplicate(item);
  9206. }
  9207. };
  9208. return SmartArrayNoDuplicate;
  9209. }(SmartArray));
  9210. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9211. })(BABYLON || (BABYLON = {}));
  9212. //# sourceMappingURL=babylon.smartArray.js.map
  9213. var BABYLON;
  9214. (function (BABYLON) {
  9215. /** Class used to store color4 gradient */
  9216. var ColorGradient = /** @class */ (function () {
  9217. function ColorGradient() {
  9218. }
  9219. /**
  9220. * Will get a color picked randomly between color1 and color2.
  9221. * If color2 is undefined then color1 will be used
  9222. * @param result defines the target Color4 to store the result in
  9223. */
  9224. ColorGradient.prototype.getColorToRef = function (result) {
  9225. if (!this.color2) {
  9226. result.copyFrom(this.color1);
  9227. return;
  9228. }
  9229. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9230. };
  9231. return ColorGradient;
  9232. }());
  9233. BABYLON.ColorGradient = ColorGradient;
  9234. /** Class used to store color 3 gradient */
  9235. var Color3Gradient = /** @class */ (function () {
  9236. function Color3Gradient() {
  9237. }
  9238. return Color3Gradient;
  9239. }());
  9240. BABYLON.Color3Gradient = Color3Gradient;
  9241. /** Class used to store factor gradient */
  9242. var FactorGradient = /** @class */ (function () {
  9243. function FactorGradient() {
  9244. }
  9245. /**
  9246. * Will get a number picked randomly between factor1 and factor2.
  9247. * If factor2 is undefined then factor1 will be used
  9248. * @returns the picked number
  9249. */
  9250. FactorGradient.prototype.getFactor = function () {
  9251. if (this.factor2 === undefined) {
  9252. return this.factor1;
  9253. }
  9254. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9255. };
  9256. return FactorGradient;
  9257. }());
  9258. BABYLON.FactorGradient = FactorGradient;
  9259. /**
  9260. * @ignore
  9261. * Application error to support additional information when loading a file
  9262. */
  9263. var LoadFileError = /** @class */ (function (_super) {
  9264. __extends(LoadFileError, _super);
  9265. /**
  9266. * Creates a new LoadFileError
  9267. * @param message defines the message of the error
  9268. * @param request defines the optional XHR request
  9269. */
  9270. function LoadFileError(message,
  9271. /** defines the optional XHR request */
  9272. request) {
  9273. var _this = _super.call(this, message) || this;
  9274. _this.request = request;
  9275. _this.name = "LoadFileError";
  9276. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9277. return _this;
  9278. }
  9279. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9280. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9281. // Polyfill for Object.setPrototypeOf if necessary.
  9282. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9283. return LoadFileError;
  9284. }(Error));
  9285. BABYLON.LoadFileError = LoadFileError;
  9286. /**
  9287. * Class used to define a retry strategy when error happens while loading assets
  9288. */
  9289. var RetryStrategy = /** @class */ (function () {
  9290. function RetryStrategy() {
  9291. }
  9292. /**
  9293. * Function used to defines an exponential back off strategy
  9294. * @param maxRetries defines the maximum number of retries (3 by default)
  9295. * @param baseInterval defines the interval between retries
  9296. * @returns the strategy function to use
  9297. */
  9298. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9299. if (maxRetries === void 0) { maxRetries = 3; }
  9300. if (baseInterval === void 0) { baseInterval = 500; }
  9301. return function (url, request, retryIndex) {
  9302. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9303. return -1;
  9304. }
  9305. return Math.pow(2, retryIndex) * baseInterval;
  9306. };
  9307. };
  9308. return RetryStrategy;
  9309. }());
  9310. BABYLON.RetryStrategy = RetryStrategy;
  9311. // Screenshots
  9312. var screenshotCanvas;
  9313. var cloneValue = function (source, destinationObject) {
  9314. if (!source) {
  9315. return null;
  9316. }
  9317. if (source instanceof BABYLON.Mesh) {
  9318. return null;
  9319. }
  9320. if (source instanceof BABYLON.SubMesh) {
  9321. return source.clone(destinationObject);
  9322. }
  9323. else if (source.clone) {
  9324. return source.clone();
  9325. }
  9326. return null;
  9327. };
  9328. /**
  9329. * Class containing a set of static utilities functions
  9330. */
  9331. var Tools = /** @class */ (function () {
  9332. function Tools() {
  9333. }
  9334. /**
  9335. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9336. * @param u defines the coordinate on X axis
  9337. * @param v defines the coordinate on Y axis
  9338. * @param width defines the width of the source data
  9339. * @param height defines the height of the source data
  9340. * @param pixels defines the source byte array
  9341. * @param color defines the output color
  9342. */
  9343. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9344. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9345. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9346. var position = (wrappedU + wrappedV * width) * 4;
  9347. color.r = pixels[position] / 255;
  9348. color.g = pixels[position + 1] / 255;
  9349. color.b = pixels[position + 2] / 255;
  9350. color.a = pixels[position + 3] / 255;
  9351. };
  9352. /**
  9353. * Interpolates between a and b via alpha
  9354. * @param a The lower value (returned when alpha = 0)
  9355. * @param b The upper value (returned when alpha = 1)
  9356. * @param alpha The interpolation-factor
  9357. * @return The mixed value
  9358. */
  9359. Tools.Mix = function (a, b, alpha) {
  9360. return a * (1 - alpha) + b * alpha;
  9361. };
  9362. /**
  9363. * Tries to instantiate a new object from a given class name
  9364. * @param className defines the class name to instantiate
  9365. * @returns the new object or null if the system was not able to do the instantiation
  9366. */
  9367. Tools.Instantiate = function (className) {
  9368. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9369. return Tools.RegisteredExternalClasses[className];
  9370. }
  9371. var arr = className.split(".");
  9372. var fn = (window || this);
  9373. for (var i = 0, len = arr.length; i < len; i++) {
  9374. fn = fn[arr[i]];
  9375. }
  9376. if (typeof fn !== "function") {
  9377. return null;
  9378. }
  9379. return fn;
  9380. };
  9381. /**
  9382. * Provides a slice function that will work even on IE
  9383. * @param data defines the array to slice
  9384. * @param start defines the start of the data (optional)
  9385. * @param end defines the end of the data (optional)
  9386. * @returns the new sliced array
  9387. */
  9388. Tools.Slice = function (data, start, end) {
  9389. if (data.slice) {
  9390. return data.slice(start, end);
  9391. }
  9392. return Array.prototype.slice.call(data, start, end);
  9393. };
  9394. /**
  9395. * Polyfill for setImmediate
  9396. * @param action defines the action to execute after the current execution block
  9397. */
  9398. Tools.SetImmediate = function (action) {
  9399. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9400. window.setImmediate(action);
  9401. }
  9402. else {
  9403. setTimeout(action, 1);
  9404. }
  9405. };
  9406. /**
  9407. * Function indicating if a number is an exponent of 2
  9408. * @param value defines the value to test
  9409. * @returns true if the value is an exponent of 2
  9410. */
  9411. Tools.IsExponentOfTwo = function (value) {
  9412. var count = 1;
  9413. do {
  9414. count *= 2;
  9415. } while (count < value);
  9416. return count === value;
  9417. };
  9418. /**
  9419. * Returns the nearest 32-bit single precision float representation of a Number
  9420. * @param value A Number. If the parameter is of a different type, it will get converted
  9421. * to a number or to NaN if it cannot be converted
  9422. * @returns number
  9423. */
  9424. Tools.FloatRound = function (value) {
  9425. if (Math.fround) {
  9426. return Math.fround(value);
  9427. }
  9428. return (Tools._tmpFloatArray[0] = value);
  9429. };
  9430. /**
  9431. * Find the next highest power of two.
  9432. * @param x Number to start search from.
  9433. * @return Next highest power of two.
  9434. */
  9435. Tools.CeilingPOT = function (x) {
  9436. x--;
  9437. x |= x >> 1;
  9438. x |= x >> 2;
  9439. x |= x >> 4;
  9440. x |= x >> 8;
  9441. x |= x >> 16;
  9442. x++;
  9443. return x;
  9444. };
  9445. /**
  9446. * Find the next lowest power of two.
  9447. * @param x Number to start search from.
  9448. * @return Next lowest power of two.
  9449. */
  9450. Tools.FloorPOT = function (x) {
  9451. x = x | (x >> 1);
  9452. x = x | (x >> 2);
  9453. x = x | (x >> 4);
  9454. x = x | (x >> 8);
  9455. x = x | (x >> 16);
  9456. return x - (x >> 1);
  9457. };
  9458. /**
  9459. * Find the nearest power of two.
  9460. * @param x Number to start search from.
  9461. * @return Next nearest power of two.
  9462. */
  9463. Tools.NearestPOT = function (x) {
  9464. var c = Tools.CeilingPOT(x);
  9465. var f = Tools.FloorPOT(x);
  9466. return (c - x) > (x - f) ? f : c;
  9467. };
  9468. /**
  9469. * Get the closest exponent of two
  9470. * @param value defines the value to approximate
  9471. * @param max defines the maximum value to return
  9472. * @param mode defines how to define the closest value
  9473. * @returns closest exponent of two of the given value
  9474. */
  9475. Tools.GetExponentOfTwo = function (value, max, mode) {
  9476. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9477. var pot;
  9478. switch (mode) {
  9479. case BABYLON.Engine.SCALEMODE_FLOOR:
  9480. pot = Tools.FloorPOT(value);
  9481. break;
  9482. case BABYLON.Engine.SCALEMODE_NEAREST:
  9483. pot = Tools.NearestPOT(value);
  9484. break;
  9485. case BABYLON.Engine.SCALEMODE_CEILING:
  9486. default:
  9487. pot = Tools.CeilingPOT(value);
  9488. break;
  9489. }
  9490. return Math.min(pot, max);
  9491. };
  9492. /**
  9493. * Extracts the filename from a path
  9494. * @param path defines the path to use
  9495. * @returns the filename
  9496. */
  9497. Tools.GetFilename = function (path) {
  9498. var index = path.lastIndexOf("/");
  9499. if (index < 0) {
  9500. return path;
  9501. }
  9502. return path.substring(index + 1);
  9503. };
  9504. /**
  9505. * Extracts the "folder" part of a path (everything before the filename).
  9506. * @param uri The URI to extract the info from
  9507. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9508. * @returns The "folder" part of the path
  9509. */
  9510. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9511. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9512. var index = uri.lastIndexOf("/");
  9513. if (index < 0) {
  9514. if (returnUnchangedIfNoSlash) {
  9515. return uri;
  9516. }
  9517. return "";
  9518. }
  9519. return uri.substring(0, index + 1);
  9520. };
  9521. /**
  9522. * Extracts text content from a DOM element hierarchy
  9523. * @param element defines the root element
  9524. * @returns a string
  9525. */
  9526. Tools.GetDOMTextContent = function (element) {
  9527. var result = "";
  9528. var child = element.firstChild;
  9529. while (child) {
  9530. if (child.nodeType === 3) {
  9531. result += child.textContent;
  9532. }
  9533. child = child.nextSibling;
  9534. }
  9535. return result;
  9536. };
  9537. /**
  9538. * Convert an angle in radians to degrees
  9539. * @param angle defines the angle to convert
  9540. * @returns the angle in degrees
  9541. */
  9542. Tools.ToDegrees = function (angle) {
  9543. return angle * 180 / Math.PI;
  9544. };
  9545. /**
  9546. * Convert an angle in degrees to radians
  9547. * @param angle defines the angle to convert
  9548. * @returns the angle in radians
  9549. */
  9550. Tools.ToRadians = function (angle) {
  9551. return angle * Math.PI / 180;
  9552. };
  9553. /**
  9554. * Encode a buffer to a base64 string
  9555. * @param buffer defines the buffer to encode
  9556. * @returns the encoded string
  9557. */
  9558. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9559. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9560. var output = "";
  9561. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9562. var i = 0;
  9563. var bytes = new Uint8Array(buffer);
  9564. while (i < bytes.length) {
  9565. chr1 = bytes[i++];
  9566. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9567. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9568. enc1 = chr1 >> 2;
  9569. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9570. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9571. enc4 = chr3 & 63;
  9572. if (isNaN(chr2)) {
  9573. enc3 = enc4 = 64;
  9574. }
  9575. else if (isNaN(chr3)) {
  9576. enc4 = 64;
  9577. }
  9578. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9579. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9580. }
  9581. return "data:image/png;base64," + output;
  9582. };
  9583. /**
  9584. * Extracts minimum and maximum values from a list of indexed positions
  9585. * @param positions defines the positions to use
  9586. * @param indices defines the indices to the positions
  9587. * @param indexStart defines the start index
  9588. * @param indexCount defines the end index
  9589. * @param bias defines bias value to add to the result
  9590. * @return minimum and maximum values
  9591. */
  9592. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9593. if (bias === void 0) { bias = null; }
  9594. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9595. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9596. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9597. var offset = indices[index] * 3;
  9598. var x = positions[offset];
  9599. var y = positions[offset + 1];
  9600. var z = positions[offset + 2];
  9601. minimum.minimizeInPlaceFromFloats(x, y, z);
  9602. maximum.maximizeInPlaceFromFloats(x, y, z);
  9603. }
  9604. if (bias) {
  9605. minimum.x -= minimum.x * bias.x + bias.y;
  9606. minimum.y -= minimum.y * bias.x + bias.y;
  9607. minimum.z -= minimum.z * bias.x + bias.y;
  9608. maximum.x += maximum.x * bias.x + bias.y;
  9609. maximum.y += maximum.y * bias.x + bias.y;
  9610. maximum.z += maximum.z * bias.x + bias.y;
  9611. }
  9612. return {
  9613. minimum: minimum,
  9614. maximum: maximum
  9615. };
  9616. };
  9617. /**
  9618. * Extracts minimum and maximum values from a list of positions
  9619. * @param positions defines the positions to use
  9620. * @param start defines the start index in the positions array
  9621. * @param count defines the number of positions to handle
  9622. * @param bias defines bias value to add to the result
  9623. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9624. * @return minimum and maximum values
  9625. */
  9626. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9627. if (bias === void 0) { bias = null; }
  9628. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9629. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9630. if (!stride) {
  9631. stride = 3;
  9632. }
  9633. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9634. var x = positions[offset];
  9635. var y = positions[offset + 1];
  9636. var z = positions[offset + 2];
  9637. minimum.minimizeInPlaceFromFloats(x, y, z);
  9638. maximum.maximizeInPlaceFromFloats(x, y, z);
  9639. }
  9640. if (bias) {
  9641. minimum.x -= minimum.x * bias.x + bias.y;
  9642. minimum.y -= minimum.y * bias.x + bias.y;
  9643. minimum.z -= minimum.z * bias.x + bias.y;
  9644. maximum.x += maximum.x * bias.x + bias.y;
  9645. maximum.y += maximum.y * bias.x + bias.y;
  9646. maximum.z += maximum.z * bias.x + bias.y;
  9647. }
  9648. return {
  9649. minimum: minimum,
  9650. maximum: maximum
  9651. };
  9652. };
  9653. /**
  9654. * Returns an array if obj is not an array
  9655. * @param obj defines the object to evaluate as an array
  9656. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9657. * @returns either obj directly if obj is an array or a new array containing obj
  9658. */
  9659. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9660. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  9661. return null;
  9662. }
  9663. return Array.isArray(obj) ? obj : [obj];
  9664. };
  9665. /**
  9666. * Gets the pointer prefix to use
  9667. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9668. */
  9669. Tools.GetPointerPrefix = function () {
  9670. var eventPrefix = "pointer";
  9671. // Check if pointer events are supported
  9672. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9673. eventPrefix = "mouse";
  9674. }
  9675. return eventPrefix;
  9676. };
  9677. /**
  9678. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9679. * @param func - the function to be called
  9680. * @param requester - the object that will request the next frame. Falls back to window.
  9681. * @returns frame number
  9682. */
  9683. Tools.QueueNewFrame = function (func, requester) {
  9684. if (!Tools.IsWindowObjectExist()) {
  9685. return setTimeout(func, 16);
  9686. }
  9687. if (!requester) {
  9688. requester = window;
  9689. }
  9690. if (requester.requestAnimationFrame) {
  9691. return requester.requestAnimationFrame(func);
  9692. }
  9693. else if (requester.msRequestAnimationFrame) {
  9694. return requester.msRequestAnimationFrame(func);
  9695. }
  9696. else if (requester.webkitRequestAnimationFrame) {
  9697. return requester.webkitRequestAnimationFrame(func);
  9698. }
  9699. else if (requester.mozRequestAnimationFrame) {
  9700. return requester.mozRequestAnimationFrame(func);
  9701. }
  9702. else if (requester.oRequestAnimationFrame) {
  9703. return requester.oRequestAnimationFrame(func);
  9704. }
  9705. else {
  9706. return window.setTimeout(func, 16);
  9707. }
  9708. };
  9709. /**
  9710. * Ask the browser to promote the current element to fullscreen rendering mode
  9711. * @param element defines the DOM element to promote
  9712. */
  9713. Tools.RequestFullscreen = function (element) {
  9714. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9715. if (!requestFunction) {
  9716. return;
  9717. }
  9718. requestFunction.call(element);
  9719. };
  9720. /**
  9721. * Asks the browser to exit fullscreen mode
  9722. */
  9723. Tools.ExitFullscreen = function () {
  9724. if (document.exitFullscreen) {
  9725. document.exitFullscreen();
  9726. }
  9727. else if (document.mozCancelFullScreen) {
  9728. document.mozCancelFullScreen();
  9729. }
  9730. else if (document.webkitCancelFullScreen) {
  9731. document.webkitCancelFullScreen();
  9732. }
  9733. else if (document.msCancelFullScreen) {
  9734. document.msCancelFullScreen();
  9735. }
  9736. };
  9737. /**
  9738. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9739. * @param url define the url we are trying
  9740. * @param element define the dom element where to configure the cors policy
  9741. */
  9742. Tools.SetCorsBehavior = function (url, element) {
  9743. if (url && url.indexOf("data:") === 0) {
  9744. return;
  9745. }
  9746. if (Tools.CorsBehavior) {
  9747. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9748. element.crossOrigin = Tools.CorsBehavior;
  9749. }
  9750. else {
  9751. var result = Tools.CorsBehavior(url);
  9752. if (result) {
  9753. element.crossOrigin = result;
  9754. }
  9755. }
  9756. }
  9757. };
  9758. // External files
  9759. /**
  9760. * Removes unwanted characters from an url
  9761. * @param url defines the url to clean
  9762. * @returns the cleaned url
  9763. */
  9764. Tools.CleanUrl = function (url) {
  9765. url = url.replace(/#/mg, "%23");
  9766. return url;
  9767. };
  9768. /**
  9769. * Loads an image as an HTMLImageElement.
  9770. * @param input url string, ArrayBuffer, or Blob to load
  9771. * @param onLoad callback called when the image successfully loads
  9772. * @param onError callback called when the image fails to load
  9773. * @param database database for caching
  9774. * @returns the HTMLImageElement of the loaded image
  9775. */
  9776. Tools.LoadImage = function (input, onLoad, onError, database) {
  9777. var url;
  9778. var usingObjectURL = false;
  9779. if (input instanceof ArrayBuffer) {
  9780. url = URL.createObjectURL(new Blob([input]));
  9781. usingObjectURL = true;
  9782. }
  9783. else if (input instanceof Blob) {
  9784. url = URL.createObjectURL(input);
  9785. usingObjectURL = true;
  9786. }
  9787. else {
  9788. url = Tools.CleanUrl(input);
  9789. url = Tools.PreprocessUrl(input);
  9790. }
  9791. var img = new Image();
  9792. Tools.SetCorsBehavior(url, img);
  9793. var loadHandler = function () {
  9794. if (usingObjectURL && img.src) {
  9795. URL.revokeObjectURL(img.src);
  9796. }
  9797. img.removeEventListener("load", loadHandler);
  9798. img.removeEventListener("error", errorHandler);
  9799. onLoad(img);
  9800. };
  9801. var errorHandler = function (err) {
  9802. if (usingObjectURL && img.src) {
  9803. URL.revokeObjectURL(img.src);
  9804. }
  9805. img.removeEventListener("load", loadHandler);
  9806. img.removeEventListener("error", errorHandler);
  9807. Tools.Error("Error while trying to load image: " + input);
  9808. if (onError) {
  9809. onError("Error while trying to load image: " + input, err);
  9810. }
  9811. };
  9812. img.addEventListener("load", loadHandler);
  9813. img.addEventListener("error", errorHandler);
  9814. var noIndexedDB = function () {
  9815. img.src = url;
  9816. };
  9817. var loadFromIndexedDB = function () {
  9818. if (database) {
  9819. database.loadImageFromDB(url, img);
  9820. }
  9821. };
  9822. //ANY database to do!
  9823. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9824. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9825. }
  9826. else {
  9827. if (url.indexOf("file:") !== -1) {
  9828. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9829. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9830. try {
  9831. var blobURL;
  9832. try {
  9833. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9834. }
  9835. catch (ex) {
  9836. // Chrome doesn't support oneTimeOnly parameter
  9837. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9838. }
  9839. img.src = blobURL;
  9840. usingObjectURL = true;
  9841. }
  9842. catch (e) {
  9843. img.src = "";
  9844. }
  9845. return img;
  9846. }
  9847. }
  9848. noIndexedDB();
  9849. }
  9850. return img;
  9851. };
  9852. /**
  9853. * Loads a file
  9854. * @param url url string, ArrayBuffer, or Blob to load
  9855. * @param onSuccess callback called when the file successfully loads
  9856. * @param onProgress callback called while file is loading (if the server supports this mode)
  9857. * @param database database for caching
  9858. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9859. * @param onError callback called when the file fails to load
  9860. * @returns a file request object
  9861. */
  9862. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9863. url = Tools.CleanUrl(url);
  9864. url = Tools.PreprocessUrl(url);
  9865. // If file and file input are set
  9866. if (url.indexOf("file:") !== -1) {
  9867. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9868. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9869. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9870. }
  9871. }
  9872. var loadUrl = Tools.BaseUrl + url;
  9873. var aborted = false;
  9874. var fileRequest = {
  9875. onCompleteObservable: new BABYLON.Observable(),
  9876. abort: function () { return aborted = true; },
  9877. };
  9878. var requestFile = function () {
  9879. var request = new XMLHttpRequest();
  9880. var retryHandle = null;
  9881. fileRequest.abort = function () {
  9882. aborted = true;
  9883. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9884. request.abort();
  9885. }
  9886. if (retryHandle !== null) {
  9887. clearTimeout(retryHandle);
  9888. retryHandle = null;
  9889. }
  9890. };
  9891. var retryLoop = function (retryIndex) {
  9892. request.open('GET', loadUrl, true);
  9893. if (useArrayBuffer) {
  9894. request.responseType = "arraybuffer";
  9895. }
  9896. if (onProgress) {
  9897. request.addEventListener("progress", onProgress);
  9898. }
  9899. var onLoadEnd = function () {
  9900. request.removeEventListener("loadend", onLoadEnd);
  9901. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9902. fileRequest.onCompleteObservable.clear();
  9903. };
  9904. request.addEventListener("loadend", onLoadEnd);
  9905. var onReadyStateChange = function () {
  9906. if (aborted) {
  9907. return;
  9908. }
  9909. // In case of undefined state in some browsers.
  9910. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9911. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9912. request.removeEventListener("readystatechange", onReadyStateChange);
  9913. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9914. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9915. return;
  9916. }
  9917. var retryStrategy = Tools.DefaultRetryStrategy;
  9918. if (retryStrategy) {
  9919. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9920. if (waitTime !== -1) {
  9921. // Prevent the request from completing for retry.
  9922. request.removeEventListener("loadend", onLoadEnd);
  9923. request = new XMLHttpRequest();
  9924. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9925. return;
  9926. }
  9927. }
  9928. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9929. if (onError) {
  9930. onError(request, e);
  9931. }
  9932. else {
  9933. throw e;
  9934. }
  9935. }
  9936. };
  9937. request.addEventListener("readystatechange", onReadyStateChange);
  9938. request.send();
  9939. };
  9940. retryLoop(0);
  9941. };
  9942. // Caching all files
  9943. if (database && database.enableSceneOffline) {
  9944. var noIndexedDB_1 = function (request) {
  9945. if (request && request.status > 400) {
  9946. if (onError) {
  9947. onError(request);
  9948. }
  9949. }
  9950. else {
  9951. if (!aborted) {
  9952. requestFile();
  9953. }
  9954. }
  9955. };
  9956. var loadFromIndexedDB = function () {
  9957. // TODO: database needs to support aborting and should return a IFileRequest
  9958. if (aborted) {
  9959. return;
  9960. }
  9961. if (database) {
  9962. database.loadFileFromDB(url, function (data) {
  9963. if (!aborted) {
  9964. onSuccess(data);
  9965. }
  9966. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9967. }, onProgress ? function (event) {
  9968. if (!aborted) {
  9969. onProgress(event);
  9970. }
  9971. } : undefined, noIndexedDB_1, useArrayBuffer);
  9972. }
  9973. };
  9974. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9975. }
  9976. else {
  9977. requestFile();
  9978. }
  9979. return fileRequest;
  9980. };
  9981. /**
  9982. * Load a script (identified by an url). When the url returns, the
  9983. * content of this file is added into a new script element, attached to the DOM (body element)
  9984. * @param scriptUrl defines the url of the script to laod
  9985. * @param onSuccess defines the callback called when the script is loaded
  9986. * @param onError defines the callback to call if an error occurs
  9987. */
  9988. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9989. if (!Tools.IsWindowObjectExist()) {
  9990. return;
  9991. }
  9992. var head = document.getElementsByTagName('head')[0];
  9993. var script = document.createElement('script');
  9994. script.type = 'text/javascript';
  9995. script.src = scriptUrl;
  9996. script.onload = function () {
  9997. if (onSuccess) {
  9998. onSuccess();
  9999. }
  10000. };
  10001. script.onerror = function (e) {
  10002. if (onError) {
  10003. onError("Unable to load script '" + scriptUrl + "'", e);
  10004. }
  10005. };
  10006. head.appendChild(script);
  10007. };
  10008. /**
  10009. * Loads a file from a blob
  10010. * @param fileToLoad defines the blob to use
  10011. * @param callback defines the callback to call when data is loaded
  10012. * @param progressCallback defines the callback to call during loading process
  10013. * @returns a file request object
  10014. */
  10015. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  10016. var reader = new FileReader();
  10017. var request = {
  10018. onCompleteObservable: new BABYLON.Observable(),
  10019. abort: function () { return reader.abort(); },
  10020. };
  10021. reader.onloadend = function (e) {
  10022. request.onCompleteObservable.notifyObservers(request);
  10023. };
  10024. reader.onload = function (e) {
  10025. //target doesn't have result from ts 1.3
  10026. callback(e.target['result']);
  10027. };
  10028. reader.onprogress = progressCallback;
  10029. reader.readAsDataURL(fileToLoad);
  10030. return request;
  10031. };
  10032. /**
  10033. * Loads a file
  10034. * @param fileToLoad defines the file to load
  10035. * @param callback defines the callback to call when data is loaded
  10036. * @param progressCallBack defines the callback to call during loading process
  10037. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  10038. * @returns a file request object
  10039. */
  10040. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  10041. var reader = new FileReader();
  10042. var request = {
  10043. onCompleteObservable: new BABYLON.Observable(),
  10044. abort: function () { return reader.abort(); },
  10045. };
  10046. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  10047. reader.onerror = function (e) {
  10048. Tools.Log("Error while reading file: " + fileToLoad.name);
  10049. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  10050. };
  10051. reader.onload = function (e) {
  10052. //target doesn't have result from ts 1.3
  10053. callback(e.target['result']);
  10054. };
  10055. if (progressCallBack) {
  10056. reader.onprogress = progressCallBack;
  10057. }
  10058. if (!useArrayBuffer) {
  10059. // Asynchronous read
  10060. reader.readAsText(fileToLoad);
  10061. }
  10062. else {
  10063. reader.readAsArrayBuffer(fileToLoad);
  10064. }
  10065. return request;
  10066. };
  10067. /**
  10068. * Creates a data url from a given string content
  10069. * @param content defines the content to convert
  10070. * @returns the new data url link
  10071. */
  10072. Tools.FileAsURL = function (content) {
  10073. var fileBlob = new Blob([content]);
  10074. var url = window.URL || window.webkitURL;
  10075. var link = url.createObjectURL(fileBlob);
  10076. return link;
  10077. };
  10078. /**
  10079. * Format the given number to a specific decimal format
  10080. * @param value defines the number to format
  10081. * @param decimals defines the number of decimals to use
  10082. * @returns the formatted string
  10083. */
  10084. Tools.Format = function (value, decimals) {
  10085. if (decimals === void 0) { decimals = 2; }
  10086. return value.toFixed(decimals);
  10087. };
  10088. /**
  10089. * Checks if a given vector is inside a specific range
  10090. * @param v defines the vector to test
  10091. * @param min defines the minimum range
  10092. * @param max defines the maximum range
  10093. */
  10094. Tools.CheckExtends = function (v, min, max) {
  10095. if (v.x < min.x) {
  10096. min.x = v.x;
  10097. }
  10098. if (v.y < min.y) {
  10099. min.y = v.y;
  10100. }
  10101. if (v.z < min.z) {
  10102. min.z = v.z;
  10103. }
  10104. if (v.x > max.x) {
  10105. max.x = v.x;
  10106. }
  10107. if (v.y > max.y) {
  10108. max.y = v.y;
  10109. }
  10110. if (v.z > max.z) {
  10111. max.z = v.z;
  10112. }
  10113. };
  10114. /**
  10115. * Tries to copy an object by duplicating every property
  10116. * @param source defines the source object
  10117. * @param destination defines the target object
  10118. * @param doNotCopyList defines a list of properties to avoid
  10119. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  10120. */
  10121. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  10122. for (var prop in source) {
  10123. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  10124. continue;
  10125. }
  10126. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  10127. continue;
  10128. }
  10129. var sourceValue = source[prop];
  10130. var typeOfSourceValue = typeof sourceValue;
  10131. if (typeOfSourceValue === "function") {
  10132. continue;
  10133. }
  10134. try {
  10135. if (typeOfSourceValue === "object") {
  10136. if (sourceValue instanceof Array) {
  10137. destination[prop] = [];
  10138. if (sourceValue.length > 0) {
  10139. if (typeof sourceValue[0] == "object") {
  10140. for (var index = 0; index < sourceValue.length; index++) {
  10141. var clonedValue = cloneValue(sourceValue[index], destination);
  10142. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  10143. destination[prop].push(clonedValue);
  10144. }
  10145. }
  10146. }
  10147. else {
  10148. destination[prop] = sourceValue.slice(0);
  10149. }
  10150. }
  10151. }
  10152. else {
  10153. destination[prop] = cloneValue(sourceValue, destination);
  10154. }
  10155. }
  10156. else {
  10157. destination[prop] = sourceValue;
  10158. }
  10159. }
  10160. catch (e) {
  10161. // Just ignore error (it could be because of a read-only property)
  10162. }
  10163. }
  10164. };
  10165. /**
  10166. * Gets a boolean indicating if the given object has no own property
  10167. * @param obj defines the object to test
  10168. * @returns true if object has no own property
  10169. */
  10170. Tools.IsEmpty = function (obj) {
  10171. for (var i in obj) {
  10172. if (obj.hasOwnProperty(i)) {
  10173. return false;
  10174. }
  10175. }
  10176. return true;
  10177. };
  10178. /**
  10179. * Function used to register events at window level
  10180. * @param events defines the events to register
  10181. */
  10182. Tools.RegisterTopRootEvents = function (events) {
  10183. for (var index = 0; index < events.length; index++) {
  10184. var event = events[index];
  10185. window.addEventListener(event.name, event.handler, false);
  10186. try {
  10187. if (window.parent) {
  10188. window.parent.addEventListener(event.name, event.handler, false);
  10189. }
  10190. }
  10191. catch (e) {
  10192. // Silently fails...
  10193. }
  10194. }
  10195. };
  10196. /**
  10197. * Function used to unregister events from window level
  10198. * @param events defines the events to unregister
  10199. */
  10200. Tools.UnregisterTopRootEvents = function (events) {
  10201. for (var index = 0; index < events.length; index++) {
  10202. var event = events[index];
  10203. window.removeEventListener(event.name, event.handler);
  10204. try {
  10205. if (window.parent) {
  10206. window.parent.removeEventListener(event.name, event.handler);
  10207. }
  10208. }
  10209. catch (e) {
  10210. // Silently fails...
  10211. }
  10212. }
  10213. };
  10214. /**
  10215. * Dumps the current bound framebuffer
  10216. * @param width defines the rendering width
  10217. * @param height defines the rendering height
  10218. * @param engine defines the hosting engine
  10219. * @param successCallback defines the callback triggered once the data are available
  10220. * @param mimeType defines the mime type of the result
  10221. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10222. */
  10223. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10224. if (mimeType === void 0) { mimeType = "image/png"; }
  10225. // Read the contents of the framebuffer
  10226. var numberOfChannelsByLine = width * 4;
  10227. var halfHeight = height / 2;
  10228. //Reading datas from WebGL
  10229. var data = engine.readPixels(0, 0, width, height);
  10230. //To flip image on Y axis.
  10231. for (var i = 0; i < halfHeight; i++) {
  10232. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10233. var currentCell = j + i * numberOfChannelsByLine;
  10234. var targetLine = height - i - 1;
  10235. var targetCell = j + targetLine * numberOfChannelsByLine;
  10236. var temp = data[currentCell];
  10237. data[currentCell] = data[targetCell];
  10238. data[targetCell] = temp;
  10239. }
  10240. }
  10241. // Create a 2D canvas to store the result
  10242. if (!screenshotCanvas) {
  10243. screenshotCanvas = document.createElement('canvas');
  10244. }
  10245. screenshotCanvas.width = width;
  10246. screenshotCanvas.height = height;
  10247. var context = screenshotCanvas.getContext('2d');
  10248. if (context) {
  10249. // Copy the pixels to a 2D canvas
  10250. var imageData = context.createImageData(width, height);
  10251. var castData = (imageData.data);
  10252. castData.set(data);
  10253. context.putImageData(imageData, 0, 0);
  10254. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10255. }
  10256. };
  10257. /**
  10258. * Converts the canvas data to blob.
  10259. * This acts as a polyfill for browsers not supporting the to blob function.
  10260. * @param canvas Defines the canvas to extract the data from
  10261. * @param successCallback Defines the callback triggered once the data are available
  10262. * @param mimeType Defines the mime type of the result
  10263. */
  10264. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10265. if (mimeType === void 0) { mimeType = "image/png"; }
  10266. // We need HTMLCanvasElement.toBlob for HD screenshots
  10267. if (!canvas.toBlob) {
  10268. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10269. canvas.toBlob = function (callback, type, quality) {
  10270. var _this = this;
  10271. setTimeout(function () {
  10272. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10273. for (var i = 0; i < len; i++) {
  10274. arr[i] = binStr.charCodeAt(i);
  10275. }
  10276. callback(new Blob([arr]));
  10277. });
  10278. };
  10279. }
  10280. canvas.toBlob(function (blob) {
  10281. successCallback(blob);
  10282. }, mimeType);
  10283. };
  10284. /**
  10285. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10286. * @param successCallback defines the callback triggered once the data are available
  10287. * @param mimeType defines the mime type of the result
  10288. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10289. */
  10290. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10291. if (mimeType === void 0) { mimeType = "image/png"; }
  10292. if (successCallback) {
  10293. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10294. successCallback(base64Image);
  10295. }
  10296. else {
  10297. this.ToBlob(screenshotCanvas, function (blob) {
  10298. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10299. if (("download" in document.createElement("a"))) {
  10300. if (!fileName) {
  10301. var date = new Date();
  10302. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10303. fileName = "screenshot_" + stringDate + ".png";
  10304. }
  10305. Tools.Download(blob, fileName);
  10306. }
  10307. else {
  10308. var url = URL.createObjectURL(blob);
  10309. var newWindow = window.open("");
  10310. if (!newWindow) {
  10311. return;
  10312. }
  10313. var img = newWindow.document.createElement("img");
  10314. img.onload = function () {
  10315. // no longer need to read the blob so it's revoked
  10316. URL.revokeObjectURL(url);
  10317. };
  10318. img.src = url;
  10319. newWindow.document.body.appendChild(img);
  10320. }
  10321. }, mimeType);
  10322. }
  10323. };
  10324. /**
  10325. * Downloads a blob in the browser
  10326. * @param blob defines the blob to download
  10327. * @param fileName defines the name of the downloaded file
  10328. */
  10329. Tools.Download = function (blob, fileName) {
  10330. if (navigator && navigator.msSaveBlob) {
  10331. navigator.msSaveBlob(blob, fileName);
  10332. return;
  10333. }
  10334. var url = window.URL.createObjectURL(blob);
  10335. var a = document.createElement("a");
  10336. document.body.appendChild(a);
  10337. a.style.display = "none";
  10338. a.href = url;
  10339. a.download = fileName;
  10340. a.addEventListener("click", function () {
  10341. if (a.parentElement) {
  10342. a.parentElement.removeChild(a);
  10343. }
  10344. });
  10345. a.click();
  10346. window.URL.revokeObjectURL(url);
  10347. };
  10348. /**
  10349. * Captures a screenshot of the current rendering
  10350. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10351. * @param engine defines the rendering engine
  10352. * @param camera defines the source camera
  10353. * @param size This parameter can be set to a single number or to an object with the
  10354. * following (optional) properties: precision, width, height. If a single number is passed,
  10355. * it will be used for both width and height. If an object is passed, the screenshot size
  10356. * will be derived from the parameters. The precision property is a multiplier allowing
  10357. * rendering at a higher or lower resolution
  10358. * @param successCallback defines the callback receives a single parameter which contains the
  10359. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10360. * src parameter of an <img> to display it
  10361. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10362. * Check your browser for supported MIME types
  10363. */
  10364. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10365. if (mimeType === void 0) { mimeType = "image/png"; }
  10366. var width;
  10367. var height;
  10368. // If a precision value is specified
  10369. if (size.precision) {
  10370. width = Math.round(engine.getRenderWidth() * size.precision);
  10371. height = Math.round(width / engine.getAspectRatio(camera));
  10372. }
  10373. else if (size.width && size.height) {
  10374. width = size.width;
  10375. height = size.height;
  10376. }
  10377. //If passing only width, computing height to keep display canvas ratio.
  10378. else if (size.width && !size.height) {
  10379. width = size.width;
  10380. height = Math.round(width / engine.getAspectRatio(camera));
  10381. }
  10382. //If passing only height, computing width to keep display canvas ratio.
  10383. else if (size.height && !size.width) {
  10384. height = size.height;
  10385. width = Math.round(height * engine.getAspectRatio(camera));
  10386. }
  10387. //Assuming here that "size" parameter is a number
  10388. else if (!isNaN(size)) {
  10389. height = size;
  10390. width = size;
  10391. }
  10392. else {
  10393. Tools.Error("Invalid 'size' parameter !");
  10394. return;
  10395. }
  10396. if (!screenshotCanvas) {
  10397. screenshotCanvas = document.createElement('canvas');
  10398. }
  10399. screenshotCanvas.width = width;
  10400. screenshotCanvas.height = height;
  10401. var renderContext = screenshotCanvas.getContext("2d");
  10402. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10403. var newWidth = width;
  10404. var newHeight = newWidth / ratio;
  10405. if (newHeight > height) {
  10406. newHeight = height;
  10407. newWidth = newHeight * ratio;
  10408. }
  10409. var offsetX = Math.max(0, width - newWidth) / 2;
  10410. var offsetY = Math.max(0, height - newHeight) / 2;
  10411. var renderingCanvas = engine.getRenderingCanvas();
  10412. if (renderContext && renderingCanvas) {
  10413. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10414. }
  10415. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10416. };
  10417. /**
  10418. * Generates an image screenshot from the specified camera.
  10419. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10420. * @param engine The engine to use for rendering
  10421. * @param camera The camera to use for rendering
  10422. * @param size This parameter can be set to a single number or to an object with the
  10423. * following (optional) properties: precision, width, height. If a single number is passed,
  10424. * it will be used for both width and height. If an object is passed, the screenshot size
  10425. * will be derived from the parameters. The precision property is a multiplier allowing
  10426. * rendering at a higher or lower resolution
  10427. * @param successCallback The callback receives a single parameter which contains the
  10428. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10429. * src parameter of an <img> to display it
  10430. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10431. * Check your browser for supported MIME types
  10432. * @param samples Texture samples (default: 1)
  10433. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10434. * @param fileName A name for for the downloaded file.
  10435. */
  10436. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10437. if (mimeType === void 0) { mimeType = "image/png"; }
  10438. if (samples === void 0) { samples = 1; }
  10439. if (antialiasing === void 0) { antialiasing = false; }
  10440. var width;
  10441. var height;
  10442. //If a precision value is specified
  10443. if (size.precision) {
  10444. width = Math.round(engine.getRenderWidth() * size.precision);
  10445. height = Math.round(width / engine.getAspectRatio(camera));
  10446. size = { width: width, height: height };
  10447. }
  10448. else if (size.width && size.height) {
  10449. width = size.width;
  10450. height = size.height;
  10451. }
  10452. //If passing only width, computing height to keep display canvas ratio.
  10453. else if (size.width && !size.height) {
  10454. width = size.width;
  10455. height = Math.round(width / engine.getAspectRatio(camera));
  10456. size = { width: width, height: height };
  10457. }
  10458. //If passing only height, computing width to keep display canvas ratio.
  10459. else if (size.height && !size.width) {
  10460. height = size.height;
  10461. width = Math.round(height * engine.getAspectRatio(camera));
  10462. size = { width: width, height: height };
  10463. }
  10464. //Assuming here that "size" parameter is a number
  10465. else if (!isNaN(size)) {
  10466. height = size;
  10467. width = size;
  10468. }
  10469. else {
  10470. Tools.Error("Invalid 'size' parameter !");
  10471. return;
  10472. }
  10473. var scene = camera.getScene();
  10474. var previousCamera = null;
  10475. if (scene.activeCamera !== camera) {
  10476. previousCamera = scene.activeCamera;
  10477. scene.activeCamera = camera;
  10478. }
  10479. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10480. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10481. texture.renderList = null;
  10482. texture.samples = samples;
  10483. if (antialiasing) {
  10484. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10485. }
  10486. texture.onAfterRenderObservable.add(function () {
  10487. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10488. });
  10489. scene.incrementRenderId();
  10490. scene.resetCachedMaterial();
  10491. texture.render(true);
  10492. texture.dispose();
  10493. if (previousCamera) {
  10494. scene.activeCamera = previousCamera;
  10495. }
  10496. camera.getProjectionMatrix(true); // Force cache refresh;
  10497. };
  10498. /**
  10499. * Validates if xhr data is correct
  10500. * @param xhr defines the request to validate
  10501. * @param dataType defines the expected data type
  10502. * @returns true if data is correct
  10503. */
  10504. Tools.ValidateXHRData = function (xhr, dataType) {
  10505. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10506. if (dataType === void 0) { dataType = 7; }
  10507. try {
  10508. if (dataType & 1) {
  10509. if (xhr.responseText && xhr.responseText.length > 0) {
  10510. return true;
  10511. }
  10512. else if (dataType === 1) {
  10513. return false;
  10514. }
  10515. }
  10516. if (dataType & 2) {
  10517. // Check header width and height since there is no "TGA" magic number
  10518. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10519. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10520. return true;
  10521. }
  10522. else if (dataType === 2) {
  10523. return false;
  10524. }
  10525. }
  10526. if (dataType & 4) {
  10527. // Check for the "DDS" magic number
  10528. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10529. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10530. return true;
  10531. }
  10532. else {
  10533. return false;
  10534. }
  10535. }
  10536. }
  10537. catch (e) {
  10538. // Global protection
  10539. }
  10540. return false;
  10541. };
  10542. /**
  10543. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10544. * Be aware Math.random() could cause collisions, but:
  10545. * "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"
  10546. * @returns a pseudo random id
  10547. */
  10548. Tools.RandomId = function () {
  10549. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10550. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10551. return v.toString(16);
  10552. });
  10553. };
  10554. /**
  10555. * Test if the given uri is a base64 string
  10556. * @param uri The uri to test
  10557. * @return True if the uri is a base64 string or false otherwise
  10558. */
  10559. Tools.IsBase64 = function (uri) {
  10560. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10561. };
  10562. /**
  10563. * Decode the given base64 uri.
  10564. * @param uri The uri to decode
  10565. * @return The decoded base64 data.
  10566. */
  10567. Tools.DecodeBase64 = function (uri) {
  10568. var decodedString = atob(uri.split(",")[1]);
  10569. var bufferLength = decodedString.length;
  10570. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10571. for (var i = 0; i < bufferLength; i++) {
  10572. bufferView[i] = decodedString.charCodeAt(i);
  10573. }
  10574. return bufferView.buffer;
  10575. };
  10576. Tools._AddLogEntry = function (entry) {
  10577. Tools._LogCache = entry + Tools._LogCache;
  10578. if (Tools.OnNewCacheEntry) {
  10579. Tools.OnNewCacheEntry(entry);
  10580. }
  10581. };
  10582. Tools._FormatMessage = function (message) {
  10583. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10584. var date = new Date();
  10585. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10586. };
  10587. Tools._LogDisabled = function (message) {
  10588. // nothing to do
  10589. };
  10590. Tools._LogEnabled = function (message) {
  10591. var formattedMessage = Tools._FormatMessage(message);
  10592. console.log("BJS - " + formattedMessage);
  10593. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10594. Tools._AddLogEntry(entry);
  10595. };
  10596. Tools._WarnDisabled = function (message) {
  10597. // nothing to do
  10598. };
  10599. Tools._WarnEnabled = function (message) {
  10600. var formattedMessage = Tools._FormatMessage(message);
  10601. console.warn("BJS - " + formattedMessage);
  10602. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10603. Tools._AddLogEntry(entry);
  10604. };
  10605. Tools._ErrorDisabled = function (message) {
  10606. // nothing to do
  10607. };
  10608. Tools._ErrorEnabled = function (message) {
  10609. Tools.errorsCount++;
  10610. var formattedMessage = Tools._FormatMessage(message);
  10611. console.error("BJS - " + formattedMessage);
  10612. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10613. Tools._AddLogEntry(entry);
  10614. };
  10615. Object.defineProperty(Tools, "LogCache", {
  10616. /**
  10617. * Gets current log cache (list of logs)
  10618. */
  10619. get: function () {
  10620. return Tools._LogCache;
  10621. },
  10622. enumerable: true,
  10623. configurable: true
  10624. });
  10625. /**
  10626. * Clears the log cache
  10627. */
  10628. Tools.ClearLogCache = function () {
  10629. Tools._LogCache = "";
  10630. Tools.errorsCount = 0;
  10631. };
  10632. Object.defineProperty(Tools, "LogLevels", {
  10633. /**
  10634. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10635. */
  10636. set: function (level) {
  10637. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10638. Tools.Log = Tools._LogEnabled;
  10639. }
  10640. else {
  10641. Tools.Log = Tools._LogDisabled;
  10642. }
  10643. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10644. Tools.Warn = Tools._WarnEnabled;
  10645. }
  10646. else {
  10647. Tools.Warn = Tools._WarnDisabled;
  10648. }
  10649. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10650. Tools.Error = Tools._ErrorEnabled;
  10651. }
  10652. else {
  10653. Tools.Error = Tools._ErrorDisabled;
  10654. }
  10655. },
  10656. enumerable: true,
  10657. configurable: true
  10658. });
  10659. /**
  10660. * Checks if the loaded document was accessed via `file:`-Protocol.
  10661. * @returns boolean
  10662. */
  10663. Tools.IsFileURL = function () {
  10664. return location.protocol === "file:";
  10665. };
  10666. /**
  10667. * Checks if the window object exists
  10668. * @returns true if the window object exists
  10669. */
  10670. Tools.IsWindowObjectExist = function () {
  10671. return (typeof window) !== "undefined";
  10672. };
  10673. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10674. /**
  10675. * Sets the current performance log level
  10676. */
  10677. set: function (level) {
  10678. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10679. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10680. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10681. return;
  10682. }
  10683. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10684. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10685. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10686. return;
  10687. }
  10688. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10689. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10690. },
  10691. enumerable: true,
  10692. configurable: true
  10693. });
  10694. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10695. };
  10696. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10697. };
  10698. Tools._StartUserMark = function (counterName, condition) {
  10699. if (condition === void 0) { condition = true; }
  10700. if (!Tools._performance) {
  10701. if (!Tools.IsWindowObjectExist()) {
  10702. return;
  10703. }
  10704. Tools._performance = window.performance;
  10705. }
  10706. if (!condition || !Tools._performance.mark) {
  10707. return;
  10708. }
  10709. Tools._performance.mark(counterName + "-Begin");
  10710. };
  10711. Tools._EndUserMark = function (counterName, condition) {
  10712. if (condition === void 0) { condition = true; }
  10713. if (!condition || !Tools._performance.mark) {
  10714. return;
  10715. }
  10716. Tools._performance.mark(counterName + "-End");
  10717. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10718. };
  10719. Tools._StartPerformanceConsole = function (counterName, condition) {
  10720. if (condition === void 0) { condition = true; }
  10721. if (!condition) {
  10722. return;
  10723. }
  10724. Tools._StartUserMark(counterName, condition);
  10725. if (console.time) {
  10726. console.time(counterName);
  10727. }
  10728. };
  10729. Tools._EndPerformanceConsole = function (counterName, condition) {
  10730. if (condition === void 0) { condition = true; }
  10731. if (!condition) {
  10732. return;
  10733. }
  10734. Tools._EndUserMark(counterName, condition);
  10735. if (console.time) {
  10736. console.timeEnd(counterName);
  10737. }
  10738. };
  10739. Object.defineProperty(Tools, "Now", {
  10740. /**
  10741. * Gets either window.performance.now() if supported or Date.now() else
  10742. */
  10743. get: function () {
  10744. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10745. return window.performance.now();
  10746. }
  10747. return Date.now();
  10748. },
  10749. enumerable: true,
  10750. configurable: true
  10751. });
  10752. /**
  10753. * This method will return the name of the class used to create the instance of the given object.
  10754. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10755. * @param object the object to get the class name from
  10756. * @param isType defines if the object is actually a type
  10757. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10758. */
  10759. Tools.GetClassName = function (object, isType) {
  10760. if (isType === void 0) { isType = false; }
  10761. var name = null;
  10762. if (!isType && object.getClassName) {
  10763. name = object.getClassName();
  10764. }
  10765. else {
  10766. if (object instanceof Object) {
  10767. var classObj = isType ? object : Object.getPrototypeOf(object);
  10768. name = classObj.constructor["__bjsclassName__"];
  10769. }
  10770. if (!name) {
  10771. name = typeof object;
  10772. }
  10773. }
  10774. return name;
  10775. };
  10776. /**
  10777. * Gets the first element of an array satisfying a given predicate
  10778. * @param array defines the array to browse
  10779. * @param predicate defines the predicate to use
  10780. * @returns null if not found or the element
  10781. */
  10782. Tools.First = function (array, predicate) {
  10783. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10784. var el = array_1[_i];
  10785. if (predicate(el)) {
  10786. return el;
  10787. }
  10788. }
  10789. return null;
  10790. };
  10791. /**
  10792. * This method will return the name of the full name of the class, including its owning module (if any).
  10793. * 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).
  10794. * @param object the object to get the class name from
  10795. * @param isType defines if the object is actually a type
  10796. * @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.
  10797. * @ignorenaming
  10798. */
  10799. Tools.getFullClassName = function (object, isType) {
  10800. if (isType === void 0) { isType = false; }
  10801. var className = null;
  10802. var moduleName = null;
  10803. if (!isType && object.getClassName) {
  10804. className = object.getClassName();
  10805. }
  10806. else {
  10807. if (object instanceof Object) {
  10808. var classObj = isType ? object : Object.getPrototypeOf(object);
  10809. className = classObj.constructor["__bjsclassName__"];
  10810. moduleName = classObj.constructor["__bjsmoduleName__"];
  10811. }
  10812. if (!className) {
  10813. className = typeof object;
  10814. }
  10815. }
  10816. if (!className) {
  10817. return null;
  10818. }
  10819. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10820. };
  10821. /**
  10822. * Returns a promise that resolves after the given amount of time.
  10823. * @param delay Number of milliseconds to delay
  10824. * @returns Promise that resolves after the given amount of time
  10825. */
  10826. Tools.DelayAsync = function (delay) {
  10827. return new Promise(function (resolve) {
  10828. setTimeout(function () {
  10829. resolve();
  10830. }, delay);
  10831. });
  10832. };
  10833. /**
  10834. * Gets the current gradient from an array of IValueGradient
  10835. * @param ratio defines the current ratio to get
  10836. * @param gradients defines the array of IValueGradient
  10837. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10838. */
  10839. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10840. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10841. var currentGradient = gradients[gradientIndex];
  10842. var nextGradient = gradients[gradientIndex + 1];
  10843. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10844. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10845. updateFunc(currentGradient, nextGradient, scale);
  10846. return;
  10847. }
  10848. }
  10849. // Use last index if over
  10850. var lastIndex = gradients.length - 1;
  10851. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10852. };
  10853. /**
  10854. * Gets or sets the base URL to use to load assets
  10855. */
  10856. Tools.BaseUrl = "";
  10857. /**
  10858. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10859. */
  10860. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10861. /**
  10862. * Default behaviour for cors in the application.
  10863. * It can be a string if the expected behavior is identical in the entire app.
  10864. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10865. */
  10866. Tools.CorsBehavior = "anonymous";
  10867. /**
  10868. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10869. * @ignorenaming
  10870. */
  10871. Tools.UseFallbackTexture = true;
  10872. /**
  10873. * Use this object to register external classes like custom textures or material
  10874. * to allow the laoders to instantiate them
  10875. */
  10876. Tools.RegisteredExternalClasses = {};
  10877. /**
  10878. * Texture content used if a texture cannot loaded
  10879. * @ignorenaming
  10880. */
  10881. 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";
  10882. Tools._tmpFloatArray = new Float32Array(1);
  10883. /**
  10884. * Gets or sets a function used to pre-process url before using them to load assets
  10885. */
  10886. Tools.PreprocessUrl = function (url) {
  10887. return url;
  10888. };
  10889. // Logs
  10890. /**
  10891. * No log
  10892. */
  10893. Tools.NoneLogLevel = 0;
  10894. /**
  10895. * Only message logs
  10896. */
  10897. Tools.MessageLogLevel = 1;
  10898. /**
  10899. * Only warning logs
  10900. */
  10901. Tools.WarningLogLevel = 2;
  10902. /**
  10903. * Only error logs
  10904. */
  10905. Tools.ErrorLogLevel = 4;
  10906. /**
  10907. * All logs
  10908. */
  10909. Tools.AllLogLevel = 7;
  10910. Tools._LogCache = "";
  10911. /**
  10912. * Gets a value indicating the number of loading errors
  10913. * @ignorenaming
  10914. */
  10915. Tools.errorsCount = 0;
  10916. /**
  10917. * Log a message to the console
  10918. */
  10919. Tools.Log = Tools._LogEnabled;
  10920. /**
  10921. * Write a warning message to the console
  10922. */
  10923. Tools.Warn = Tools._WarnEnabled;
  10924. /**
  10925. * Write an error message to the console
  10926. */
  10927. Tools.Error = Tools._ErrorEnabled;
  10928. // Performances
  10929. /**
  10930. * No performance log
  10931. */
  10932. Tools.PerformanceNoneLogLevel = 0;
  10933. /**
  10934. * Use user marks to log performance
  10935. */
  10936. Tools.PerformanceUserMarkLogLevel = 1;
  10937. /**
  10938. * Log performance to the console
  10939. */
  10940. Tools.PerformanceConsoleLogLevel = 2;
  10941. /**
  10942. * Starts a performance counter
  10943. */
  10944. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10945. /**
  10946. * Ends a specific performance coutner
  10947. */
  10948. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10949. return Tools;
  10950. }());
  10951. BABYLON.Tools = Tools;
  10952. /**
  10953. * This class is used to track a performance counter which is number based.
  10954. * The user has access to many properties which give statistics of different nature.
  10955. *
  10956. * The implementer can track two kinds of Performance Counter: time and count.
  10957. * 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.
  10958. * 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.
  10959. */
  10960. var PerfCounter = /** @class */ (function () {
  10961. /**
  10962. * Creates a new counter
  10963. */
  10964. function PerfCounter() {
  10965. this._startMonitoringTime = 0;
  10966. this._min = 0;
  10967. this._max = 0;
  10968. this._average = 0;
  10969. this._lastSecAverage = 0;
  10970. this._current = 0;
  10971. this._totalValueCount = 0;
  10972. this._totalAccumulated = 0;
  10973. this._lastSecAccumulated = 0;
  10974. this._lastSecTime = 0;
  10975. this._lastSecValueCount = 0;
  10976. }
  10977. Object.defineProperty(PerfCounter.prototype, "min", {
  10978. /**
  10979. * Returns the smallest value ever
  10980. */
  10981. get: function () {
  10982. return this._min;
  10983. },
  10984. enumerable: true,
  10985. configurable: true
  10986. });
  10987. Object.defineProperty(PerfCounter.prototype, "max", {
  10988. /**
  10989. * Returns the biggest value ever
  10990. */
  10991. get: function () {
  10992. return this._max;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(PerfCounter.prototype, "average", {
  10998. /**
  10999. * Returns the average value since the performance counter is running
  11000. */
  11001. get: function () {
  11002. return this._average;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  11008. /**
  11009. * Returns the average value of the last second the counter was monitored
  11010. */
  11011. get: function () {
  11012. return this._lastSecAverage;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(PerfCounter.prototype, "current", {
  11018. /**
  11019. * Returns the current value
  11020. */
  11021. get: function () {
  11022. return this._current;
  11023. },
  11024. enumerable: true,
  11025. configurable: true
  11026. });
  11027. Object.defineProperty(PerfCounter.prototype, "total", {
  11028. /**
  11029. * Gets the accumulated total
  11030. */
  11031. get: function () {
  11032. return this._totalAccumulated;
  11033. },
  11034. enumerable: true,
  11035. configurable: true
  11036. });
  11037. Object.defineProperty(PerfCounter.prototype, "count", {
  11038. /**
  11039. * Gets the total value count
  11040. */
  11041. get: function () {
  11042. return this._totalValueCount;
  11043. },
  11044. enumerable: true,
  11045. configurable: true
  11046. });
  11047. /**
  11048. * Call this method to start monitoring a new frame.
  11049. * 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.
  11050. */
  11051. PerfCounter.prototype.fetchNewFrame = function () {
  11052. this._totalValueCount++;
  11053. this._current = 0;
  11054. this._lastSecValueCount++;
  11055. };
  11056. /**
  11057. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  11058. * @param newCount the count value to add to the monitored count
  11059. * @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.
  11060. */
  11061. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  11062. if (!PerfCounter.Enabled) {
  11063. return;
  11064. }
  11065. this._current += newCount;
  11066. if (fetchResult) {
  11067. this._fetchResult();
  11068. }
  11069. };
  11070. /**
  11071. * Start monitoring this performance counter
  11072. */
  11073. PerfCounter.prototype.beginMonitoring = function () {
  11074. if (!PerfCounter.Enabled) {
  11075. return;
  11076. }
  11077. this._startMonitoringTime = Tools.Now;
  11078. };
  11079. /**
  11080. * Compute the time lapsed since the previous beginMonitoring() call.
  11081. * @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
  11082. */
  11083. PerfCounter.prototype.endMonitoring = function (newFrame) {
  11084. if (newFrame === void 0) { newFrame = true; }
  11085. if (!PerfCounter.Enabled) {
  11086. return;
  11087. }
  11088. if (newFrame) {
  11089. this.fetchNewFrame();
  11090. }
  11091. var currentTime = Tools.Now;
  11092. this._current = currentTime - this._startMonitoringTime;
  11093. if (newFrame) {
  11094. this._fetchResult();
  11095. }
  11096. };
  11097. PerfCounter.prototype._fetchResult = function () {
  11098. this._totalAccumulated += this._current;
  11099. this._lastSecAccumulated += this._current;
  11100. // Min/Max update
  11101. this._min = Math.min(this._min, this._current);
  11102. this._max = Math.max(this._max, this._current);
  11103. this._average = this._totalAccumulated / this._totalValueCount;
  11104. // Reset last sec?
  11105. var now = Tools.Now;
  11106. if ((now - this._lastSecTime) > 1000) {
  11107. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  11108. this._lastSecTime = now;
  11109. this._lastSecAccumulated = 0;
  11110. this._lastSecValueCount = 0;
  11111. }
  11112. };
  11113. /**
  11114. * Gets or sets a global boolean to turn on and off all the counters
  11115. */
  11116. PerfCounter.Enabled = true;
  11117. return PerfCounter;
  11118. }());
  11119. BABYLON.PerfCounter = PerfCounter;
  11120. /**
  11121. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  11122. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  11123. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  11124. * @param name The name of the class, case should be preserved
  11125. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  11126. */
  11127. function className(name, module) {
  11128. return function (target) {
  11129. target["__bjsclassName__"] = name;
  11130. target["__bjsmoduleName__"] = (module != null) ? module : null;
  11131. };
  11132. }
  11133. BABYLON.className = className;
  11134. /**
  11135. * An implementation of a loop for asynchronous functions.
  11136. */
  11137. var AsyncLoop = /** @class */ (function () {
  11138. /**
  11139. * Constructor.
  11140. * @param iterations the number of iterations.
  11141. * @param func the function to run each iteration
  11142. * @param successCallback the callback that will be called upon succesful execution
  11143. * @param offset starting offset.
  11144. */
  11145. function AsyncLoop(
  11146. /**
  11147. * Defines the number of iterations for the loop
  11148. */
  11149. iterations, func, successCallback, offset) {
  11150. if (offset === void 0) { offset = 0; }
  11151. this.iterations = iterations;
  11152. this.index = offset - 1;
  11153. this._done = false;
  11154. this._fn = func;
  11155. this._successCallback = successCallback;
  11156. }
  11157. /**
  11158. * Execute the next iteration. Must be called after the last iteration was finished.
  11159. */
  11160. AsyncLoop.prototype.executeNext = function () {
  11161. if (!this._done) {
  11162. if (this.index + 1 < this.iterations) {
  11163. ++this.index;
  11164. this._fn(this);
  11165. }
  11166. else {
  11167. this.breakLoop();
  11168. }
  11169. }
  11170. };
  11171. /**
  11172. * Break the loop and run the success callback.
  11173. */
  11174. AsyncLoop.prototype.breakLoop = function () {
  11175. this._done = true;
  11176. this._successCallback();
  11177. };
  11178. /**
  11179. * Create and run an async loop.
  11180. * @param iterations the number of iterations.
  11181. * @param fn the function to run each iteration
  11182. * @param successCallback the callback that will be called upon succesful execution
  11183. * @param offset starting offset.
  11184. * @returns the created async loop object
  11185. */
  11186. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11187. if (offset === void 0) { offset = 0; }
  11188. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11189. loop.executeNext();
  11190. return loop;
  11191. };
  11192. /**
  11193. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11194. * @param iterations total number of iterations
  11195. * @param syncedIterations number of synchronous iterations in each async iteration.
  11196. * @param fn the function to call each iteration.
  11197. * @param callback a success call back that will be called when iterating stops.
  11198. * @param breakFunction a break condition (optional)
  11199. * @param timeout timeout settings for the setTimeout function. default - 0.
  11200. * @returns the created async loop object
  11201. */
  11202. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11203. if (timeout === void 0) { timeout = 0; }
  11204. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11205. if (breakFunction && breakFunction()) {
  11206. loop.breakLoop();
  11207. }
  11208. else {
  11209. setTimeout(function () {
  11210. for (var i = 0; i < syncedIterations; ++i) {
  11211. var iteration = (loop.index * syncedIterations) + i;
  11212. if (iteration >= iterations) {
  11213. break;
  11214. }
  11215. fn(iteration);
  11216. if (breakFunction && breakFunction()) {
  11217. loop.breakLoop();
  11218. break;
  11219. }
  11220. }
  11221. loop.executeNext();
  11222. }, timeout);
  11223. }
  11224. }, callback);
  11225. };
  11226. return AsyncLoop;
  11227. }());
  11228. BABYLON.AsyncLoop = AsyncLoop;
  11229. })(BABYLON || (BABYLON = {}));
  11230. //# sourceMappingURL=babylon.tools.js.map
  11231. var BABYLON;
  11232. (function (BABYLON) {
  11233. var PromiseStates;
  11234. (function (PromiseStates) {
  11235. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11236. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11237. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11238. })(PromiseStates || (PromiseStates = {}));
  11239. var FulFillmentAgregator = /** @class */ (function () {
  11240. function FulFillmentAgregator() {
  11241. this.count = 0;
  11242. this.target = 0;
  11243. this.results = [];
  11244. }
  11245. return FulFillmentAgregator;
  11246. }());
  11247. var InternalPromise = /** @class */ (function () {
  11248. function InternalPromise(resolver) {
  11249. var _this = this;
  11250. this._state = PromiseStates.Pending;
  11251. this._children = new Array();
  11252. this._rejectWasConsumed = false;
  11253. if (!resolver) {
  11254. return;
  11255. }
  11256. try {
  11257. resolver(function (value) {
  11258. _this._resolve(value);
  11259. }, function (reason) {
  11260. _this._reject(reason);
  11261. });
  11262. }
  11263. catch (e) {
  11264. this._reject(e);
  11265. }
  11266. }
  11267. Object.defineProperty(InternalPromise.prototype, "_result", {
  11268. get: function () {
  11269. return this._resultValue;
  11270. },
  11271. set: function (value) {
  11272. this._resultValue = value;
  11273. if (this._parent && this._parent._result === undefined) {
  11274. this._parent._result = value;
  11275. }
  11276. },
  11277. enumerable: true,
  11278. configurable: true
  11279. });
  11280. InternalPromise.prototype.catch = function (onRejected) {
  11281. return this.then(undefined, onRejected);
  11282. };
  11283. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11284. var _this = this;
  11285. var newPromise = new InternalPromise();
  11286. newPromise._onFulfilled = onFulfilled;
  11287. newPromise._onRejected = onRejected;
  11288. // Composition
  11289. this._children.push(newPromise);
  11290. newPromise._parent = this;
  11291. if (this._state !== PromiseStates.Pending) {
  11292. BABYLON.Tools.SetImmediate(function () {
  11293. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11294. var returnedValue = newPromise._resolve(_this._result);
  11295. if (returnedValue !== undefined && returnedValue !== null) {
  11296. if (returnedValue._state !== undefined) {
  11297. var returnedPromise = returnedValue;
  11298. newPromise._children.push(returnedPromise);
  11299. returnedPromise._parent = newPromise;
  11300. newPromise = returnedPromise;
  11301. }
  11302. else {
  11303. newPromise._result = returnedValue;
  11304. }
  11305. }
  11306. }
  11307. else {
  11308. newPromise._reject(_this._reason);
  11309. }
  11310. });
  11311. }
  11312. return newPromise;
  11313. };
  11314. InternalPromise.prototype._moveChildren = function (children) {
  11315. var _this = this;
  11316. var _a;
  11317. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11318. this._children.forEach(function (child) {
  11319. child._parent = _this;
  11320. });
  11321. if (this._state === PromiseStates.Fulfilled) {
  11322. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11323. var child = _b[_i];
  11324. child._resolve(this._result);
  11325. }
  11326. }
  11327. else if (this._state === PromiseStates.Rejected) {
  11328. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11329. var child = _d[_c];
  11330. child._reject(this._reason);
  11331. }
  11332. }
  11333. };
  11334. InternalPromise.prototype._resolve = function (value) {
  11335. try {
  11336. this._state = PromiseStates.Fulfilled;
  11337. var returnedValue = null;
  11338. if (this._onFulfilled) {
  11339. returnedValue = this._onFulfilled(value);
  11340. }
  11341. if (returnedValue !== undefined && returnedValue !== null) {
  11342. if (returnedValue._state !== undefined) {
  11343. // Transmit children
  11344. var returnedPromise = returnedValue;
  11345. returnedPromise._parent = this;
  11346. returnedPromise._moveChildren(this._children);
  11347. value = returnedPromise._result;
  11348. }
  11349. else {
  11350. value = returnedValue;
  11351. }
  11352. }
  11353. this._result = value;
  11354. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11355. var child = _a[_i];
  11356. child._resolve(value);
  11357. }
  11358. this._children.length = 0;
  11359. delete this._onFulfilled;
  11360. delete this._onRejected;
  11361. }
  11362. catch (e) {
  11363. this._reject(e, true);
  11364. }
  11365. };
  11366. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11367. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11368. this._state = PromiseStates.Rejected;
  11369. this._reason = reason;
  11370. if (this._onRejected && !onLocalThrow) {
  11371. try {
  11372. this._onRejected(reason);
  11373. this._rejectWasConsumed = true;
  11374. }
  11375. catch (e) {
  11376. reason = e;
  11377. }
  11378. }
  11379. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11380. var child = _a[_i];
  11381. if (this._rejectWasConsumed) {
  11382. child._resolve(null);
  11383. }
  11384. else {
  11385. child._reject(reason);
  11386. }
  11387. }
  11388. this._children.length = 0;
  11389. delete this._onFulfilled;
  11390. delete this._onRejected;
  11391. };
  11392. InternalPromise.resolve = function (value) {
  11393. var newPromise = new InternalPromise();
  11394. newPromise._resolve(value);
  11395. return newPromise;
  11396. };
  11397. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11398. promise.then(function (value) {
  11399. agregator.results[index] = value;
  11400. agregator.count++;
  11401. if (agregator.count === agregator.target) {
  11402. agregator.rootPromise._resolve(agregator.results);
  11403. }
  11404. return null;
  11405. }, function (reason) {
  11406. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11407. agregator.rootPromise._reject(reason);
  11408. }
  11409. });
  11410. };
  11411. InternalPromise.all = function (promises) {
  11412. var newPromise = new InternalPromise();
  11413. var agregator = new FulFillmentAgregator();
  11414. agregator.target = promises.length;
  11415. agregator.rootPromise = newPromise;
  11416. if (promises.length) {
  11417. for (var index = 0; index < promises.length; index++) {
  11418. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11419. }
  11420. }
  11421. else {
  11422. newPromise._resolve([]);
  11423. }
  11424. return newPromise;
  11425. };
  11426. InternalPromise.race = function (promises) {
  11427. var newPromise = new InternalPromise();
  11428. if (promises.length) {
  11429. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11430. var promise = promises_1[_i];
  11431. promise.then(function (value) {
  11432. if (newPromise) {
  11433. newPromise._resolve(value);
  11434. newPromise = null;
  11435. }
  11436. return null;
  11437. }, function (reason) {
  11438. if (newPromise) {
  11439. newPromise._reject(reason);
  11440. newPromise = null;
  11441. }
  11442. });
  11443. }
  11444. }
  11445. return newPromise;
  11446. };
  11447. return InternalPromise;
  11448. }());
  11449. /**
  11450. * Helper class that provides a small promise polyfill
  11451. */
  11452. var PromisePolyfill = /** @class */ (function () {
  11453. function PromisePolyfill() {
  11454. }
  11455. /**
  11456. * Static function used to check if the polyfill is required
  11457. * If this is the case then the function will inject the polyfill to window.Promise
  11458. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11459. */
  11460. PromisePolyfill.Apply = function (force) {
  11461. if (force === void 0) { force = false; }
  11462. if (force || typeof Promise === 'undefined') {
  11463. var root = window;
  11464. root.Promise = InternalPromise;
  11465. }
  11466. };
  11467. return PromisePolyfill;
  11468. }());
  11469. BABYLON.PromisePolyfill = PromisePolyfill;
  11470. })(BABYLON || (BABYLON = {}));
  11471. //# sourceMappingURL=babylon.promise.js.map
  11472. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11473. var BABYLON;
  11474. (function (BABYLON) {
  11475. /**
  11476. * Helper class to push actions to a pool of workers.
  11477. */
  11478. var WorkerPool = /** @class */ (function () {
  11479. /**
  11480. * Constructor
  11481. * @param workers Array of workers to use for actions
  11482. */
  11483. function WorkerPool(workers) {
  11484. this._pendingActions = new Array();
  11485. this._workerInfos = workers.map(function (worker) { return ({
  11486. worker: worker,
  11487. active: false
  11488. }); });
  11489. }
  11490. /**
  11491. * Terminates all workers and clears any pending actions.
  11492. */
  11493. WorkerPool.prototype.dispose = function () {
  11494. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11495. var workerInfo = _a[_i];
  11496. workerInfo.worker.terminate();
  11497. }
  11498. delete this._workerInfos;
  11499. delete this._pendingActions;
  11500. };
  11501. /**
  11502. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11503. * pended until a worker has completed its action.
  11504. * @param action The action to perform. Call onComplete when the action is complete.
  11505. */
  11506. WorkerPool.prototype.push = function (action) {
  11507. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11508. var workerInfo = _a[_i];
  11509. if (!workerInfo.active) {
  11510. this._execute(workerInfo, action);
  11511. return;
  11512. }
  11513. }
  11514. this._pendingActions.push(action);
  11515. };
  11516. WorkerPool.prototype._execute = function (workerInfo, action) {
  11517. var _this = this;
  11518. workerInfo.active = true;
  11519. action(workerInfo.worker, function () {
  11520. workerInfo.active = false;
  11521. var nextAction = _this._pendingActions.shift();
  11522. if (nextAction) {
  11523. _this._execute(workerInfo, nextAction);
  11524. }
  11525. });
  11526. };
  11527. return WorkerPool;
  11528. }());
  11529. BABYLON.WorkerPool = WorkerPool;
  11530. })(BABYLON || (BABYLON = {}));
  11531. //# sourceMappingURL=babylon.workerPool.js.map
  11532. var BABYLON;
  11533. (function (BABYLON) {
  11534. /**
  11535. * @hidden
  11536. **/
  11537. var _AlphaState = /** @class */ (function () {
  11538. /**
  11539. * Initializes the state.
  11540. */
  11541. function _AlphaState() {
  11542. this._isAlphaBlendDirty = false;
  11543. this._isBlendFunctionParametersDirty = false;
  11544. this._isBlendEquationParametersDirty = false;
  11545. this._isBlendConstantsDirty = false;
  11546. this._alphaBlend = false;
  11547. this._blendFunctionParameters = new Array(4);
  11548. this._blendEquationParameters = new Array(2);
  11549. this._blendConstants = new Array(4);
  11550. this.reset();
  11551. }
  11552. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11553. get: function () {
  11554. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11555. },
  11556. enumerable: true,
  11557. configurable: true
  11558. });
  11559. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11560. get: function () {
  11561. return this._alphaBlend;
  11562. },
  11563. set: function (value) {
  11564. if (this._alphaBlend === value) {
  11565. return;
  11566. }
  11567. this._alphaBlend = value;
  11568. this._isAlphaBlendDirty = true;
  11569. },
  11570. enumerable: true,
  11571. configurable: true
  11572. });
  11573. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11574. if (this._blendConstants[0] === r &&
  11575. this._blendConstants[1] === g &&
  11576. this._blendConstants[2] === b &&
  11577. this._blendConstants[3] === a) {
  11578. return;
  11579. }
  11580. this._blendConstants[0] = r;
  11581. this._blendConstants[1] = g;
  11582. this._blendConstants[2] = b;
  11583. this._blendConstants[3] = a;
  11584. this._isBlendConstantsDirty = true;
  11585. };
  11586. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11587. if (this._blendFunctionParameters[0] === value0 &&
  11588. this._blendFunctionParameters[1] === value1 &&
  11589. this._blendFunctionParameters[2] === value2 &&
  11590. this._blendFunctionParameters[3] === value3) {
  11591. return;
  11592. }
  11593. this._blendFunctionParameters[0] = value0;
  11594. this._blendFunctionParameters[1] = value1;
  11595. this._blendFunctionParameters[2] = value2;
  11596. this._blendFunctionParameters[3] = value3;
  11597. this._isBlendFunctionParametersDirty = true;
  11598. };
  11599. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11600. if (this._blendEquationParameters[0] === rgb &&
  11601. this._blendEquationParameters[1] === alpha) {
  11602. return;
  11603. }
  11604. this._blendEquationParameters[0] = rgb;
  11605. this._blendEquationParameters[1] = alpha;
  11606. this._isBlendEquationParametersDirty = true;
  11607. };
  11608. _AlphaState.prototype.reset = function () {
  11609. this._alphaBlend = false;
  11610. this._blendFunctionParameters[0] = null;
  11611. this._blendFunctionParameters[1] = null;
  11612. this._blendFunctionParameters[2] = null;
  11613. this._blendFunctionParameters[3] = null;
  11614. this._blendEquationParameters[0] = null;
  11615. this._blendEquationParameters[1] = null;
  11616. this._blendConstants[0] = null;
  11617. this._blendConstants[1] = null;
  11618. this._blendConstants[2] = null;
  11619. this._blendConstants[3] = null;
  11620. this._isAlphaBlendDirty = true;
  11621. this._isBlendFunctionParametersDirty = false;
  11622. this._isBlendEquationParametersDirty = false;
  11623. this._isBlendConstantsDirty = false;
  11624. };
  11625. _AlphaState.prototype.apply = function (gl) {
  11626. if (!this.isDirty) {
  11627. return;
  11628. }
  11629. // Alpha blend
  11630. if (this._isAlphaBlendDirty) {
  11631. if (this._alphaBlend) {
  11632. gl.enable(gl.BLEND);
  11633. }
  11634. else {
  11635. gl.disable(gl.BLEND);
  11636. }
  11637. this._isAlphaBlendDirty = false;
  11638. }
  11639. // Alpha function
  11640. if (this._isBlendFunctionParametersDirty) {
  11641. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11642. this._isBlendFunctionParametersDirty = false;
  11643. }
  11644. // Alpha equation
  11645. if (this._isBlendEquationParametersDirty) {
  11646. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11647. this._isBlendEquationParametersDirty = false;
  11648. }
  11649. // Constants
  11650. if (this._isBlendConstantsDirty) {
  11651. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11652. this._isBlendConstantsDirty = false;
  11653. }
  11654. };
  11655. return _AlphaState;
  11656. }());
  11657. BABYLON._AlphaState = _AlphaState;
  11658. })(BABYLON || (BABYLON = {}));
  11659. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11660. var BABYLON;
  11661. (function (BABYLON) {
  11662. /**
  11663. * @hidden
  11664. **/
  11665. var _DepthCullingState = /** @class */ (function () {
  11666. /**
  11667. * Initializes the state.
  11668. */
  11669. function _DepthCullingState() {
  11670. this._isDepthTestDirty = false;
  11671. this._isDepthMaskDirty = false;
  11672. this._isDepthFuncDirty = false;
  11673. this._isCullFaceDirty = false;
  11674. this._isCullDirty = false;
  11675. this._isZOffsetDirty = false;
  11676. this._isFrontFaceDirty = false;
  11677. this.reset();
  11678. }
  11679. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11680. get: function () {
  11681. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11682. },
  11683. enumerable: true,
  11684. configurable: true
  11685. });
  11686. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11687. get: function () {
  11688. return this._zOffset;
  11689. },
  11690. set: function (value) {
  11691. if (this._zOffset === value) {
  11692. return;
  11693. }
  11694. this._zOffset = value;
  11695. this._isZOffsetDirty = true;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11701. get: function () {
  11702. return this._cullFace;
  11703. },
  11704. set: function (value) {
  11705. if (this._cullFace === value) {
  11706. return;
  11707. }
  11708. this._cullFace = value;
  11709. this._isCullFaceDirty = true;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11715. get: function () {
  11716. return this._cull;
  11717. },
  11718. set: function (value) {
  11719. if (this._cull === value) {
  11720. return;
  11721. }
  11722. this._cull = value;
  11723. this._isCullDirty = true;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11729. get: function () {
  11730. return this._depthFunc;
  11731. },
  11732. set: function (value) {
  11733. if (this._depthFunc === value) {
  11734. return;
  11735. }
  11736. this._depthFunc = value;
  11737. this._isDepthFuncDirty = true;
  11738. },
  11739. enumerable: true,
  11740. configurable: true
  11741. });
  11742. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11743. get: function () {
  11744. return this._depthMask;
  11745. },
  11746. set: function (value) {
  11747. if (this._depthMask === value) {
  11748. return;
  11749. }
  11750. this._depthMask = value;
  11751. this._isDepthMaskDirty = true;
  11752. },
  11753. enumerable: true,
  11754. configurable: true
  11755. });
  11756. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11757. get: function () {
  11758. return this._depthTest;
  11759. },
  11760. set: function (value) {
  11761. if (this._depthTest === value) {
  11762. return;
  11763. }
  11764. this._depthTest = value;
  11765. this._isDepthTestDirty = true;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11771. get: function () {
  11772. return this._frontFace;
  11773. },
  11774. set: function (value) {
  11775. if (this._frontFace === value) {
  11776. return;
  11777. }
  11778. this._frontFace = value;
  11779. this._isFrontFaceDirty = true;
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. _DepthCullingState.prototype.reset = function () {
  11785. this._depthMask = true;
  11786. this._depthTest = true;
  11787. this._depthFunc = null;
  11788. this._cullFace = null;
  11789. this._cull = null;
  11790. this._zOffset = 0;
  11791. this._frontFace = null;
  11792. this._isDepthTestDirty = true;
  11793. this._isDepthMaskDirty = true;
  11794. this._isDepthFuncDirty = false;
  11795. this._isCullFaceDirty = false;
  11796. this._isCullDirty = false;
  11797. this._isZOffsetDirty = false;
  11798. this._isFrontFaceDirty = false;
  11799. };
  11800. _DepthCullingState.prototype.apply = function (gl) {
  11801. if (!this.isDirty) {
  11802. return;
  11803. }
  11804. // Cull
  11805. if (this._isCullDirty) {
  11806. if (this.cull) {
  11807. gl.enable(gl.CULL_FACE);
  11808. }
  11809. else {
  11810. gl.disable(gl.CULL_FACE);
  11811. }
  11812. this._isCullDirty = false;
  11813. }
  11814. // Cull face
  11815. if (this._isCullFaceDirty) {
  11816. gl.cullFace(this.cullFace);
  11817. this._isCullFaceDirty = false;
  11818. }
  11819. // Depth mask
  11820. if (this._isDepthMaskDirty) {
  11821. gl.depthMask(this.depthMask);
  11822. this._isDepthMaskDirty = false;
  11823. }
  11824. // Depth test
  11825. if (this._isDepthTestDirty) {
  11826. if (this.depthTest) {
  11827. gl.enable(gl.DEPTH_TEST);
  11828. }
  11829. else {
  11830. gl.disable(gl.DEPTH_TEST);
  11831. }
  11832. this._isDepthTestDirty = false;
  11833. }
  11834. // Depth func
  11835. if (this._isDepthFuncDirty) {
  11836. gl.depthFunc(this.depthFunc);
  11837. this._isDepthFuncDirty = false;
  11838. }
  11839. // zOffset
  11840. if (this._isZOffsetDirty) {
  11841. if (this.zOffset) {
  11842. gl.enable(gl.POLYGON_OFFSET_FILL);
  11843. gl.polygonOffset(this.zOffset, 0);
  11844. }
  11845. else {
  11846. gl.disable(gl.POLYGON_OFFSET_FILL);
  11847. }
  11848. this._isZOffsetDirty = false;
  11849. }
  11850. // Front face
  11851. if (this._isFrontFaceDirty) {
  11852. gl.frontFace(this.frontFace);
  11853. this._isFrontFaceDirty = false;
  11854. }
  11855. };
  11856. return _DepthCullingState;
  11857. }());
  11858. BABYLON._DepthCullingState = _DepthCullingState;
  11859. })(BABYLON || (BABYLON = {}));
  11860. //# sourceMappingURL=babylon.depthCullingState.js.map
  11861. var BABYLON;
  11862. (function (BABYLON) {
  11863. /**
  11864. * @hidden
  11865. **/
  11866. var _StencilState = /** @class */ (function () {
  11867. function _StencilState() {
  11868. this._isStencilTestDirty = false;
  11869. this._isStencilMaskDirty = false;
  11870. this._isStencilFuncDirty = false;
  11871. this._isStencilOpDirty = false;
  11872. this.reset();
  11873. }
  11874. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11875. get: function () {
  11876. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11877. },
  11878. enumerable: true,
  11879. configurable: true
  11880. });
  11881. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11882. get: function () {
  11883. return this._stencilFunc;
  11884. },
  11885. set: function (value) {
  11886. if (this._stencilFunc === value) {
  11887. return;
  11888. }
  11889. this._stencilFunc = value;
  11890. this._isStencilFuncDirty = true;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11896. get: function () {
  11897. return this._stencilFuncRef;
  11898. },
  11899. set: function (value) {
  11900. if (this._stencilFuncRef === value) {
  11901. return;
  11902. }
  11903. this._stencilFuncRef = value;
  11904. this._isStencilFuncDirty = true;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11910. get: function () {
  11911. return this._stencilFuncMask;
  11912. },
  11913. set: function (value) {
  11914. if (this._stencilFuncMask === value) {
  11915. return;
  11916. }
  11917. this._stencilFuncMask = value;
  11918. this._isStencilFuncDirty = true;
  11919. },
  11920. enumerable: true,
  11921. configurable: true
  11922. });
  11923. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11924. get: function () {
  11925. return this._stencilOpStencilFail;
  11926. },
  11927. set: function (value) {
  11928. if (this._stencilOpStencilFail === value) {
  11929. return;
  11930. }
  11931. this._stencilOpStencilFail = value;
  11932. this._isStencilOpDirty = true;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11938. get: function () {
  11939. return this._stencilOpDepthFail;
  11940. },
  11941. set: function (value) {
  11942. if (this._stencilOpDepthFail === value) {
  11943. return;
  11944. }
  11945. this._stencilOpDepthFail = value;
  11946. this._isStencilOpDirty = true;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11952. get: function () {
  11953. return this._stencilOpStencilDepthPass;
  11954. },
  11955. set: function (value) {
  11956. if (this._stencilOpStencilDepthPass === value) {
  11957. return;
  11958. }
  11959. this._stencilOpStencilDepthPass = value;
  11960. this._isStencilOpDirty = true;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11966. get: function () {
  11967. return this._stencilMask;
  11968. },
  11969. set: function (value) {
  11970. if (this._stencilMask === value) {
  11971. return;
  11972. }
  11973. this._stencilMask = value;
  11974. this._isStencilMaskDirty = true;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11980. get: function () {
  11981. return this._stencilTest;
  11982. },
  11983. set: function (value) {
  11984. if (this._stencilTest === value) {
  11985. return;
  11986. }
  11987. this._stencilTest = value;
  11988. this._isStencilTestDirty = true;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. _StencilState.prototype.reset = function () {
  11994. this._stencilTest = false;
  11995. this._stencilMask = 0xFF;
  11996. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11997. this._stencilFuncRef = 1;
  11998. this._stencilFuncMask = 0xFF;
  11999. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12000. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12001. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12002. this._isStencilTestDirty = true;
  12003. this._isStencilMaskDirty = true;
  12004. this._isStencilFuncDirty = true;
  12005. this._isStencilOpDirty = true;
  12006. };
  12007. _StencilState.prototype.apply = function (gl) {
  12008. if (!this.isDirty) {
  12009. return;
  12010. }
  12011. // Stencil test
  12012. if (this._isStencilTestDirty) {
  12013. if (this.stencilTest) {
  12014. gl.enable(gl.STENCIL_TEST);
  12015. }
  12016. else {
  12017. gl.disable(gl.STENCIL_TEST);
  12018. }
  12019. this._isStencilTestDirty = false;
  12020. }
  12021. // Stencil mask
  12022. if (this._isStencilMaskDirty) {
  12023. gl.stencilMask(this.stencilMask);
  12024. this._isStencilMaskDirty = false;
  12025. }
  12026. // Stencil func
  12027. if (this._isStencilFuncDirty) {
  12028. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12029. this._isStencilFuncDirty = false;
  12030. }
  12031. // Stencil op
  12032. if (this._isStencilOpDirty) {
  12033. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12034. this._isStencilOpDirty = false;
  12035. }
  12036. };
  12037. return _StencilState;
  12038. }());
  12039. BABYLON._StencilState = _StencilState;
  12040. })(BABYLON || (BABYLON = {}));
  12041. //# sourceMappingURL=babylon.stencilState.js.map
  12042. var __assign = (this && this.__assign) || function () {
  12043. __assign = Object.assign || function(t) {
  12044. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12045. s = arguments[i];
  12046. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12047. t[p] = s[p];
  12048. }
  12049. return t;
  12050. };
  12051. return __assign.apply(this, arguments);
  12052. };
  12053. var BABYLON;
  12054. (function (BABYLON) {
  12055. /**
  12056. * Keeps track of all the buffer info used in engine.
  12057. */
  12058. var BufferPointer = /** @class */ (function () {
  12059. function BufferPointer() {
  12060. }
  12061. return BufferPointer;
  12062. }());
  12063. /**
  12064. * Interface for attribute information associated with buffer instanciation
  12065. */
  12066. var InstancingAttributeInfo = /** @class */ (function () {
  12067. function InstancingAttributeInfo() {
  12068. }
  12069. return InstancingAttributeInfo;
  12070. }());
  12071. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12072. /**
  12073. * Define options used to create a render target texture
  12074. */
  12075. var RenderTargetCreationOptions = /** @class */ (function () {
  12076. function RenderTargetCreationOptions() {
  12077. }
  12078. return RenderTargetCreationOptions;
  12079. }());
  12080. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12081. /**
  12082. * Define options used to create a depth texture
  12083. */
  12084. var DepthTextureCreationOptions = /** @class */ (function () {
  12085. function DepthTextureCreationOptions() {
  12086. }
  12087. return DepthTextureCreationOptions;
  12088. }());
  12089. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12090. /**
  12091. * Class used to describe the capabilities of the engine relatively to the current browser
  12092. */
  12093. var EngineCapabilities = /** @class */ (function () {
  12094. function EngineCapabilities() {
  12095. }
  12096. return EngineCapabilities;
  12097. }());
  12098. BABYLON.EngineCapabilities = EngineCapabilities;
  12099. /**
  12100. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12101. */
  12102. var Engine = /** @class */ (function () {
  12103. /**
  12104. * Creates a new engine
  12105. * @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
  12106. * @param antialias defines enable antialiasing (default: false)
  12107. * @param options defines further options to be sent to the getContext() function
  12108. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12109. */
  12110. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12111. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12112. var _this = this;
  12113. // Public members
  12114. /**
  12115. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12116. */
  12117. this.forcePOTTextures = false;
  12118. /**
  12119. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12120. */
  12121. this.isFullscreen = false;
  12122. /**
  12123. * Gets a boolean indicating if the pointer is currently locked
  12124. */
  12125. this.isPointerLock = false;
  12126. /**
  12127. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12128. */
  12129. this.cullBackFaces = true;
  12130. /**
  12131. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12132. */
  12133. this.renderEvenInBackground = true;
  12134. /**
  12135. * Gets or sets a boolean indicating that cache can be kept between frames
  12136. */
  12137. this.preventCacheWipeBetweenFrames = false;
  12138. /**
  12139. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12140. **/
  12141. this.enableOfflineSupport = false;
  12142. /**
  12143. * 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)
  12144. **/
  12145. this.disableManifestCheck = false;
  12146. /**
  12147. * Gets the list of created scenes
  12148. */
  12149. this.scenes = new Array();
  12150. /**
  12151. * Gets the list of created postprocesses
  12152. */
  12153. this.postProcesses = new Array();
  12154. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12155. this.validateShaderPrograms = false;
  12156. // Observables
  12157. /**
  12158. * Observable event triggered each time the rendering canvas is resized
  12159. */
  12160. this.onResizeObservable = new BABYLON.Observable();
  12161. /**
  12162. * Observable event triggered each time the canvas loses focus
  12163. */
  12164. this.onCanvasBlurObservable = new BABYLON.Observable();
  12165. /**
  12166. * Observable event triggered each time the canvas gains focus
  12167. */
  12168. this.onCanvasFocusObservable = new BABYLON.Observable();
  12169. /**
  12170. * Observable event triggered each time the canvas receives pointerout event
  12171. */
  12172. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12173. /**
  12174. * Observable event triggered before each texture is initialized
  12175. */
  12176. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12177. //WebVR
  12178. this._vrDisplay = undefined;
  12179. this._vrSupported = false;
  12180. this._vrExclusivePointerMode = false;
  12181. // Uniform buffers list
  12182. /**
  12183. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12184. */
  12185. this.disableUniformBuffers = false;
  12186. /** @hidden */
  12187. this._uniformBuffers = new Array();
  12188. // Observables
  12189. /**
  12190. * Observable raised when the engine begins a new frame
  12191. */
  12192. this.onBeginFrameObservable = new BABYLON.Observable();
  12193. /**
  12194. * Observable raised when the engine ends the current frame
  12195. */
  12196. this.onEndFrameObservable = new BABYLON.Observable();
  12197. /**
  12198. * Observable raised when the engine is about to compile a shader
  12199. */
  12200. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12201. /**
  12202. * Observable raised when the engine has jsut compiled a shader
  12203. */
  12204. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12205. this._windowIsBackground = false;
  12206. this._webGLVersion = 1.0;
  12207. /** @hidden */
  12208. this._badOS = false;
  12209. /** @hidden */
  12210. this._badDesktopOS = false;
  12211. /**
  12212. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12213. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12214. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12215. */
  12216. this.disableTextureBindingOptimization = false;
  12217. /**
  12218. * Observable signaled when VR display mode changes
  12219. */
  12220. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12221. /**
  12222. * Observable signaled when VR request present is complete
  12223. */
  12224. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12225. /**
  12226. * Observable signaled when VR request present starts
  12227. */
  12228. this.onVRRequestPresentStart = new BABYLON.Observable();
  12229. this._colorWrite = true;
  12230. /** @hidden */
  12231. this._drawCalls = new BABYLON.PerfCounter();
  12232. /** @hidden */
  12233. this._textureCollisions = new BABYLON.PerfCounter();
  12234. this._renderingQueueLaunched = false;
  12235. this._activeRenderLoops = new Array();
  12236. // Deterministic lockstepMaxSteps
  12237. this._deterministicLockstep = false;
  12238. this._lockstepMaxSteps = 4;
  12239. // Lost context
  12240. /**
  12241. * Observable signaled when a context lost event is raised
  12242. */
  12243. this.onContextLostObservable = new BABYLON.Observable();
  12244. /**
  12245. * Observable signaled when a context restored event is raised
  12246. */
  12247. this.onContextRestoredObservable = new BABYLON.Observable();
  12248. this._contextWasLost = false;
  12249. this._doNotHandleContextLost = false;
  12250. // FPS
  12251. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12252. this._fps = 60;
  12253. this._deltaTime = 0;
  12254. /**
  12255. * Turn this value on if you want to pause FPS computation when in background
  12256. */
  12257. this.disablePerformanceMonitorInBackground = false;
  12258. // States
  12259. /** @hidden */
  12260. this._depthCullingState = new BABYLON._DepthCullingState();
  12261. /** @hidden */
  12262. this._stencilState = new BABYLON._StencilState();
  12263. /** @hidden */
  12264. this._alphaState = new BABYLON._AlphaState();
  12265. /** @hidden */
  12266. this._alphaMode = Engine.ALPHA_DISABLE;
  12267. // Cache
  12268. this._internalTexturesCache = new Array();
  12269. /** @hidden */
  12270. this._activeChannel = 0;
  12271. this._currentTextureChannel = -1;
  12272. /** @hidden */
  12273. this._boundTexturesCache = {};
  12274. this._compiledEffects = {};
  12275. this._vertexAttribArraysEnabled = [];
  12276. this._uintIndicesCurrentlySet = false;
  12277. this._currentBoundBuffer = new Array();
  12278. /** @hidden */
  12279. this._currentFramebuffer = null;
  12280. this._currentBufferPointers = new Array();
  12281. this._currentInstanceLocations = new Array();
  12282. this._currentInstanceBuffers = new Array();
  12283. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12284. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12285. this._vaoRecordInProgress = false;
  12286. this._mustWipeVertexAttributes = false;
  12287. this._nextFreeTextureSlots = new Array();
  12288. this._maxSimultaneousTextures = 0;
  12289. this._activeRequests = new Array();
  12290. // Hardware supported Compressed Textures
  12291. this._texturesSupported = new Array();
  12292. /**
  12293. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12294. */
  12295. this.premultipliedAlpha = true;
  12296. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12297. this._onVRFullScreenTriggered = function () {
  12298. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12299. //get the old size before we change
  12300. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12301. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12302. //get the width and height, change the render size
  12303. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12304. _this.setHardwareScalingLevel(1);
  12305. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12306. }
  12307. else {
  12308. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12309. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12310. }
  12311. };
  12312. this._unpackFlipYCached = null;
  12313. /**
  12314. * In case you are sharing the context with other applications, it might
  12315. * be interested to not cache the unpack flip y state to ensure a consistent
  12316. * value would be set.
  12317. */
  12318. this.enableUnpackFlipYCached = true;
  12319. this._boundUniforms = {};
  12320. // Register promises
  12321. BABYLON.PromisePolyfill.Apply();
  12322. var canvas = null;
  12323. Engine.Instances.push(this);
  12324. if (!canvasOrContext) {
  12325. return;
  12326. }
  12327. options = options || {};
  12328. if (canvasOrContext.getContext) {
  12329. canvas = canvasOrContext;
  12330. this._renderingCanvas = canvas;
  12331. if (antialias != null) {
  12332. options.antialias = antialias;
  12333. }
  12334. if (options.deterministicLockstep === undefined) {
  12335. options.deterministicLockstep = false;
  12336. }
  12337. if (options.lockstepMaxSteps === undefined) {
  12338. options.lockstepMaxSteps = 4;
  12339. }
  12340. if (options.preserveDrawingBuffer === undefined) {
  12341. options.preserveDrawingBuffer = false;
  12342. }
  12343. if (options.audioEngine === undefined) {
  12344. options.audioEngine = true;
  12345. }
  12346. if (options.stencil === undefined) {
  12347. options.stencil = true;
  12348. }
  12349. if (options.premultipliedAlpha === false) {
  12350. this.premultipliedAlpha = false;
  12351. }
  12352. this._deterministicLockstep = options.deterministicLockstep;
  12353. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12354. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12355. // Exceptions
  12356. if (navigator && navigator.userAgent) {
  12357. var ua = navigator.userAgent;
  12358. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12359. var exception = _a[_i];
  12360. var key = exception.key;
  12361. var targets = exception.targets;
  12362. if (ua.indexOf(key) > -1) {
  12363. if (exception.capture && exception.captureConstraint) {
  12364. var capture = exception.capture;
  12365. var constraint = exception.captureConstraint;
  12366. var regex = new RegExp(capture);
  12367. var matches = regex.exec(ua);
  12368. if (matches && matches.length > 0) {
  12369. var capturedValue = parseInt(matches[matches.length - 1]);
  12370. if (capturedValue >= constraint) {
  12371. continue;
  12372. }
  12373. }
  12374. }
  12375. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12376. var target = targets_1[_b];
  12377. switch (target) {
  12378. case "uniformBuffer":
  12379. this.disableUniformBuffers = true;
  12380. break;
  12381. case "textureBindingOptimization":
  12382. this.disableTextureBindingOptimization = true;
  12383. break;
  12384. }
  12385. }
  12386. }
  12387. }
  12388. }
  12389. // GL
  12390. if (!options.disableWebGL2Support) {
  12391. try {
  12392. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12393. if (this._gl) {
  12394. this._webGLVersion = 2.0;
  12395. // Prevent weird browsers to lie :-)
  12396. if (!this._gl.deleteQuery) {
  12397. this._webGLVersion = 1.0;
  12398. }
  12399. }
  12400. }
  12401. catch (e) {
  12402. // Do nothing
  12403. }
  12404. }
  12405. if (!this._gl) {
  12406. if (!canvas) {
  12407. throw new Error("The provided canvas is null or undefined.");
  12408. }
  12409. try {
  12410. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12411. }
  12412. catch (e) {
  12413. throw new Error("WebGL not supported");
  12414. }
  12415. }
  12416. if (!this._gl) {
  12417. throw new Error("WebGL not supported");
  12418. }
  12419. this._onCanvasFocus = function () {
  12420. _this.onCanvasFocusObservable.notifyObservers(_this);
  12421. };
  12422. this._onCanvasBlur = function () {
  12423. _this.onCanvasBlurObservable.notifyObservers(_this);
  12424. };
  12425. canvas.addEventListener("focus", this._onCanvasFocus);
  12426. canvas.addEventListener("blur", this._onCanvasBlur);
  12427. this._onBlur = function () {
  12428. if (_this.disablePerformanceMonitorInBackground) {
  12429. _this._performanceMonitor.disable();
  12430. }
  12431. _this._windowIsBackground = true;
  12432. };
  12433. this._onFocus = function () {
  12434. if (_this.disablePerformanceMonitorInBackground) {
  12435. _this._performanceMonitor.enable();
  12436. }
  12437. _this._windowIsBackground = false;
  12438. };
  12439. this._onCanvasPointerOut = function (ev) {
  12440. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12441. };
  12442. window.addEventListener("blur", this._onBlur);
  12443. window.addEventListener("focus", this._onFocus);
  12444. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12445. // Context lost
  12446. if (!this._doNotHandleContextLost) {
  12447. this._onContextLost = function (evt) {
  12448. evt.preventDefault();
  12449. _this._contextWasLost = true;
  12450. BABYLON.Tools.Warn("WebGL context lost.");
  12451. _this.onContextLostObservable.notifyObservers(_this);
  12452. };
  12453. this._onContextRestored = function (evt) {
  12454. // Adding a timeout to avoid race condition at browser level
  12455. setTimeout(function () {
  12456. // Rebuild gl context
  12457. _this._initGLContext();
  12458. // Rebuild effects
  12459. _this._rebuildEffects();
  12460. // Rebuild textures
  12461. _this._rebuildInternalTextures();
  12462. // Rebuild buffers
  12463. _this._rebuildBuffers();
  12464. // Cache
  12465. _this.wipeCaches(true);
  12466. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12467. _this.onContextRestoredObservable.notifyObservers(_this);
  12468. _this._contextWasLost = false;
  12469. }, 0);
  12470. };
  12471. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12472. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12473. }
  12474. }
  12475. else {
  12476. this._gl = canvasOrContext;
  12477. this._renderingCanvas = this._gl.canvas;
  12478. if (this._gl.renderbufferStorageMultisample) {
  12479. this._webGLVersion = 2.0;
  12480. }
  12481. options.stencil = this._gl.getContextAttributes().stencil;
  12482. }
  12483. // Viewport
  12484. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12485. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12486. this.resize();
  12487. this._isStencilEnable = options.stencil ? true : false;
  12488. this._initGLContext();
  12489. if (canvas) {
  12490. // Fullscreen
  12491. this._onFullscreenChange = function () {
  12492. if (document.fullscreen !== undefined) {
  12493. _this.isFullscreen = document.fullscreen;
  12494. }
  12495. else if (document.mozFullScreen !== undefined) {
  12496. _this.isFullscreen = document.mozFullScreen;
  12497. }
  12498. else if (document.webkitIsFullScreen !== undefined) {
  12499. _this.isFullscreen = document.webkitIsFullScreen;
  12500. }
  12501. else if (document.msIsFullScreen !== undefined) {
  12502. _this.isFullscreen = document.msIsFullScreen;
  12503. }
  12504. // Pointer lock
  12505. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12506. canvas.requestPointerLock = canvas.requestPointerLock ||
  12507. canvas.msRequestPointerLock ||
  12508. canvas.mozRequestPointerLock ||
  12509. canvas.webkitRequestPointerLock;
  12510. if (canvas.requestPointerLock) {
  12511. canvas.requestPointerLock();
  12512. }
  12513. }
  12514. };
  12515. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12516. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12517. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12518. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12519. // Pointer lock
  12520. this._onPointerLockChange = function () {
  12521. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12522. document.webkitPointerLockElement === canvas ||
  12523. document.msPointerLockElement === canvas ||
  12524. document.pointerLockElement === canvas);
  12525. };
  12526. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12527. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12528. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12529. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12530. this._onVRDisplayPointerRestricted = function () {
  12531. if (canvas) {
  12532. canvas.requestPointerLock();
  12533. }
  12534. };
  12535. this._onVRDisplayPointerUnrestricted = function () {
  12536. document.exitPointerLock();
  12537. };
  12538. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12539. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12540. }
  12541. // Create Audio Engine if needed.
  12542. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12543. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12544. }
  12545. // Prepare buffer pointers
  12546. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12547. this._currentBufferPointers[i] = new BufferPointer();
  12548. }
  12549. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12550. // Load WebVR Devices
  12551. if (options.autoEnableWebVR) {
  12552. this.initWebVR();
  12553. }
  12554. // Detect if we are running on a faulty buggy OS.
  12555. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12556. // Detect if we are running on a faulty buggy desktop OS.
  12557. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12558. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12559. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12560. }
  12561. Object.defineProperty(Engine, "LastCreatedEngine", {
  12562. /**
  12563. * Gets the latest created engine
  12564. */
  12565. get: function () {
  12566. if (Engine.Instances.length === 0) {
  12567. return null;
  12568. }
  12569. return Engine.Instances[Engine.Instances.length - 1];
  12570. },
  12571. enumerable: true,
  12572. configurable: true
  12573. });
  12574. Object.defineProperty(Engine, "LastCreatedScene", {
  12575. /**
  12576. * Gets the latest created scene
  12577. */
  12578. get: function () {
  12579. var lastCreatedEngine = Engine.LastCreatedEngine;
  12580. if (!lastCreatedEngine) {
  12581. return null;
  12582. }
  12583. if (lastCreatedEngine.scenes.length === 0) {
  12584. return null;
  12585. }
  12586. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12587. },
  12588. enumerable: true,
  12589. configurable: true
  12590. });
  12591. /**
  12592. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12593. * @param flag defines which part of the materials must be marked as dirty
  12594. * @param predicate defines a predicate used to filter which materials should be affected
  12595. */
  12596. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12597. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12598. var engine = Engine.Instances[engineIndex];
  12599. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12600. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12601. }
  12602. }
  12603. };
  12604. Object.defineProperty(Engine, "Version", {
  12605. /**
  12606. * Returns the current version of the framework
  12607. */
  12608. get: function () {
  12609. return "3.3.0-rc.4";
  12610. },
  12611. enumerable: true,
  12612. configurable: true
  12613. });
  12614. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12615. /**
  12616. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12617. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12618. */
  12619. get: function () {
  12620. return this._vrExclusivePointerMode;
  12621. },
  12622. enumerable: true,
  12623. configurable: true
  12624. });
  12625. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12626. /**
  12627. * Gets a boolean indicating that the engine supports uniform buffers
  12628. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12629. */
  12630. get: function () {
  12631. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12632. },
  12633. enumerable: true,
  12634. configurable: true
  12635. });
  12636. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12637. /**
  12638. * Gets a boolean indicating that only power of 2 textures are supported
  12639. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12640. */
  12641. get: function () {
  12642. return this._webGLVersion < 2 || this.forcePOTTextures;
  12643. },
  12644. enumerable: true,
  12645. configurable: true
  12646. });
  12647. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12648. /**
  12649. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12650. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12651. */
  12652. get: function () {
  12653. return this._doNotHandleContextLost;
  12654. },
  12655. set: function (value) {
  12656. this._doNotHandleContextLost = value;
  12657. },
  12658. enumerable: true,
  12659. configurable: true
  12660. });
  12661. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12662. /**
  12663. * Gets the performance monitor attached to this engine
  12664. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12665. */
  12666. get: function () {
  12667. return this._performanceMonitor;
  12668. },
  12669. enumerable: true,
  12670. configurable: true
  12671. });
  12672. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12673. /**
  12674. * Gets the list of texture formats supported
  12675. */
  12676. get: function () {
  12677. return this._texturesSupported;
  12678. },
  12679. enumerable: true,
  12680. configurable: true
  12681. });
  12682. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12683. /**
  12684. * Gets the list of texture formats in use
  12685. */
  12686. get: function () {
  12687. return this._textureFormatInUse;
  12688. },
  12689. enumerable: true,
  12690. configurable: true
  12691. });
  12692. Object.defineProperty(Engine.prototype, "currentViewport", {
  12693. /**
  12694. * Gets the current viewport
  12695. */
  12696. get: function () {
  12697. return this._cachedViewport;
  12698. },
  12699. enumerable: true,
  12700. configurable: true
  12701. });
  12702. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12703. /**
  12704. * Gets the default empty texture
  12705. */
  12706. get: function () {
  12707. if (!this._emptyTexture) {
  12708. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12709. }
  12710. return this._emptyTexture;
  12711. },
  12712. enumerable: true,
  12713. configurable: true
  12714. });
  12715. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12716. /**
  12717. * Gets the default empty 3D texture
  12718. */
  12719. get: function () {
  12720. if (!this._emptyTexture3D) {
  12721. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12722. }
  12723. return this._emptyTexture3D;
  12724. },
  12725. enumerable: true,
  12726. configurable: true
  12727. });
  12728. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12729. /**
  12730. * Gets the default empty cube texture
  12731. */
  12732. get: function () {
  12733. if (!this._emptyCubeTexture) {
  12734. var faceData = new Uint8Array(4);
  12735. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12736. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12737. }
  12738. return this._emptyCubeTexture;
  12739. },
  12740. enumerable: true,
  12741. configurable: true
  12742. });
  12743. Engine.prototype._rebuildInternalTextures = function () {
  12744. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12745. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12746. var internalTexture = currentState_1[_i];
  12747. internalTexture._rebuild();
  12748. }
  12749. };
  12750. Engine.prototype._rebuildEffects = function () {
  12751. for (var key in this._compiledEffects) {
  12752. var effect = this._compiledEffects[key];
  12753. effect._prepareEffect();
  12754. }
  12755. BABYLON.Effect.ResetCache();
  12756. };
  12757. Engine.prototype._rebuildBuffers = function () {
  12758. // Index / Vertex
  12759. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12760. var scene = _a[_i];
  12761. scene.resetCachedMaterial();
  12762. scene._rebuildGeometries();
  12763. scene._rebuildTextures();
  12764. }
  12765. // Uniforms
  12766. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12767. var uniformBuffer = _c[_b];
  12768. uniformBuffer._rebuild();
  12769. }
  12770. };
  12771. Engine.prototype._initGLContext = function () {
  12772. // Caps
  12773. this._caps = new EngineCapabilities();
  12774. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12775. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12776. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12777. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12778. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12779. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12780. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12781. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12782. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12783. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12784. // Infos
  12785. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12786. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12787. if (rendererInfo != null) {
  12788. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12789. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12790. }
  12791. if (!this._glVendor) {
  12792. this._glVendor = "Unknown vendor";
  12793. }
  12794. if (!this._glRenderer) {
  12795. this._glRenderer = "Unknown renderer";
  12796. }
  12797. // Constants
  12798. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12799. if (this._gl.RGBA16F !== 0x881A) {
  12800. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12801. }
  12802. if (this._gl.RGBA32F !== 0x8814) {
  12803. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12804. }
  12805. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12806. this._gl.DEPTH24_STENCIL8 = 35056;
  12807. }
  12808. // Extensions
  12809. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12810. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12811. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12812. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12813. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12814. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12815. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12816. 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');
  12817. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12818. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12819. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12820. this._caps.highPrecisionShaderSupported = true;
  12821. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12822. if (this._caps.timerQuery) {
  12823. if (this._webGLVersion === 1) {
  12824. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12825. }
  12826. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12827. }
  12828. // Checks if some of the format renders first to allow the use of webgl inspector.
  12829. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12830. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12831. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12832. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12833. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12834. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12835. if (this._webGLVersion > 1) {
  12836. this._gl.HALF_FLOAT_OES = 0x140B;
  12837. }
  12838. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12839. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12840. // Draw buffers
  12841. if (this._webGLVersion > 1) {
  12842. this._caps.drawBuffersExtension = true;
  12843. }
  12844. else {
  12845. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12846. if (drawBuffersExtension !== null) {
  12847. this._caps.drawBuffersExtension = true;
  12848. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12849. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12850. for (var i = 0; i < 16; i++) {
  12851. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12852. }
  12853. }
  12854. else {
  12855. this._caps.drawBuffersExtension = false;
  12856. }
  12857. }
  12858. // Depth Texture
  12859. if (this._webGLVersion > 1) {
  12860. this._caps.depthTextureExtension = true;
  12861. }
  12862. else {
  12863. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12864. if (depthTextureExtension != null) {
  12865. this._caps.depthTextureExtension = true;
  12866. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12867. }
  12868. }
  12869. // Vertex array object
  12870. if (this._webGLVersion > 1) {
  12871. this._caps.vertexArrayObject = true;
  12872. }
  12873. else {
  12874. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12875. if (vertexArrayObjectExtension != null) {
  12876. this._caps.vertexArrayObject = true;
  12877. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12878. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12879. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12880. }
  12881. else {
  12882. this._caps.vertexArrayObject = false;
  12883. }
  12884. }
  12885. // Instances count
  12886. if (this._webGLVersion > 1) {
  12887. this._caps.instancedArrays = true;
  12888. }
  12889. else {
  12890. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12891. if (instanceExtension != null) {
  12892. this._caps.instancedArrays = true;
  12893. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12894. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12895. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12896. }
  12897. else {
  12898. this._caps.instancedArrays = false;
  12899. }
  12900. }
  12901. // Intelligently add supported compressed formats in order to check for.
  12902. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12903. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12904. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12905. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12906. if (this._caps.astc) {
  12907. this.texturesSupported.push('-astc.ktx');
  12908. }
  12909. if (this._caps.s3tc) {
  12910. this.texturesSupported.push('-dxt.ktx');
  12911. }
  12912. if (this._caps.pvrtc) {
  12913. this.texturesSupported.push('-pvrtc.ktx');
  12914. }
  12915. if (this._caps.etc2) {
  12916. this.texturesSupported.push('-etc2.ktx');
  12917. }
  12918. if (this._caps.etc1) {
  12919. this.texturesSupported.push('-etc1.ktx');
  12920. }
  12921. if (this._gl.getShaderPrecisionFormat) {
  12922. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12923. if (highp) {
  12924. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12925. }
  12926. }
  12927. // Depth buffer
  12928. this.setDepthBuffer(true);
  12929. this.setDepthFunctionToLessOrEqual();
  12930. this.setDepthWrite(true);
  12931. // Texture maps
  12932. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12933. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12934. this._nextFreeTextureSlots.push(slot);
  12935. }
  12936. };
  12937. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12938. /**
  12939. * Gets version of the current webGL context
  12940. */
  12941. get: function () {
  12942. return this._webGLVersion;
  12943. },
  12944. enumerable: true,
  12945. configurable: true
  12946. });
  12947. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12948. /**
  12949. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12950. */
  12951. get: function () {
  12952. return this._isStencilEnable;
  12953. },
  12954. enumerable: true,
  12955. configurable: true
  12956. });
  12957. Engine.prototype._prepareWorkingCanvas = function () {
  12958. if (this._workingCanvas) {
  12959. return;
  12960. }
  12961. this._workingCanvas = document.createElement("canvas");
  12962. var context = this._workingCanvas.getContext("2d");
  12963. if (context) {
  12964. this._workingContext = context;
  12965. }
  12966. };
  12967. /**
  12968. * Reset the texture cache to empty state
  12969. */
  12970. Engine.prototype.resetTextureCache = function () {
  12971. for (var key in this._boundTexturesCache) {
  12972. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12973. continue;
  12974. }
  12975. var boundTexture = this._boundTexturesCache[key];
  12976. if (boundTexture) {
  12977. this._removeDesignatedSlot(boundTexture);
  12978. }
  12979. this._boundTexturesCache[key] = null;
  12980. }
  12981. if (!this.disableTextureBindingOptimization) {
  12982. this._nextFreeTextureSlots = [];
  12983. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12984. this._nextFreeTextureSlots.push(slot);
  12985. }
  12986. }
  12987. this._currentTextureChannel = -1;
  12988. };
  12989. /**
  12990. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12991. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12992. * @returns true if engine is in deterministic lock step mode
  12993. */
  12994. Engine.prototype.isDeterministicLockStep = function () {
  12995. return this._deterministicLockstep;
  12996. };
  12997. /**
  12998. * Gets the max steps when engine is running in deterministic lock step
  12999. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13000. * @returns the max steps
  13001. */
  13002. Engine.prototype.getLockstepMaxSteps = function () {
  13003. return this._lockstepMaxSteps;
  13004. };
  13005. /**
  13006. * Gets an object containing information about the current webGL context
  13007. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13008. */
  13009. Engine.prototype.getGlInfo = function () {
  13010. return {
  13011. vendor: this._glVendor,
  13012. renderer: this._glRenderer,
  13013. version: this._glVersion
  13014. };
  13015. };
  13016. /**
  13017. * Gets current aspect ratio
  13018. * @param camera defines the camera to use to get the aspect ratio
  13019. * @param useScreen defines if screen size must be used (or the current render target if any)
  13020. * @returns a number defining the aspect ratio
  13021. */
  13022. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13023. if (useScreen === void 0) { useScreen = false; }
  13024. var viewport = camera.viewport;
  13025. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13026. };
  13027. /**
  13028. * Gets current screen aspect ratio
  13029. * @returns a number defining the aspect ratio
  13030. */
  13031. Engine.prototype.getScreenAspectRatio = function () {
  13032. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13033. };
  13034. /**
  13035. * Gets the current render width
  13036. * @param useScreen defines if screen size must be used (or the current render target if any)
  13037. * @returns a number defining the current render width
  13038. */
  13039. Engine.prototype.getRenderWidth = function (useScreen) {
  13040. if (useScreen === void 0) { useScreen = false; }
  13041. if (!useScreen && this._currentRenderTarget) {
  13042. return this._currentRenderTarget.width;
  13043. }
  13044. return this._gl.drawingBufferWidth;
  13045. };
  13046. /**
  13047. * Gets the current render height
  13048. * @param useScreen defines if screen size must be used (or the current render target if any)
  13049. * @returns a number defining the current render height
  13050. */
  13051. Engine.prototype.getRenderHeight = function (useScreen) {
  13052. if (useScreen === void 0) { useScreen = false; }
  13053. if (!useScreen && this._currentRenderTarget) {
  13054. return this._currentRenderTarget.height;
  13055. }
  13056. return this._gl.drawingBufferHeight;
  13057. };
  13058. /**
  13059. * Gets the HTML canvas attached with the current webGL context
  13060. * @returns a HTML canvas
  13061. */
  13062. Engine.prototype.getRenderingCanvas = function () {
  13063. return this._renderingCanvas;
  13064. };
  13065. /**
  13066. * Gets the client rect of the HTML canvas attached with the current webGL context
  13067. * @returns a client rectanglee
  13068. */
  13069. Engine.prototype.getRenderingCanvasClientRect = function () {
  13070. if (!this._renderingCanvas) {
  13071. return null;
  13072. }
  13073. return this._renderingCanvas.getBoundingClientRect();
  13074. };
  13075. /**
  13076. * Defines the hardware scaling level.
  13077. * By default the hardware scaling level is computed from the window device ratio.
  13078. * 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.
  13079. * @param level defines the level to use
  13080. */
  13081. Engine.prototype.setHardwareScalingLevel = function (level) {
  13082. this._hardwareScalingLevel = level;
  13083. this.resize();
  13084. };
  13085. /**
  13086. * Gets the current hardware scaling level.
  13087. * By default the hardware scaling level is computed from the window device ratio.
  13088. * 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.
  13089. * @returns a number indicating the current hardware scaling level
  13090. */
  13091. Engine.prototype.getHardwareScalingLevel = function () {
  13092. return this._hardwareScalingLevel;
  13093. };
  13094. /**
  13095. * Gets the list of loaded textures
  13096. * @returns an array containing all loaded textures
  13097. */
  13098. Engine.prototype.getLoadedTexturesCache = function () {
  13099. return this._internalTexturesCache;
  13100. };
  13101. /**
  13102. * Gets the object containing all engine capabilities
  13103. * @returns the EngineCapabilities object
  13104. */
  13105. Engine.prototype.getCaps = function () {
  13106. return this._caps;
  13107. };
  13108. Object.defineProperty(Engine.prototype, "drawCalls", {
  13109. /** @hidden */
  13110. get: function () {
  13111. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  13112. return 0;
  13113. },
  13114. enumerable: true,
  13115. configurable: true
  13116. });
  13117. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  13118. /** @hidden */
  13119. get: function () {
  13120. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  13121. return null;
  13122. },
  13123. enumerable: true,
  13124. configurable: true
  13125. });
  13126. /**
  13127. * Gets the current depth function
  13128. * @returns a number defining the depth function
  13129. */
  13130. Engine.prototype.getDepthFunction = function () {
  13131. return this._depthCullingState.depthFunc;
  13132. };
  13133. /**
  13134. * Sets the current depth function
  13135. * @param depthFunc defines the function to use
  13136. */
  13137. Engine.prototype.setDepthFunction = function (depthFunc) {
  13138. this._depthCullingState.depthFunc = depthFunc;
  13139. };
  13140. /**
  13141. * Sets the current depth function to GREATER
  13142. */
  13143. Engine.prototype.setDepthFunctionToGreater = function () {
  13144. this._depthCullingState.depthFunc = this._gl.GREATER;
  13145. };
  13146. /**
  13147. * Sets the current depth function to GEQUAL
  13148. */
  13149. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13150. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13151. };
  13152. /**
  13153. * Sets the current depth function to LESS
  13154. */
  13155. Engine.prototype.setDepthFunctionToLess = function () {
  13156. this._depthCullingState.depthFunc = this._gl.LESS;
  13157. };
  13158. /**
  13159. * Sets the current depth function to LEQUAL
  13160. */
  13161. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13162. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13163. };
  13164. /**
  13165. * Gets a boolean indicating if stencil buffer is enabled
  13166. * @returns the current stencil buffer state
  13167. */
  13168. Engine.prototype.getStencilBuffer = function () {
  13169. return this._stencilState.stencilTest;
  13170. };
  13171. /**
  13172. * Enable or disable the stencil buffer
  13173. * @param enable defines if the stencil buffer must be enabled or disabled
  13174. */
  13175. Engine.prototype.setStencilBuffer = function (enable) {
  13176. this._stencilState.stencilTest = enable;
  13177. };
  13178. /**
  13179. * Gets the current stencil mask
  13180. * @returns a number defining the new stencil mask to use
  13181. */
  13182. Engine.prototype.getStencilMask = function () {
  13183. return this._stencilState.stencilMask;
  13184. };
  13185. /**
  13186. * Sets the current stencil mask
  13187. * @param mask defines the new stencil mask to use
  13188. */
  13189. Engine.prototype.setStencilMask = function (mask) {
  13190. this._stencilState.stencilMask = mask;
  13191. };
  13192. /**
  13193. * Gets the current stencil function
  13194. * @returns a number defining the stencil function to use
  13195. */
  13196. Engine.prototype.getStencilFunction = function () {
  13197. return this._stencilState.stencilFunc;
  13198. };
  13199. /**
  13200. * Gets the current stencil reference value
  13201. * @returns a number defining the stencil reference value to use
  13202. */
  13203. Engine.prototype.getStencilFunctionReference = function () {
  13204. return this._stencilState.stencilFuncRef;
  13205. };
  13206. /**
  13207. * Gets the current stencil mask
  13208. * @returns a number defining the stencil mask to use
  13209. */
  13210. Engine.prototype.getStencilFunctionMask = function () {
  13211. return this._stencilState.stencilFuncMask;
  13212. };
  13213. /**
  13214. * Sets the current stencil function
  13215. * @param stencilFunc defines the new stencil function to use
  13216. */
  13217. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13218. this._stencilState.stencilFunc = stencilFunc;
  13219. };
  13220. /**
  13221. * Sets the current stencil reference
  13222. * @param reference defines the new stencil reference to use
  13223. */
  13224. Engine.prototype.setStencilFunctionReference = function (reference) {
  13225. this._stencilState.stencilFuncRef = reference;
  13226. };
  13227. /**
  13228. * Sets the current stencil mask
  13229. * @param mask defines the new stencil mask to use
  13230. */
  13231. Engine.prototype.setStencilFunctionMask = function (mask) {
  13232. this._stencilState.stencilFuncMask = mask;
  13233. };
  13234. /**
  13235. * Gets the current stencil operation when stencil fails
  13236. * @returns a number defining stencil operation to use when stencil fails
  13237. */
  13238. Engine.prototype.getStencilOperationFail = function () {
  13239. return this._stencilState.stencilOpStencilFail;
  13240. };
  13241. /**
  13242. * Gets the current stencil operation when depth fails
  13243. * @returns a number defining stencil operation to use when depth fails
  13244. */
  13245. Engine.prototype.getStencilOperationDepthFail = function () {
  13246. return this._stencilState.stencilOpDepthFail;
  13247. };
  13248. /**
  13249. * Gets the current stencil operation when stencil passes
  13250. * @returns a number defining stencil operation to use when stencil passes
  13251. */
  13252. Engine.prototype.getStencilOperationPass = function () {
  13253. return this._stencilState.stencilOpStencilDepthPass;
  13254. };
  13255. /**
  13256. * Sets the stencil operation to use when stencil fails
  13257. * @param operation defines the stencil operation to use when stencil fails
  13258. */
  13259. Engine.prototype.setStencilOperationFail = function (operation) {
  13260. this._stencilState.stencilOpStencilFail = operation;
  13261. };
  13262. /**
  13263. * Sets the stencil operation to use when depth fails
  13264. * @param operation defines the stencil operation to use when depth fails
  13265. */
  13266. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13267. this._stencilState.stencilOpDepthFail = operation;
  13268. };
  13269. /**
  13270. * Sets the stencil operation to use when stencil passes
  13271. * @param operation defines the stencil operation to use when stencil passes
  13272. */
  13273. Engine.prototype.setStencilOperationPass = function (operation) {
  13274. this._stencilState.stencilOpStencilDepthPass = operation;
  13275. };
  13276. /**
  13277. * Sets a boolean indicating if the dithering state is enabled or disabled
  13278. * @param value defines the dithering state
  13279. */
  13280. Engine.prototype.setDitheringState = function (value) {
  13281. if (value) {
  13282. this._gl.enable(this._gl.DITHER);
  13283. }
  13284. else {
  13285. this._gl.disable(this._gl.DITHER);
  13286. }
  13287. };
  13288. /**
  13289. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13290. * @param value defines the rasterizer state
  13291. */
  13292. Engine.prototype.setRasterizerState = function (value) {
  13293. if (value) {
  13294. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13295. }
  13296. else {
  13297. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13298. }
  13299. };
  13300. /**
  13301. * stop executing a render loop function and remove it from the execution array
  13302. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13303. */
  13304. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13305. if (!renderFunction) {
  13306. this._activeRenderLoops = [];
  13307. return;
  13308. }
  13309. var index = this._activeRenderLoops.indexOf(renderFunction);
  13310. if (index >= 0) {
  13311. this._activeRenderLoops.splice(index, 1);
  13312. }
  13313. };
  13314. /** @hidden */
  13315. Engine.prototype._renderLoop = function () {
  13316. if (!this._contextWasLost) {
  13317. var shouldRender = true;
  13318. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13319. shouldRender = false;
  13320. }
  13321. if (shouldRender) {
  13322. // Start new frame
  13323. this.beginFrame();
  13324. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13325. var renderFunction = this._activeRenderLoops[index];
  13326. renderFunction();
  13327. }
  13328. // Present
  13329. this.endFrame();
  13330. }
  13331. }
  13332. if (this._activeRenderLoops.length > 0) {
  13333. // Register new frame
  13334. var requester = null;
  13335. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13336. requester = this._vrDisplay;
  13337. }
  13338. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13339. }
  13340. else {
  13341. this._renderingQueueLaunched = false;
  13342. }
  13343. };
  13344. /**
  13345. * Register and execute a render loop. The engine can have more than one render function
  13346. * @param renderFunction defines the function to continuously execute
  13347. */
  13348. Engine.prototype.runRenderLoop = function (renderFunction) {
  13349. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13350. return;
  13351. }
  13352. this._activeRenderLoops.push(renderFunction);
  13353. if (!this._renderingQueueLaunched) {
  13354. this._renderingQueueLaunched = true;
  13355. this._bindedRenderFunction = this._renderLoop.bind(this);
  13356. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13357. }
  13358. };
  13359. /**
  13360. * Toggle full screen mode
  13361. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13362. */
  13363. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13364. if (this.isFullscreen) {
  13365. BABYLON.Tools.ExitFullscreen();
  13366. }
  13367. else {
  13368. this._pointerLockRequested = requestPointerLock;
  13369. if (this._renderingCanvas) {
  13370. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13371. }
  13372. }
  13373. };
  13374. /**
  13375. * Clear the current render buffer or the current render target (if any is set up)
  13376. * @param color defines the color to use
  13377. * @param backBuffer defines if the back buffer must be cleared
  13378. * @param depth defines if the depth buffer must be cleared
  13379. * @param stencil defines if the stencil buffer must be cleared
  13380. */
  13381. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13382. if (stencil === void 0) { stencil = false; }
  13383. this.applyStates();
  13384. var mode = 0;
  13385. if (backBuffer && color) {
  13386. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13387. mode |= this._gl.COLOR_BUFFER_BIT;
  13388. }
  13389. if (depth) {
  13390. this._gl.clearDepth(1.0);
  13391. mode |= this._gl.DEPTH_BUFFER_BIT;
  13392. }
  13393. if (stencil) {
  13394. this._gl.clearStencil(0);
  13395. mode |= this._gl.STENCIL_BUFFER_BIT;
  13396. }
  13397. this._gl.clear(mode);
  13398. };
  13399. /**
  13400. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13401. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13402. * @param y defines the y-coordinate of the corner of the clear rectangle
  13403. * @param width defines the width of the clear rectangle
  13404. * @param height defines the height of the clear rectangle
  13405. * @param clearColor defines the clear color
  13406. */
  13407. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13408. var gl = this._gl;
  13409. // Save state
  13410. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13411. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13412. // Change state
  13413. gl.enable(gl.SCISSOR_TEST);
  13414. gl.scissor(x, y, width, height);
  13415. // Clear
  13416. this.clear(clearColor, true, true, true);
  13417. // Restore state
  13418. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13419. if (curScissor === true) {
  13420. gl.enable(gl.SCISSOR_TEST);
  13421. }
  13422. else {
  13423. gl.disable(gl.SCISSOR_TEST);
  13424. }
  13425. };
  13426. /** @hidden */
  13427. Engine.prototype._viewport = function (x, y, width, height) {
  13428. if (x !== this._viewportCached.x ||
  13429. y !== this._viewportCached.y ||
  13430. width !== this._viewportCached.z ||
  13431. height !== this._viewportCached.w) {
  13432. this._viewportCached.x = x;
  13433. this._viewportCached.y = y;
  13434. this._viewportCached.z = width;
  13435. this._viewportCached.w = height;
  13436. this._gl.viewport(x, y, width, height);
  13437. }
  13438. };
  13439. /**
  13440. * Set the WebGL's viewport
  13441. * @param viewport defines the viewport element to be used
  13442. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13443. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13444. */
  13445. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13446. var width = requiredWidth || this.getRenderWidth();
  13447. var height = requiredHeight || this.getRenderHeight();
  13448. var x = viewport.x || 0;
  13449. var y = viewport.y || 0;
  13450. this._cachedViewport = viewport;
  13451. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13452. };
  13453. /**
  13454. * Directly set the WebGL Viewport
  13455. * @param x defines the x coordinate of the viewport (in screen space)
  13456. * @param y defines the y coordinate of the viewport (in screen space)
  13457. * @param width defines the width of the viewport (in screen space)
  13458. * @param height defines the height of the viewport (in screen space)
  13459. * @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
  13460. */
  13461. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13462. var currentViewport = this._cachedViewport;
  13463. this._cachedViewport = null;
  13464. this._viewport(x, y, width, height);
  13465. return currentViewport;
  13466. };
  13467. /**
  13468. * Begin a new frame
  13469. */
  13470. Engine.prototype.beginFrame = function () {
  13471. this.onBeginFrameObservable.notifyObservers(this);
  13472. this._measureFps();
  13473. };
  13474. /**
  13475. * Enf the current frame
  13476. */
  13477. Engine.prototype.endFrame = function () {
  13478. // Force a flush in case we are using a bad OS.
  13479. if (this._badOS) {
  13480. this.flushFramebuffer();
  13481. }
  13482. // Submit frame to the vr device, if enabled
  13483. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13484. // TODO: We should only submit the frame if we read frameData successfully.
  13485. this._vrDisplay.submitFrame();
  13486. }
  13487. this.onEndFrameObservable.notifyObservers(this);
  13488. };
  13489. /**
  13490. * Resize the view according to the canvas' size
  13491. */
  13492. Engine.prototype.resize = function () {
  13493. // We're not resizing the size of the canvas while in VR mode & presenting
  13494. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13495. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13496. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13497. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13498. }
  13499. };
  13500. /**
  13501. * Force a specific size of the canvas
  13502. * @param width defines the new canvas' width
  13503. * @param height defines the new canvas' height
  13504. */
  13505. Engine.prototype.setSize = function (width, height) {
  13506. if (!this._renderingCanvas) {
  13507. return;
  13508. }
  13509. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13510. return;
  13511. }
  13512. this._renderingCanvas.width = width;
  13513. this._renderingCanvas.height = height;
  13514. for (var index = 0; index < this.scenes.length; index++) {
  13515. var scene = this.scenes[index];
  13516. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13517. var cam = scene.cameras[camIndex];
  13518. cam._currentRenderId = 0;
  13519. }
  13520. }
  13521. if (this.onResizeObservable.hasObservers) {
  13522. this.onResizeObservable.notifyObservers(this);
  13523. }
  13524. };
  13525. // WebVR functions
  13526. /**
  13527. * Gets a boolean indicating if a webVR device was detected
  13528. * @returns true if a webVR device was detected
  13529. */
  13530. Engine.prototype.isVRDevicePresent = function () {
  13531. return !!this._vrDisplay;
  13532. };
  13533. /**
  13534. * Gets the current webVR device
  13535. * @returns the current webVR device (or null)
  13536. */
  13537. Engine.prototype.getVRDevice = function () {
  13538. return this._vrDisplay;
  13539. };
  13540. /**
  13541. * Initializes a webVR display and starts listening to display change events
  13542. * The onVRDisplayChangedObservable will be notified upon these changes
  13543. * @returns The onVRDisplayChangedObservable
  13544. */
  13545. Engine.prototype.initWebVR = function () {
  13546. this.initWebVRAsync();
  13547. return this.onVRDisplayChangedObservable;
  13548. };
  13549. /**
  13550. * Initializes a webVR display and starts listening to display change events
  13551. * The onVRDisplayChangedObservable will be notified upon these changes
  13552. * @returns A promise containing a VRDisplay and if vr is supported
  13553. */
  13554. Engine.prototype.initWebVRAsync = function () {
  13555. var _this = this;
  13556. var notifyObservers = function () {
  13557. var eventArgs = {
  13558. vrDisplay: _this._vrDisplay,
  13559. vrSupported: _this._vrSupported
  13560. };
  13561. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13562. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13563. };
  13564. if (!this._onVrDisplayConnect) {
  13565. this._onVrDisplayConnect = function (event) {
  13566. _this._vrDisplay = event.display;
  13567. notifyObservers();
  13568. };
  13569. this._onVrDisplayDisconnect = function () {
  13570. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13571. _this._vrDisplay = undefined;
  13572. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13573. notifyObservers();
  13574. };
  13575. this._onVrDisplayPresentChange = function () {
  13576. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13577. };
  13578. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13579. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13580. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13581. }
  13582. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13583. this._webVRInitPromise.then(notifyObservers);
  13584. return this._webVRInitPromise;
  13585. };
  13586. /**
  13587. * Call this function to switch to webVR mode
  13588. * Will do nothing if webVR is not supported or if there is no webVR device
  13589. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13590. */
  13591. Engine.prototype.enableVR = function () {
  13592. var _this = this;
  13593. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13594. var onResolved = function () {
  13595. _this.onVRRequestPresentComplete.notifyObservers(true);
  13596. _this._onVRFullScreenTriggered();
  13597. };
  13598. var onRejected = function () {
  13599. _this.onVRRequestPresentComplete.notifyObservers(false);
  13600. };
  13601. this.onVRRequestPresentStart.notifyObservers(this);
  13602. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13603. }
  13604. };
  13605. /**
  13606. * Call this function to leave webVR mode
  13607. * Will do nothing if webVR is not supported or if there is no webVR device
  13608. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13609. */
  13610. Engine.prototype.disableVR = function () {
  13611. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13612. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13613. }
  13614. };
  13615. Engine.prototype._getVRDisplaysAsync = function () {
  13616. var _this = this;
  13617. return new Promise(function (res, rej) {
  13618. if (navigator.getVRDisplays) {
  13619. navigator.getVRDisplays().then(function (devices) {
  13620. _this._vrSupported = true;
  13621. // note that devices may actually be an empty array. This is fine;
  13622. // we expect this._vrDisplay to be undefined in this case.
  13623. _this._vrDisplay = devices[0];
  13624. res({
  13625. vrDisplay: _this._vrDisplay,
  13626. vrSupported: _this._vrSupported
  13627. });
  13628. });
  13629. }
  13630. else {
  13631. _this._vrDisplay = undefined;
  13632. _this._vrSupported = false;
  13633. res({
  13634. vrDisplay: _this._vrDisplay,
  13635. vrSupported: _this._vrSupported
  13636. });
  13637. }
  13638. });
  13639. };
  13640. /**
  13641. * Binds the frame buffer to the specified texture.
  13642. * @param texture The texture to render to or null for the default canvas
  13643. * @param faceIndex The face of the texture to render to in case of cube texture
  13644. * @param requiredWidth The width of the target to render to
  13645. * @param requiredHeight The height of the target to render to
  13646. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13647. * @param depthStencilTexture The depth stencil texture to use to render
  13648. * @param lodLevel defines le lod level to bind to the frame buffer
  13649. */
  13650. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13651. if (lodLevel === void 0) { lodLevel = 0; }
  13652. if (this._currentRenderTarget) {
  13653. this.unBindFramebuffer(this._currentRenderTarget);
  13654. }
  13655. this._currentRenderTarget = texture;
  13656. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13657. var gl = this._gl;
  13658. if (texture.isCube) {
  13659. if (faceIndex === undefined) {
  13660. faceIndex = 0;
  13661. }
  13662. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13663. if (depthStencilTexture) {
  13664. if (depthStencilTexture._generateStencilBuffer) {
  13665. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13666. }
  13667. else {
  13668. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13669. }
  13670. }
  13671. }
  13672. if (this._cachedViewport && !forceFullscreenViewport) {
  13673. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13674. }
  13675. else {
  13676. if (!requiredWidth) {
  13677. requiredWidth = texture.width;
  13678. if (lodLevel) {
  13679. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13680. }
  13681. }
  13682. if (!requiredHeight) {
  13683. requiredHeight = texture.height;
  13684. if (lodLevel) {
  13685. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13686. }
  13687. }
  13688. this._viewport(0, 0, requiredWidth, requiredHeight);
  13689. }
  13690. this.wipeCaches();
  13691. };
  13692. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13693. if (this._currentFramebuffer !== framebuffer) {
  13694. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13695. this._currentFramebuffer = framebuffer;
  13696. }
  13697. };
  13698. /**
  13699. * Unbind the current render target texture from the webGL context
  13700. * @param texture defines the render target texture to unbind
  13701. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13702. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13703. */
  13704. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13705. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13706. this._currentRenderTarget = null;
  13707. // If MSAA, we need to bitblt back to main texture
  13708. var gl = this._gl;
  13709. if (texture._MSAAFramebuffer) {
  13710. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13711. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13712. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13713. }
  13714. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13715. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13716. gl.generateMipmap(gl.TEXTURE_2D);
  13717. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13718. }
  13719. if (onBeforeUnbind) {
  13720. if (texture._MSAAFramebuffer) {
  13721. // Bind the correct framebuffer
  13722. this.bindUnboundFramebuffer(texture._framebuffer);
  13723. }
  13724. onBeforeUnbind();
  13725. }
  13726. this.bindUnboundFramebuffer(null);
  13727. };
  13728. /**
  13729. * Unbind a list of render target textures from the webGL context
  13730. * This is used only when drawBuffer extension or webGL2 are active
  13731. * @param textures defines the render target textures to unbind
  13732. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13733. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13734. */
  13735. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13736. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13737. this._currentRenderTarget = null;
  13738. // If MSAA, we need to bitblt back to main texture
  13739. var gl = this._gl;
  13740. if (textures[0]._MSAAFramebuffer) {
  13741. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13742. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13743. var attachments = textures[0]._attachments;
  13744. if (!attachments) {
  13745. attachments = new Array(textures.length);
  13746. textures[0]._attachments = attachments;
  13747. }
  13748. for (var i = 0; i < textures.length; i++) {
  13749. var texture = textures[i];
  13750. for (var j = 0; j < attachments.length; j++) {
  13751. attachments[j] = gl.NONE;
  13752. }
  13753. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13754. gl.readBuffer(attachments[i]);
  13755. gl.drawBuffers(attachments);
  13756. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13757. }
  13758. for (var i = 0; i < attachments.length; i++) {
  13759. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13760. }
  13761. gl.drawBuffers(attachments);
  13762. }
  13763. for (var i = 0; i < textures.length; i++) {
  13764. var texture = textures[i];
  13765. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13766. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13767. gl.generateMipmap(gl.TEXTURE_2D);
  13768. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13769. }
  13770. }
  13771. if (onBeforeUnbind) {
  13772. if (textures[0]._MSAAFramebuffer) {
  13773. // Bind the correct framebuffer
  13774. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13775. }
  13776. onBeforeUnbind();
  13777. }
  13778. this.bindUnboundFramebuffer(null);
  13779. };
  13780. /**
  13781. * Force the mipmap generation for the given render target texture
  13782. * @param texture defines the render target texture to use
  13783. */
  13784. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13785. if (texture.generateMipMaps) {
  13786. var gl = this._gl;
  13787. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13788. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13789. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13790. }
  13791. };
  13792. /**
  13793. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13794. */
  13795. Engine.prototype.flushFramebuffer = function () {
  13796. this._gl.flush();
  13797. };
  13798. /**
  13799. * Unbind the current render target and bind the default framebuffer
  13800. */
  13801. Engine.prototype.restoreDefaultFramebuffer = function () {
  13802. if (this._currentRenderTarget) {
  13803. this.unBindFramebuffer(this._currentRenderTarget);
  13804. }
  13805. else {
  13806. this.bindUnboundFramebuffer(null);
  13807. }
  13808. if (this._cachedViewport) {
  13809. this.setViewport(this._cachedViewport);
  13810. }
  13811. this.wipeCaches();
  13812. };
  13813. // UBOs
  13814. /**
  13815. * Create an uniform buffer
  13816. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13817. * @param elements defines the content of the uniform buffer
  13818. * @returns the webGL uniform buffer
  13819. */
  13820. Engine.prototype.createUniformBuffer = function (elements) {
  13821. var ubo = this._gl.createBuffer();
  13822. if (!ubo) {
  13823. throw new Error("Unable to create uniform buffer");
  13824. }
  13825. this.bindUniformBuffer(ubo);
  13826. if (elements instanceof Float32Array) {
  13827. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13828. }
  13829. else {
  13830. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13831. }
  13832. this.bindUniformBuffer(null);
  13833. ubo.references = 1;
  13834. return ubo;
  13835. };
  13836. /**
  13837. * Create a dynamic uniform buffer
  13838. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13839. * @param elements defines the content of the uniform buffer
  13840. * @returns the webGL uniform buffer
  13841. */
  13842. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13843. var ubo = this._gl.createBuffer();
  13844. if (!ubo) {
  13845. throw new Error("Unable to create dynamic uniform buffer");
  13846. }
  13847. this.bindUniformBuffer(ubo);
  13848. if (elements instanceof Float32Array) {
  13849. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13850. }
  13851. else {
  13852. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13853. }
  13854. this.bindUniformBuffer(null);
  13855. ubo.references = 1;
  13856. return ubo;
  13857. };
  13858. /**
  13859. * Update an existing uniform buffer
  13860. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13861. * @param uniformBuffer defines the target uniform buffer
  13862. * @param elements defines the content to update
  13863. * @param offset defines the offset in the uniform buffer where update should start
  13864. * @param count defines the size of the data to update
  13865. */
  13866. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13867. this.bindUniformBuffer(uniformBuffer);
  13868. if (offset === undefined) {
  13869. offset = 0;
  13870. }
  13871. if (count === undefined) {
  13872. if (elements instanceof Float32Array) {
  13873. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13874. }
  13875. else {
  13876. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13877. }
  13878. }
  13879. else {
  13880. if (elements instanceof Float32Array) {
  13881. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13882. }
  13883. else {
  13884. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13885. }
  13886. }
  13887. this.bindUniformBuffer(null);
  13888. };
  13889. // VBOs
  13890. Engine.prototype._resetVertexBufferBinding = function () {
  13891. this.bindArrayBuffer(null);
  13892. this._cachedVertexBuffers = null;
  13893. };
  13894. /**
  13895. * Creates a vertex buffer
  13896. * @param data the data for the vertex buffer
  13897. * @returns the new WebGL static buffer
  13898. */
  13899. Engine.prototype.createVertexBuffer = function (data) {
  13900. var vbo = this._gl.createBuffer();
  13901. if (!vbo) {
  13902. throw new Error("Unable to create vertex buffer");
  13903. }
  13904. this.bindArrayBuffer(vbo);
  13905. if (data instanceof Array) {
  13906. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13907. }
  13908. else {
  13909. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13910. }
  13911. this._resetVertexBufferBinding();
  13912. vbo.references = 1;
  13913. return vbo;
  13914. };
  13915. /**
  13916. * Creates a dynamic vertex buffer
  13917. * @param data the data for the dynamic vertex buffer
  13918. * @returns the new WebGL dynamic buffer
  13919. */
  13920. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13921. var vbo = this._gl.createBuffer();
  13922. if (!vbo) {
  13923. throw new Error("Unable to create dynamic vertex buffer");
  13924. }
  13925. this.bindArrayBuffer(vbo);
  13926. if (data instanceof Array) {
  13927. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13928. }
  13929. else {
  13930. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13931. }
  13932. this._resetVertexBufferBinding();
  13933. vbo.references = 1;
  13934. return vbo;
  13935. };
  13936. /**
  13937. * Update a dynamic index buffer
  13938. * @param indexBuffer defines the target index buffer
  13939. * @param indices defines the data to update
  13940. * @param offset defines the offset in the target index buffer where update should start
  13941. */
  13942. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13943. if (offset === void 0) { offset = 0; }
  13944. // Force cache update
  13945. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13946. this.bindIndexBuffer(indexBuffer);
  13947. var arrayBuffer;
  13948. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13949. arrayBuffer = indices;
  13950. }
  13951. else {
  13952. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13953. }
  13954. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13955. this._resetIndexBufferBinding();
  13956. };
  13957. /**
  13958. * Updates a dynamic vertex buffer.
  13959. * @param vertexBuffer the vertex buffer to update
  13960. * @param data the data used to update the vertex buffer
  13961. * @param byteOffset the byte offset of the data
  13962. * @param byteLength the byte length of the data
  13963. */
  13964. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13965. this.bindArrayBuffer(vertexBuffer);
  13966. if (byteOffset === undefined) {
  13967. byteOffset = 0;
  13968. }
  13969. if (byteLength === undefined) {
  13970. if (data instanceof Array) {
  13971. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13972. }
  13973. else {
  13974. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13975. }
  13976. }
  13977. else {
  13978. if (data instanceof Array) {
  13979. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13980. }
  13981. else {
  13982. if (data instanceof ArrayBuffer) {
  13983. data = new Uint8Array(data, byteOffset, byteLength);
  13984. }
  13985. else {
  13986. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13987. }
  13988. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13989. }
  13990. }
  13991. this._resetVertexBufferBinding();
  13992. };
  13993. Engine.prototype._resetIndexBufferBinding = function () {
  13994. this.bindIndexBuffer(null);
  13995. this._cachedIndexBuffer = null;
  13996. };
  13997. /**
  13998. * Creates a new index buffer
  13999. * @param indices defines the content of the index buffer
  14000. * @param updatable defines if the index buffer must be updatable
  14001. * @returns a new webGL buffer
  14002. */
  14003. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14004. var vbo = this._gl.createBuffer();
  14005. if (!vbo) {
  14006. throw new Error("Unable to create index buffer");
  14007. }
  14008. this.bindIndexBuffer(vbo);
  14009. // Check for 32 bits indices
  14010. var arrayBuffer;
  14011. var need32Bits = false;
  14012. if (indices instanceof Uint16Array) {
  14013. arrayBuffer = indices;
  14014. }
  14015. else {
  14016. //check 32 bit support
  14017. if (this._caps.uintIndices) {
  14018. if (indices instanceof Uint32Array) {
  14019. arrayBuffer = indices;
  14020. need32Bits = true;
  14021. }
  14022. else {
  14023. //number[] or Int32Array, check if 32 bit is necessary
  14024. for (var index = 0; index < indices.length; index++) {
  14025. if (indices[index] > 65535) {
  14026. need32Bits = true;
  14027. break;
  14028. }
  14029. }
  14030. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14031. }
  14032. }
  14033. else {
  14034. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14035. arrayBuffer = new Uint16Array(indices);
  14036. }
  14037. }
  14038. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14039. this._resetIndexBufferBinding();
  14040. vbo.references = 1;
  14041. vbo.is32Bits = need32Bits;
  14042. return vbo;
  14043. };
  14044. /**
  14045. * Bind a webGL buffer to the webGL context
  14046. * @param buffer defines the buffer to bind
  14047. */
  14048. Engine.prototype.bindArrayBuffer = function (buffer) {
  14049. if (!this._vaoRecordInProgress) {
  14050. this._unbindVertexArrayObject();
  14051. }
  14052. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14053. };
  14054. /**
  14055. * Bind an uniform buffer to the current webGL context
  14056. * @param buffer defines the buffer to bind
  14057. */
  14058. Engine.prototype.bindUniformBuffer = function (buffer) {
  14059. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14060. };
  14061. /**
  14062. * Bind a buffer to the current webGL context at a given location
  14063. * @param buffer defines the buffer to bind
  14064. * @param location defines the index where to bind the buffer
  14065. */
  14066. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14067. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14068. };
  14069. /**
  14070. * Bind a specific block at a given index in a specific shader program
  14071. * @param shaderProgram defines the shader program
  14072. * @param blockName defines the block name
  14073. * @param index defines the index where to bind the block
  14074. */
  14075. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14076. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14077. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14078. };
  14079. Engine.prototype.bindIndexBuffer = function (buffer) {
  14080. if (!this._vaoRecordInProgress) {
  14081. this._unbindVertexArrayObject();
  14082. }
  14083. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14084. };
  14085. Engine.prototype.bindBuffer = function (buffer, target) {
  14086. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14087. this._gl.bindBuffer(target, buffer);
  14088. this._currentBoundBuffer[target] = buffer;
  14089. }
  14090. };
  14091. /**
  14092. * update the bound buffer with the given data
  14093. * @param data defines the data to update
  14094. */
  14095. Engine.prototype.updateArrayBuffer = function (data) {
  14096. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14097. };
  14098. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14099. var pointer = this._currentBufferPointers[indx];
  14100. var changed = false;
  14101. if (!pointer.active) {
  14102. changed = true;
  14103. pointer.active = true;
  14104. pointer.index = indx;
  14105. pointer.size = size;
  14106. pointer.type = type;
  14107. pointer.normalized = normalized;
  14108. pointer.stride = stride;
  14109. pointer.offset = offset;
  14110. pointer.buffer = buffer;
  14111. }
  14112. else {
  14113. if (pointer.buffer !== buffer) {
  14114. pointer.buffer = buffer;
  14115. changed = true;
  14116. }
  14117. if (pointer.size !== size) {
  14118. pointer.size = size;
  14119. changed = true;
  14120. }
  14121. if (pointer.type !== type) {
  14122. pointer.type = type;
  14123. changed = true;
  14124. }
  14125. if (pointer.normalized !== normalized) {
  14126. pointer.normalized = normalized;
  14127. changed = true;
  14128. }
  14129. if (pointer.stride !== stride) {
  14130. pointer.stride = stride;
  14131. changed = true;
  14132. }
  14133. if (pointer.offset !== offset) {
  14134. pointer.offset = offset;
  14135. changed = true;
  14136. }
  14137. }
  14138. if (changed || this._vaoRecordInProgress) {
  14139. this.bindArrayBuffer(buffer);
  14140. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14141. }
  14142. };
  14143. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14144. if (indexBuffer == null) {
  14145. return;
  14146. }
  14147. if (this._cachedIndexBuffer !== indexBuffer) {
  14148. this._cachedIndexBuffer = indexBuffer;
  14149. this.bindIndexBuffer(indexBuffer);
  14150. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14151. }
  14152. };
  14153. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14154. var attributes = effect.getAttributesNames();
  14155. if (!this._vaoRecordInProgress) {
  14156. this._unbindVertexArrayObject();
  14157. }
  14158. this.unbindAllAttributes();
  14159. for (var index = 0; index < attributes.length; index++) {
  14160. var order = effect.getAttributeLocation(index);
  14161. if (order >= 0) {
  14162. var vertexBuffer = vertexBuffers[attributes[index]];
  14163. if (!vertexBuffer) {
  14164. continue;
  14165. }
  14166. this._gl.enableVertexAttribArray(order);
  14167. if (!this._vaoRecordInProgress) {
  14168. this._vertexAttribArraysEnabled[order] = true;
  14169. }
  14170. var buffer = vertexBuffer.getBuffer();
  14171. if (buffer) {
  14172. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14173. if (vertexBuffer.getIsInstanced()) {
  14174. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14175. if (!this._vaoRecordInProgress) {
  14176. this._currentInstanceLocations.push(order);
  14177. this._currentInstanceBuffers.push(buffer);
  14178. }
  14179. }
  14180. }
  14181. }
  14182. }
  14183. };
  14184. /**
  14185. * Records a vertex array object
  14186. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14187. * @param vertexBuffers defines the list of vertex buffers to store
  14188. * @param indexBuffer defines the index buffer to store
  14189. * @param effect defines the effect to store
  14190. * @returns the new vertex array object
  14191. */
  14192. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14193. var vao = this._gl.createVertexArray();
  14194. this._vaoRecordInProgress = true;
  14195. this._gl.bindVertexArray(vao);
  14196. this._mustWipeVertexAttributes = true;
  14197. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14198. this.bindIndexBuffer(indexBuffer);
  14199. this._vaoRecordInProgress = false;
  14200. this._gl.bindVertexArray(null);
  14201. return vao;
  14202. };
  14203. /**
  14204. * Bind a specific vertex array object
  14205. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14206. * @param vertexArrayObject defines the vertex array object to bind
  14207. * @param indexBuffer defines the index buffer to bind
  14208. */
  14209. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14210. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14211. this._cachedVertexArrayObject = vertexArrayObject;
  14212. this._gl.bindVertexArray(vertexArrayObject);
  14213. this._cachedVertexBuffers = null;
  14214. this._cachedIndexBuffer = null;
  14215. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14216. this._mustWipeVertexAttributes = true;
  14217. }
  14218. };
  14219. /**
  14220. * Bind webGl buffers directly to the webGL context
  14221. * @param vertexBuffer defines the vertex buffer to bind
  14222. * @param indexBuffer defines the index buffer to bind
  14223. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14224. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14225. * @param effect defines the effect associated with the vertex buffer
  14226. */
  14227. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14228. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14229. this._cachedVertexBuffers = vertexBuffer;
  14230. this._cachedEffectForVertexBuffers = effect;
  14231. var attributesCount = effect.getAttributesCount();
  14232. this._unbindVertexArrayObject();
  14233. this.unbindAllAttributes();
  14234. var offset = 0;
  14235. for (var index = 0; index < attributesCount; index++) {
  14236. if (index < vertexDeclaration.length) {
  14237. var order = effect.getAttributeLocation(index);
  14238. if (order >= 0) {
  14239. this._gl.enableVertexAttribArray(order);
  14240. this._vertexAttribArraysEnabled[order] = true;
  14241. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14242. }
  14243. offset += vertexDeclaration[index] * 4;
  14244. }
  14245. }
  14246. }
  14247. this._bindIndexBufferWithCache(indexBuffer);
  14248. };
  14249. Engine.prototype._unbindVertexArrayObject = function () {
  14250. if (!this._cachedVertexArrayObject) {
  14251. return;
  14252. }
  14253. this._cachedVertexArrayObject = null;
  14254. this._gl.bindVertexArray(null);
  14255. };
  14256. /**
  14257. * Bind a list of vertex buffers to the webGL context
  14258. * @param vertexBuffers defines the list of vertex buffers to bind
  14259. * @param indexBuffer defines the index buffer to bind
  14260. * @param effect defines the effect associated with the vertex buffers
  14261. */
  14262. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14263. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14264. this._cachedVertexBuffers = vertexBuffers;
  14265. this._cachedEffectForVertexBuffers = effect;
  14266. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14267. }
  14268. this._bindIndexBufferWithCache(indexBuffer);
  14269. };
  14270. /**
  14271. * Unbind all instance attributes
  14272. */
  14273. Engine.prototype.unbindInstanceAttributes = function () {
  14274. var boundBuffer;
  14275. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14276. var instancesBuffer = this._currentInstanceBuffers[i];
  14277. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14278. boundBuffer = instancesBuffer;
  14279. this.bindArrayBuffer(instancesBuffer);
  14280. }
  14281. var offsetLocation = this._currentInstanceLocations[i];
  14282. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14283. }
  14284. this._currentInstanceBuffers.length = 0;
  14285. this._currentInstanceLocations.length = 0;
  14286. };
  14287. /**
  14288. * Release and free the memory of a vertex array object
  14289. * @param vao defines the vertex array object to delete
  14290. */
  14291. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14292. this._gl.deleteVertexArray(vao);
  14293. };
  14294. /** @hidden */
  14295. Engine.prototype._releaseBuffer = function (buffer) {
  14296. buffer.references--;
  14297. if (buffer.references === 0) {
  14298. this._gl.deleteBuffer(buffer);
  14299. return true;
  14300. }
  14301. return false;
  14302. };
  14303. /**
  14304. * Creates a webGL buffer to use with instanciation
  14305. * @param capacity defines the size of the buffer
  14306. * @returns the webGL buffer
  14307. */
  14308. Engine.prototype.createInstancesBuffer = function (capacity) {
  14309. var buffer = this._gl.createBuffer();
  14310. if (!buffer) {
  14311. throw new Error("Unable to create instance buffer");
  14312. }
  14313. buffer.capacity = capacity;
  14314. this.bindArrayBuffer(buffer);
  14315. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14316. return buffer;
  14317. };
  14318. /**
  14319. * Delete a webGL buffer used with instanciation
  14320. * @param buffer defines the webGL buffer to delete
  14321. */
  14322. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14323. this._gl.deleteBuffer(buffer);
  14324. };
  14325. /**
  14326. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14327. * @param instancesBuffer defines the webGL buffer to update and bind
  14328. * @param data defines the data to store in the buffer
  14329. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14330. */
  14331. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14332. this.bindArrayBuffer(instancesBuffer);
  14333. if (data) {
  14334. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14335. }
  14336. if (offsetLocations[0].index !== undefined) {
  14337. var stride = 0;
  14338. for (var i = 0; i < offsetLocations.length; i++) {
  14339. var ai = offsetLocations[i];
  14340. stride += ai.attributeSize * 4;
  14341. }
  14342. for (var i = 0; i < offsetLocations.length; i++) {
  14343. var ai = offsetLocations[i];
  14344. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14345. this._gl.enableVertexAttribArray(ai.index);
  14346. this._vertexAttribArraysEnabled[ai.index] = true;
  14347. }
  14348. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14349. this._gl.vertexAttribDivisor(ai.index, 1);
  14350. this._currentInstanceLocations.push(ai.index);
  14351. this._currentInstanceBuffers.push(instancesBuffer);
  14352. }
  14353. }
  14354. else {
  14355. for (var index = 0; index < 4; index++) {
  14356. var offsetLocation = offsetLocations[index];
  14357. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14358. this._gl.enableVertexAttribArray(offsetLocation);
  14359. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14360. }
  14361. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14362. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14363. this._currentInstanceLocations.push(offsetLocation);
  14364. this._currentInstanceBuffers.push(instancesBuffer);
  14365. }
  14366. }
  14367. };
  14368. /**
  14369. * Apply all cached states (depth, culling, stencil and alpha)
  14370. */
  14371. Engine.prototype.applyStates = function () {
  14372. this._depthCullingState.apply(this._gl);
  14373. this._stencilState.apply(this._gl);
  14374. this._alphaState.apply(this._gl);
  14375. };
  14376. /**
  14377. * Send a draw order
  14378. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14379. * @param indexStart defines the starting index
  14380. * @param indexCount defines the number of index to draw
  14381. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14382. */
  14383. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14384. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14385. };
  14386. /**
  14387. * Draw a list of points
  14388. * @param verticesStart defines the index of first vertex to draw
  14389. * @param verticesCount defines the count of vertices to draw
  14390. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14391. */
  14392. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14393. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14394. };
  14395. /**
  14396. * Draw a list of unindexed primitives
  14397. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14398. * @param verticesStart defines the index of first vertex to draw
  14399. * @param verticesCount defines the count of vertices to draw
  14400. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14401. */
  14402. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14403. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14404. };
  14405. /**
  14406. * Draw a list of indexed primitives
  14407. * @param fillMode defines the primitive to use
  14408. * @param indexStart defines the starting index
  14409. * @param indexCount defines the number of index to draw
  14410. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14411. */
  14412. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14413. // Apply states
  14414. this.applyStates();
  14415. this._drawCalls.addCount(1, false);
  14416. // Render
  14417. var drawMode = this._drawMode(fillMode);
  14418. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14419. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14420. if (instancesCount) {
  14421. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14422. }
  14423. else {
  14424. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14425. }
  14426. };
  14427. /**
  14428. * Draw a list of unindexed primitives
  14429. * @param fillMode defines the primitive to use
  14430. * @param verticesStart defines the index of first vertex to draw
  14431. * @param verticesCount defines the count of vertices to draw
  14432. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14433. */
  14434. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14435. // Apply states
  14436. this.applyStates();
  14437. this._drawCalls.addCount(1, false);
  14438. var drawMode = this._drawMode(fillMode);
  14439. if (instancesCount) {
  14440. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14441. }
  14442. else {
  14443. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14444. }
  14445. };
  14446. Engine.prototype._drawMode = function (fillMode) {
  14447. switch (fillMode) {
  14448. // Triangle views
  14449. case BABYLON.Material.TriangleFillMode:
  14450. return this._gl.TRIANGLES;
  14451. case BABYLON.Material.PointFillMode:
  14452. return this._gl.POINTS;
  14453. case BABYLON.Material.WireFrameFillMode:
  14454. return this._gl.LINES;
  14455. // Draw modes
  14456. case BABYLON.Material.PointListDrawMode:
  14457. return this._gl.POINTS;
  14458. case BABYLON.Material.LineListDrawMode:
  14459. return this._gl.LINES;
  14460. case BABYLON.Material.LineLoopDrawMode:
  14461. return this._gl.LINE_LOOP;
  14462. case BABYLON.Material.LineStripDrawMode:
  14463. return this._gl.LINE_STRIP;
  14464. case BABYLON.Material.TriangleStripDrawMode:
  14465. return this._gl.TRIANGLE_STRIP;
  14466. case BABYLON.Material.TriangleFanDrawMode:
  14467. return this._gl.TRIANGLE_FAN;
  14468. default:
  14469. return this._gl.TRIANGLES;
  14470. }
  14471. };
  14472. // Shaders
  14473. /** @hidden */
  14474. Engine.prototype._releaseEffect = function (effect) {
  14475. if (this._compiledEffects[effect._key]) {
  14476. delete this._compiledEffects[effect._key];
  14477. this._deleteProgram(effect.getProgram());
  14478. }
  14479. };
  14480. /** @hidden */
  14481. Engine.prototype._deleteProgram = function (program) {
  14482. if (program) {
  14483. program.__SPECTOR_rebuildProgram = null;
  14484. if (program.transformFeedback) {
  14485. this.deleteTransformFeedback(program.transformFeedback);
  14486. program.transformFeedback = null;
  14487. }
  14488. this._gl.deleteProgram(program);
  14489. }
  14490. };
  14491. /**
  14492. * Create a new effect (used to store vertex/fragment shaders)
  14493. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14494. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14495. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14496. * @param samplers defines an array of string used to represent textures
  14497. * @param defines defines the string containing the defines to use to compile the shaders
  14498. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14499. * @param onCompiled defines a function to call when the effect creation is successful
  14500. * @param onError defines a function to call when the effect creation has failed
  14501. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14502. * @returns the new Effect
  14503. */
  14504. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14505. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14506. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14507. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14508. if (this._compiledEffects[name]) {
  14509. var compiledEffect = this._compiledEffects[name];
  14510. if (onCompiled && compiledEffect.isReady()) {
  14511. onCompiled(compiledEffect);
  14512. }
  14513. return compiledEffect;
  14514. }
  14515. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14516. effect._key = name;
  14517. this._compiledEffects[name] = effect;
  14518. return effect;
  14519. };
  14520. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14521. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14522. };
  14523. Engine.prototype._compileRawShader = function (source, type) {
  14524. var gl = this._gl;
  14525. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14526. gl.shaderSource(shader, source);
  14527. gl.compileShader(shader);
  14528. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14529. var log = gl.getShaderInfoLog(shader);
  14530. if (log) {
  14531. throw new Error(log);
  14532. }
  14533. }
  14534. if (!shader) {
  14535. throw new Error("Something went wrong while compile the shader.");
  14536. }
  14537. return shader;
  14538. };
  14539. /**
  14540. * Directly creates a webGL program
  14541. * @param vertexCode defines the vertex shader code to use
  14542. * @param fragmentCode defines the fragment shader code to use
  14543. * @param context defines the webGL context to use (if not set, the current one will be used)
  14544. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14545. * @returns the new webGL program
  14546. */
  14547. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14548. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14549. context = context || this._gl;
  14550. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14551. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14552. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14553. };
  14554. /**
  14555. * Creates a webGL program
  14556. * @param vertexCode defines the vertex shader code to use
  14557. * @param fragmentCode defines the fragment shader code to use
  14558. * @param defines defines the string containing the defines to use to compile the shaders
  14559. * @param context defines the webGL context to use (if not set, the current one will be used)
  14560. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14561. * @returns the new webGL program
  14562. */
  14563. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14564. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14565. context = context || this._gl;
  14566. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14567. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14568. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14569. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14570. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14571. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14572. return program;
  14573. };
  14574. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14575. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14576. var shaderProgram = context.createProgram();
  14577. if (!shaderProgram) {
  14578. throw new Error("Unable to create program");
  14579. }
  14580. context.attachShader(shaderProgram, vertexShader);
  14581. context.attachShader(shaderProgram, fragmentShader);
  14582. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14583. var transformFeedback = this.createTransformFeedback();
  14584. this.bindTransformFeedback(transformFeedback);
  14585. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14586. shaderProgram.transformFeedback = transformFeedback;
  14587. }
  14588. context.linkProgram(shaderProgram);
  14589. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14590. this.bindTransformFeedback(null);
  14591. }
  14592. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14593. if (!linked) {
  14594. var error = context.getProgramInfoLog(shaderProgram);
  14595. if (error) {
  14596. throw new Error(error);
  14597. }
  14598. }
  14599. if (this.validateShaderPrograms) {
  14600. context.validateProgram(shaderProgram);
  14601. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14602. if (!validated) {
  14603. var error = context.getProgramInfoLog(shaderProgram);
  14604. if (error) {
  14605. throw new Error(error);
  14606. }
  14607. }
  14608. }
  14609. context.deleteShader(vertexShader);
  14610. context.deleteShader(fragmentShader);
  14611. return shaderProgram;
  14612. };
  14613. /**
  14614. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14615. * @param shaderProgram defines the webGL program to use
  14616. * @param uniformsNames defines the list of uniform names
  14617. * @returns an array of webGL uniform locations
  14618. */
  14619. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14620. var results = new Array();
  14621. for (var index = 0; index < uniformsNames.length; index++) {
  14622. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14623. }
  14624. return results;
  14625. };
  14626. /**
  14627. * Gets the lsit of active attributes for a given webGL program
  14628. * @param shaderProgram defines the webGL program to use
  14629. * @param attributesNames defines the list of attribute names to get
  14630. * @returns an array of indices indicating the offset of each attribute
  14631. */
  14632. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14633. var results = [];
  14634. for (var index = 0; index < attributesNames.length; index++) {
  14635. try {
  14636. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14637. }
  14638. catch (e) {
  14639. results.push(-1);
  14640. }
  14641. }
  14642. return results;
  14643. };
  14644. /**
  14645. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14646. * @param effect defines the effect to activate
  14647. */
  14648. Engine.prototype.enableEffect = function (effect) {
  14649. if (!effect || effect === this._currentEffect) {
  14650. return;
  14651. }
  14652. // Use program
  14653. this.bindSamplers(effect);
  14654. this._currentEffect = effect;
  14655. if (effect.onBind) {
  14656. effect.onBind(effect);
  14657. }
  14658. if (effect._onBindObservable) {
  14659. effect._onBindObservable.notifyObservers(effect);
  14660. }
  14661. };
  14662. /**
  14663. * Set the value of an uniform to an array of int32
  14664. * @param uniform defines the webGL uniform location where to store the value
  14665. * @param array defines the array of int32 to store
  14666. */
  14667. Engine.prototype.setIntArray = function (uniform, array) {
  14668. if (!uniform) {
  14669. return;
  14670. }
  14671. this._gl.uniform1iv(uniform, array);
  14672. };
  14673. /**
  14674. * Set the value of an uniform to an array of int32 (stored as vec2)
  14675. * @param uniform defines the webGL uniform location where to store the value
  14676. * @param array defines the array of int32 to store
  14677. */
  14678. Engine.prototype.setIntArray2 = function (uniform, array) {
  14679. if (!uniform || array.length % 2 !== 0) {
  14680. return;
  14681. }
  14682. this._gl.uniform2iv(uniform, array);
  14683. };
  14684. /**
  14685. * Set the value of an uniform to an array of int32 (stored as vec3)
  14686. * @param uniform defines the webGL uniform location where to store the value
  14687. * @param array defines the array of int32 to store
  14688. */
  14689. Engine.prototype.setIntArray3 = function (uniform, array) {
  14690. if (!uniform || array.length % 3 !== 0) {
  14691. return;
  14692. }
  14693. this._gl.uniform3iv(uniform, array);
  14694. };
  14695. /**
  14696. * Set the value of an uniform to an array of int32 (stored as vec4)
  14697. * @param uniform defines the webGL uniform location where to store the value
  14698. * @param array defines the array of int32 to store
  14699. */
  14700. Engine.prototype.setIntArray4 = function (uniform, array) {
  14701. if (!uniform || array.length % 4 !== 0) {
  14702. return;
  14703. }
  14704. this._gl.uniform4iv(uniform, array);
  14705. };
  14706. /**
  14707. * Set the value of an uniform to an array of float32
  14708. * @param uniform defines the webGL uniform location where to store the value
  14709. * @param array defines the array of float32 to store
  14710. */
  14711. Engine.prototype.setFloatArray = function (uniform, array) {
  14712. if (!uniform) {
  14713. return;
  14714. }
  14715. this._gl.uniform1fv(uniform, array);
  14716. };
  14717. /**
  14718. * Set the value of an uniform to an array of float32 (stored as vec2)
  14719. * @param uniform defines the webGL uniform location where to store the value
  14720. * @param array defines the array of float32 to store
  14721. */
  14722. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14723. if (!uniform || array.length % 2 !== 0) {
  14724. return;
  14725. }
  14726. this._gl.uniform2fv(uniform, array);
  14727. };
  14728. /**
  14729. * Set the value of an uniform to an array of float32 (stored as vec3)
  14730. * @param uniform defines the webGL uniform location where to store the value
  14731. * @param array defines the array of float32 to store
  14732. */
  14733. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14734. if (!uniform || array.length % 3 !== 0) {
  14735. return;
  14736. }
  14737. this._gl.uniform3fv(uniform, array);
  14738. };
  14739. /**
  14740. * Set the value of an uniform to an array of float32 (stored as vec4)
  14741. * @param uniform defines the webGL uniform location where to store the value
  14742. * @param array defines the array of float32 to store
  14743. */
  14744. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14745. if (!uniform || array.length % 4 !== 0) {
  14746. return;
  14747. }
  14748. this._gl.uniform4fv(uniform, array);
  14749. };
  14750. /**
  14751. * Set the value of an uniform to an array of number
  14752. * @param uniform defines the webGL uniform location where to store the value
  14753. * @param array defines the array of number to store
  14754. */
  14755. Engine.prototype.setArray = function (uniform, array) {
  14756. if (!uniform) {
  14757. return;
  14758. }
  14759. this._gl.uniform1fv(uniform, array);
  14760. };
  14761. /**
  14762. * Set the value of an uniform to an array of number (stored as vec2)
  14763. * @param uniform defines the webGL uniform location where to store the value
  14764. * @param array defines the array of number to store
  14765. */
  14766. Engine.prototype.setArray2 = function (uniform, array) {
  14767. if (!uniform || array.length % 2 !== 0) {
  14768. return;
  14769. }
  14770. this._gl.uniform2fv(uniform, array);
  14771. };
  14772. /**
  14773. * Set the value of an uniform to an array of number (stored as vec3)
  14774. * @param uniform defines the webGL uniform location where to store the value
  14775. * @param array defines the array of number to store
  14776. */
  14777. Engine.prototype.setArray3 = function (uniform, array) {
  14778. if (!uniform || array.length % 3 !== 0) {
  14779. return;
  14780. }
  14781. this._gl.uniform3fv(uniform, array);
  14782. };
  14783. /**
  14784. * Set the value of an uniform to an array of number (stored as vec4)
  14785. * @param uniform defines the webGL uniform location where to store the value
  14786. * @param array defines the array of number to store
  14787. */
  14788. Engine.prototype.setArray4 = function (uniform, array) {
  14789. if (!uniform || array.length % 4 !== 0) {
  14790. return;
  14791. }
  14792. this._gl.uniform4fv(uniform, array);
  14793. };
  14794. /**
  14795. * Set the value of an uniform to an array of float32 (stored as matrices)
  14796. * @param uniform defines the webGL uniform location where to store the value
  14797. * @param matrices defines the array of float32 to store
  14798. */
  14799. Engine.prototype.setMatrices = function (uniform, matrices) {
  14800. if (!uniform) {
  14801. return;
  14802. }
  14803. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14804. };
  14805. /**
  14806. * Set the value of an uniform to a matrix
  14807. * @param uniform defines the webGL uniform location where to store the value
  14808. * @param matrix defines the matrix to store
  14809. */
  14810. Engine.prototype.setMatrix = function (uniform, matrix) {
  14811. if (!uniform) {
  14812. return;
  14813. }
  14814. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14815. };
  14816. /**
  14817. * Set the value of an uniform to a matrix (3x3)
  14818. * @param uniform defines the webGL uniform location where to store the value
  14819. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14820. */
  14821. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14822. if (!uniform) {
  14823. return;
  14824. }
  14825. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14826. };
  14827. /**
  14828. * Set the value of an uniform to a matrix (2x2)
  14829. * @param uniform defines the webGL uniform location where to store the value
  14830. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14831. */
  14832. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14833. if (!uniform) {
  14834. return;
  14835. }
  14836. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14837. };
  14838. /**
  14839. * Set the value of an uniform to a number (int)
  14840. * @param uniform defines the webGL uniform location where to store the value
  14841. * @param value defines the int number to store
  14842. */
  14843. Engine.prototype.setInt = function (uniform, value) {
  14844. if (!uniform) {
  14845. return;
  14846. }
  14847. this._gl.uniform1i(uniform, value);
  14848. };
  14849. /**
  14850. * Set the value of an uniform to a number (float)
  14851. * @param uniform defines the webGL uniform location where to store the value
  14852. * @param value defines the float number to store
  14853. */
  14854. Engine.prototype.setFloat = function (uniform, value) {
  14855. if (!uniform) {
  14856. return;
  14857. }
  14858. this._gl.uniform1f(uniform, value);
  14859. };
  14860. /**
  14861. * Set the value of an uniform to a vec2
  14862. * @param uniform defines the webGL uniform location where to store the value
  14863. * @param x defines the 1st component of the value
  14864. * @param y defines the 2nd component of the value
  14865. */
  14866. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14867. if (!uniform) {
  14868. return;
  14869. }
  14870. this._gl.uniform2f(uniform, x, y);
  14871. };
  14872. /**
  14873. * Set the value of an uniform to a vec3
  14874. * @param uniform defines the webGL uniform location where to store the value
  14875. * @param x defines the 1st component of the value
  14876. * @param y defines the 2nd component of the value
  14877. * @param z defines the 3rd component of the value
  14878. */
  14879. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14880. if (!uniform) {
  14881. return;
  14882. }
  14883. this._gl.uniform3f(uniform, x, y, z);
  14884. };
  14885. /**
  14886. * Set the value of an uniform to a boolean
  14887. * @param uniform defines the webGL uniform location where to store the value
  14888. * @param bool defines the boolean to store
  14889. */
  14890. Engine.prototype.setBool = function (uniform, bool) {
  14891. if (!uniform) {
  14892. return;
  14893. }
  14894. this._gl.uniform1i(uniform, bool);
  14895. };
  14896. /**
  14897. * Set the value of an uniform to a vec4
  14898. * @param uniform defines the webGL uniform location where to store the value
  14899. * @param x defines the 1st component of the value
  14900. * @param y defines the 2nd component of the value
  14901. * @param z defines the 3rd component of the value
  14902. * @param w defines the 4th component of the value
  14903. */
  14904. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14905. if (!uniform) {
  14906. return;
  14907. }
  14908. this._gl.uniform4f(uniform, x, y, z, w);
  14909. };
  14910. /**
  14911. * Set the value of an uniform to a Color3
  14912. * @param uniform defines the webGL uniform location where to store the value
  14913. * @param color3 defines the color to store
  14914. */
  14915. Engine.prototype.setColor3 = function (uniform, color3) {
  14916. if (!uniform) {
  14917. return;
  14918. }
  14919. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14920. };
  14921. /**
  14922. * Set the value of an uniform to a Color3 and an alpha value
  14923. * @param uniform defines the webGL uniform location where to store the value
  14924. * @param color3 defines the color to store
  14925. * @param alpha defines the alpha component to store
  14926. */
  14927. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14928. if (!uniform) {
  14929. return;
  14930. }
  14931. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14932. };
  14933. /**
  14934. * Sets a Color4 on a uniform variable
  14935. * @param uniform defines the uniform location
  14936. * @param color4 defines the value to be set
  14937. */
  14938. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14939. if (!uniform) {
  14940. return;
  14941. }
  14942. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14943. };
  14944. // States
  14945. /**
  14946. * Set various states to the webGL context
  14947. * @param culling defines backface culling state
  14948. * @param zOffset defines the value to apply to zOffset (0 by default)
  14949. * @param force defines if states must be applied even if cache is up to date
  14950. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14951. */
  14952. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14953. if (zOffset === void 0) { zOffset = 0; }
  14954. if (reverseSide === void 0) { reverseSide = false; }
  14955. // Culling
  14956. if (this._depthCullingState.cull !== culling || force) {
  14957. this._depthCullingState.cull = culling;
  14958. }
  14959. // Cull face
  14960. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14961. if (this._depthCullingState.cullFace !== cullFace || force) {
  14962. this._depthCullingState.cullFace = cullFace;
  14963. }
  14964. // Z offset
  14965. this.setZOffset(zOffset);
  14966. // Front face
  14967. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14968. if (this._depthCullingState.frontFace !== frontFace || force) {
  14969. this._depthCullingState.frontFace = frontFace;
  14970. }
  14971. };
  14972. /**
  14973. * Set the z offset to apply to current rendering
  14974. * @param value defines the offset to apply
  14975. */
  14976. Engine.prototype.setZOffset = function (value) {
  14977. this._depthCullingState.zOffset = value;
  14978. };
  14979. /**
  14980. * Gets the current value of the zOffset
  14981. * @returns the current zOffset state
  14982. */
  14983. Engine.prototype.getZOffset = function () {
  14984. return this._depthCullingState.zOffset;
  14985. };
  14986. /**
  14987. * Enable or disable depth buffering
  14988. * @param enable defines the state to set
  14989. */
  14990. Engine.prototype.setDepthBuffer = function (enable) {
  14991. this._depthCullingState.depthTest = enable;
  14992. };
  14993. /**
  14994. * Gets a boolean indicating if depth writing is enabled
  14995. * @returns the current depth writing state
  14996. */
  14997. Engine.prototype.getDepthWrite = function () {
  14998. return this._depthCullingState.depthMask;
  14999. };
  15000. /**
  15001. * Enable or disable depth writing
  15002. * @param enable defines the state to set
  15003. */
  15004. Engine.prototype.setDepthWrite = function (enable) {
  15005. this._depthCullingState.depthMask = enable;
  15006. };
  15007. /**
  15008. * Enable or disable color writing
  15009. * @param enable defines the state to set
  15010. */
  15011. Engine.prototype.setColorWrite = function (enable) {
  15012. this._gl.colorMask(enable, enable, enable, enable);
  15013. this._colorWrite = enable;
  15014. };
  15015. /**
  15016. * Gets a boolean indicating if color writing is enabled
  15017. * @returns the current color writing state
  15018. */
  15019. Engine.prototype.getColorWrite = function () {
  15020. return this._colorWrite;
  15021. };
  15022. /**
  15023. * Sets alpha constants used by some alpha blending modes
  15024. * @param r defines the red component
  15025. * @param g defines the green component
  15026. * @param b defines the blue component
  15027. * @param a defines the alpha component
  15028. */
  15029. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15030. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15031. };
  15032. /**
  15033. * Sets the current alpha mode
  15034. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15035. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15036. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15037. */
  15038. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15039. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15040. if (this._alphaMode === mode) {
  15041. return;
  15042. }
  15043. switch (mode) {
  15044. case Engine.ALPHA_DISABLE:
  15045. this._alphaState.alphaBlend = false;
  15046. break;
  15047. case Engine.ALPHA_PREMULTIPLIED:
  15048. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15049. this._alphaState.alphaBlend = true;
  15050. break;
  15051. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15052. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15053. this._alphaState.alphaBlend = true;
  15054. break;
  15055. case Engine.ALPHA_COMBINE:
  15056. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15057. this._alphaState.alphaBlend = true;
  15058. break;
  15059. case Engine.ALPHA_ONEONE:
  15060. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15061. this._alphaState.alphaBlend = true;
  15062. break;
  15063. case Engine.ALPHA_ADD:
  15064. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15065. this._alphaState.alphaBlend = true;
  15066. break;
  15067. case Engine.ALPHA_SUBTRACT:
  15068. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15069. this._alphaState.alphaBlend = true;
  15070. break;
  15071. case Engine.ALPHA_MULTIPLY:
  15072. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15073. this._alphaState.alphaBlend = true;
  15074. break;
  15075. case Engine.ALPHA_MAXIMIZED:
  15076. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15077. this._alphaState.alphaBlend = true;
  15078. break;
  15079. case Engine.ALPHA_INTERPOLATE:
  15080. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15081. this._alphaState.alphaBlend = true;
  15082. break;
  15083. case Engine.ALPHA_SCREENMODE:
  15084. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15085. this._alphaState.alphaBlend = true;
  15086. break;
  15087. }
  15088. if (!noDepthWriteChange) {
  15089. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15090. }
  15091. this._alphaMode = mode;
  15092. };
  15093. /**
  15094. * Gets the current alpha mode
  15095. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15096. * @returns the current alpha mode
  15097. */
  15098. Engine.prototype.getAlphaMode = function () {
  15099. return this._alphaMode;
  15100. };
  15101. // Textures
  15102. /**
  15103. * Clears the list of texture accessible through engine.
  15104. * This can help preventing texture load conflict due to name collision.
  15105. */
  15106. Engine.prototype.clearInternalTexturesCache = function () {
  15107. this._internalTexturesCache = [];
  15108. };
  15109. /**
  15110. * Force the entire cache to be cleared
  15111. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15112. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15113. */
  15114. Engine.prototype.wipeCaches = function (bruteForce) {
  15115. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15116. return;
  15117. }
  15118. this._currentEffect = null;
  15119. this._viewportCached.x = 0;
  15120. this._viewportCached.y = 0;
  15121. this._viewportCached.z = 0;
  15122. this._viewportCached.w = 0;
  15123. if (bruteForce) {
  15124. this.resetTextureCache();
  15125. this._currentProgram = null;
  15126. this._stencilState.reset();
  15127. this._depthCullingState.reset();
  15128. this.setDepthFunctionToLessOrEqual();
  15129. this._alphaState.reset();
  15130. this._unpackFlipYCached = null;
  15131. }
  15132. this._resetVertexBufferBinding();
  15133. this._cachedIndexBuffer = null;
  15134. this._cachedEffectForVertexBuffers = null;
  15135. this._unbindVertexArrayObject();
  15136. this.bindIndexBuffer(null);
  15137. };
  15138. /**
  15139. * Set the compressed texture format to use, based on the formats you have, and the formats
  15140. * supported by the hardware / browser.
  15141. *
  15142. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15143. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15144. * to API arguments needed to compressed textures. This puts the burden on the container
  15145. * generator to house the arcane code for determining these for current & future formats.
  15146. *
  15147. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15148. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15149. *
  15150. * Note: The result of this call is not taken into account when a texture is base64.
  15151. *
  15152. * @param formatsAvailable defines the list of those format families you have created
  15153. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15154. *
  15155. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15156. * @returns The extension selected.
  15157. */
  15158. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15159. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15160. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15161. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15162. return this._textureFormatInUse = this._texturesSupported[i];
  15163. }
  15164. }
  15165. }
  15166. // actively set format to nothing, to allow this to be called more than once
  15167. // and possibly fail the 2nd time
  15168. this._textureFormatInUse = null;
  15169. return null;
  15170. };
  15171. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15172. var gl = this._gl;
  15173. var magFilter = gl.NEAREST;
  15174. var minFilter = gl.NEAREST;
  15175. switch (samplingMode) {
  15176. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15177. magFilter = gl.LINEAR;
  15178. if (generateMipMaps) {
  15179. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15180. }
  15181. else {
  15182. minFilter = gl.LINEAR;
  15183. }
  15184. break;
  15185. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15186. magFilter = gl.LINEAR;
  15187. if (generateMipMaps) {
  15188. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15189. }
  15190. else {
  15191. minFilter = gl.LINEAR;
  15192. }
  15193. break;
  15194. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15195. magFilter = gl.NEAREST;
  15196. if (generateMipMaps) {
  15197. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15198. }
  15199. else {
  15200. minFilter = gl.NEAREST;
  15201. }
  15202. break;
  15203. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15204. magFilter = gl.NEAREST;
  15205. if (generateMipMaps) {
  15206. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15207. }
  15208. else {
  15209. minFilter = gl.NEAREST;
  15210. }
  15211. break;
  15212. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15213. magFilter = gl.NEAREST;
  15214. if (generateMipMaps) {
  15215. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15216. }
  15217. else {
  15218. minFilter = gl.LINEAR;
  15219. }
  15220. break;
  15221. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15222. magFilter = gl.NEAREST;
  15223. if (generateMipMaps) {
  15224. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15225. }
  15226. else {
  15227. minFilter = gl.LINEAR;
  15228. }
  15229. break;
  15230. case Engine.TEXTURE_NEAREST_LINEAR:
  15231. magFilter = gl.NEAREST;
  15232. minFilter = gl.LINEAR;
  15233. break;
  15234. case Engine.TEXTURE_NEAREST_NEAREST:
  15235. magFilter = gl.NEAREST;
  15236. minFilter = gl.NEAREST;
  15237. break;
  15238. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15239. magFilter = gl.LINEAR;
  15240. if (generateMipMaps) {
  15241. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15242. }
  15243. else {
  15244. minFilter = gl.NEAREST;
  15245. }
  15246. break;
  15247. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15248. magFilter = gl.LINEAR;
  15249. if (generateMipMaps) {
  15250. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15251. }
  15252. else {
  15253. minFilter = gl.NEAREST;
  15254. }
  15255. break;
  15256. case Engine.TEXTURE_LINEAR_LINEAR:
  15257. magFilter = gl.LINEAR;
  15258. minFilter = gl.LINEAR;
  15259. break;
  15260. case Engine.TEXTURE_LINEAR_NEAREST:
  15261. magFilter = gl.LINEAR;
  15262. minFilter = gl.NEAREST;
  15263. break;
  15264. }
  15265. return {
  15266. min: minFilter,
  15267. mag: magFilter
  15268. };
  15269. };
  15270. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15271. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15272. var img;
  15273. var onload = function () {
  15274. loadedImages[index] = img;
  15275. loadedImages._internalCount++;
  15276. if (scene) {
  15277. scene._removePendingData(img);
  15278. }
  15279. if (loadedImages._internalCount === 6) {
  15280. onfinish(loadedImages);
  15281. }
  15282. };
  15283. var onerror = function (message, exception) {
  15284. if (scene) {
  15285. scene._removePendingData(img);
  15286. }
  15287. if (onErrorCallBack) {
  15288. onErrorCallBack(message, exception);
  15289. }
  15290. };
  15291. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15292. if (scene) {
  15293. scene._addPendingData(img);
  15294. }
  15295. };
  15296. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15297. if (onError === void 0) { onError = null; }
  15298. var loadedImages = [];
  15299. loadedImages._internalCount = 0;
  15300. for (var index = 0; index < 6; index++) {
  15301. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15302. }
  15303. };
  15304. /** @hidden */
  15305. Engine.prototype._createTexture = function () {
  15306. var texture = this._gl.createTexture();
  15307. if (!texture) {
  15308. throw new Error("Unable to create texture");
  15309. }
  15310. return texture;
  15311. };
  15312. /**
  15313. * Usually called from BABYLON.Texture.ts.
  15314. * Passed information to create a WebGLTexture
  15315. * @param urlArg defines a value which contains one of the following:
  15316. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15317. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15318. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15319. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15320. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15321. * @param scene needed for loading to the correct scene
  15322. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15323. * @param onLoad optional callback to be called upon successful completion
  15324. * @param onError optional callback to be called upon failure
  15325. * @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
  15326. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15327. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15328. * @param forcedExtension defines the extension to use to pick the right loader
  15329. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15330. */
  15331. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15332. var _this = this;
  15333. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15334. if (onLoad === void 0) { onLoad = null; }
  15335. if (onError === void 0) { onError = null; }
  15336. if (buffer === void 0) { buffer = null; }
  15337. if (fallback === void 0) { fallback = null; }
  15338. if (format === void 0) { format = null; }
  15339. if (forcedExtension === void 0) { forcedExtension = null; }
  15340. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15341. var fromData = url.substr(0, 5) === "data:";
  15342. var fromBlob = url.substr(0, 5) === "blob:";
  15343. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15344. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15345. // establish the file extension, if possible
  15346. var lastDot = url.lastIndexOf('.');
  15347. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15348. var loader = null;
  15349. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15350. var availableLoader = _a[_i];
  15351. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15352. loader = availableLoader;
  15353. break;
  15354. }
  15355. }
  15356. if (loader) {
  15357. url = loader.transformUrl(url, this._textureFormatInUse);
  15358. }
  15359. if (scene) {
  15360. scene._addPendingData(texture);
  15361. }
  15362. texture.url = url;
  15363. texture.generateMipMaps = !noMipmap;
  15364. texture.samplingMode = samplingMode;
  15365. texture.invertY = invertY;
  15366. if (!this._doNotHandleContextLost) {
  15367. // Keep a link to the buffer only if we plan to handle context lost
  15368. texture._buffer = buffer;
  15369. }
  15370. var onLoadObserver = null;
  15371. if (onLoad && !fallback) {
  15372. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15373. }
  15374. if (!fallback) {
  15375. this._internalTexturesCache.push(texture);
  15376. }
  15377. var onInternalError = function (message, exception) {
  15378. if (scene) {
  15379. scene._removePendingData(texture);
  15380. }
  15381. var customFallback = false;
  15382. if (loader) {
  15383. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15384. if (fallbackUrl) {
  15385. // Add Back
  15386. customFallback = true;
  15387. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15388. }
  15389. }
  15390. if (!customFallback) {
  15391. if (onLoadObserver) {
  15392. texture.onLoadedObservable.remove(onLoadObserver);
  15393. }
  15394. if (BABYLON.Tools.UseFallbackTexture) {
  15395. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15396. }
  15397. }
  15398. if (onError) {
  15399. onError(message || "Unknown error", exception);
  15400. }
  15401. };
  15402. // processing for non-image formats
  15403. if (loader) {
  15404. var callback = function (data) {
  15405. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15406. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15407. done();
  15408. return false;
  15409. }, samplingMode);
  15410. });
  15411. };
  15412. if (!buffer) {
  15413. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15414. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15415. });
  15416. }
  15417. else {
  15418. callback(buffer);
  15419. }
  15420. }
  15421. else {
  15422. var onload = function (img) {
  15423. if (fromBlob && !_this._doNotHandleContextLost) {
  15424. // We need to store the image if we need to rebuild the texture
  15425. // in case of a webgl context lost
  15426. texture._buffer = img;
  15427. }
  15428. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15429. var gl = _this._gl;
  15430. var isPot = (img.width === potWidth && img.height === potHeight);
  15431. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15432. if (isPot) {
  15433. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15434. return false;
  15435. }
  15436. var maxTextureSize = _this._caps.maxTextureSize;
  15437. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15438. _this._prepareWorkingCanvas();
  15439. if (!_this._workingCanvas || !_this._workingContext) {
  15440. return false;
  15441. }
  15442. _this._workingCanvas.width = potWidth;
  15443. _this._workingCanvas.height = potHeight;
  15444. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15445. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15446. texture.width = potWidth;
  15447. texture.height = potHeight;
  15448. return false;
  15449. }
  15450. else {
  15451. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15452. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15453. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15454. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15455. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15456. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15459. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15460. _this._releaseTexture(source_1);
  15461. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15462. continuationCallback();
  15463. });
  15464. }
  15465. return true;
  15466. }, samplingMode);
  15467. };
  15468. if (!fromData || isBase64) {
  15469. if (buffer instanceof HTMLImageElement) {
  15470. onload(buffer);
  15471. }
  15472. else {
  15473. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15474. }
  15475. }
  15476. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15477. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15478. }
  15479. else {
  15480. onload(buffer);
  15481. }
  15482. }
  15483. return texture;
  15484. };
  15485. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15486. var _this = this;
  15487. var rtt = this.createRenderTargetTexture({
  15488. width: destination.width,
  15489. height: destination.height,
  15490. }, {
  15491. generateMipMaps: false,
  15492. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15493. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15494. generateDepthBuffer: false,
  15495. generateStencilBuffer: false
  15496. });
  15497. if (!this._rescalePostProcess) {
  15498. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15499. }
  15500. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15501. _this._rescalePostProcess.onApply = function (effect) {
  15502. effect._bindTexture("textureSampler", source);
  15503. };
  15504. var hostingScene = scene;
  15505. if (!hostingScene) {
  15506. hostingScene = _this.scenes[_this.scenes.length - 1];
  15507. }
  15508. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15509. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15510. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15511. _this.unBindFramebuffer(rtt);
  15512. _this._releaseTexture(rtt);
  15513. if (onComplete) {
  15514. onComplete();
  15515. }
  15516. });
  15517. };
  15518. /**
  15519. * Update a raw texture
  15520. * @param texture defines the texture to update
  15521. * @param data defines the data to store in the texture
  15522. * @param format defines the format of the data
  15523. * @param invertY defines if data must be stored with Y axis inverted
  15524. * @param compression defines the compression used (null by default)
  15525. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15526. */
  15527. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15528. if (compression === void 0) { compression = null; }
  15529. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15530. if (!texture) {
  15531. return;
  15532. }
  15533. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15534. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15535. // babylon's internalFormat but gl's texImage2D format
  15536. var internalFormat = this._getInternalFormat(format);
  15537. var textureType = this._getWebGLTextureType(type);
  15538. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15539. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15540. if (!this._doNotHandleContextLost) {
  15541. texture._bufferView = data;
  15542. texture.format = format;
  15543. texture.type = type;
  15544. texture.invertY = invertY;
  15545. texture._compression = compression;
  15546. }
  15547. if (texture.width % 4 !== 0) {
  15548. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15549. }
  15550. if (compression && data) {
  15551. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15552. }
  15553. else {
  15554. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15555. }
  15556. if (texture.generateMipMaps) {
  15557. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15558. }
  15559. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15560. // this.resetTextureCache();
  15561. texture.isReady = true;
  15562. };
  15563. /**
  15564. * Creates a raw texture
  15565. * @param data defines the data to store in the texture
  15566. * @param width defines the width of the texture
  15567. * @param height defines the height of the texture
  15568. * @param format defines the format of the data
  15569. * @param generateMipMaps defines if the engine should generate the mip levels
  15570. * @param invertY defines if data must be stored with Y axis inverted
  15571. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15572. * @param compression defines the compression used (null by default)
  15573. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15574. * @returns the raw texture inside an InternalTexture
  15575. */
  15576. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15577. if (compression === void 0) { compression = null; }
  15578. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15579. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15580. texture.baseWidth = width;
  15581. texture.baseHeight = height;
  15582. texture.width = width;
  15583. texture.height = height;
  15584. texture.format = format;
  15585. texture.generateMipMaps = generateMipMaps;
  15586. texture.samplingMode = samplingMode;
  15587. texture.invertY = invertY;
  15588. texture._compression = compression;
  15589. texture.type = type;
  15590. if (!this._doNotHandleContextLost) {
  15591. texture._bufferView = data;
  15592. }
  15593. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15594. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15595. // Filters
  15596. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15597. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15599. if (generateMipMaps) {
  15600. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15601. }
  15602. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15603. this._internalTexturesCache.push(texture);
  15604. return texture;
  15605. };
  15606. /** @hidden */
  15607. Engine.prototype._unpackFlipY = function (value) {
  15608. if (this._unpackFlipYCached !== value) {
  15609. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15610. if (this.enableUnpackFlipYCached) {
  15611. this._unpackFlipYCached = value;
  15612. }
  15613. }
  15614. };
  15615. /** @hidden */
  15616. Engine.prototype._getUnpackAlignement = function () {
  15617. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15618. };
  15619. /**
  15620. * Creates a dynamic texture
  15621. * @param width defines the width of the texture
  15622. * @param height defines the height of the texture
  15623. * @param generateMipMaps defines if the engine should generate the mip levels
  15624. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15625. * @returns the dynamic texture inside an InternalTexture
  15626. */
  15627. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15628. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15629. texture.baseWidth = width;
  15630. texture.baseHeight = height;
  15631. if (generateMipMaps) {
  15632. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15633. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15634. }
  15635. // this.resetTextureCache();
  15636. texture.width = width;
  15637. texture.height = height;
  15638. texture.isReady = false;
  15639. texture.generateMipMaps = generateMipMaps;
  15640. texture.samplingMode = samplingMode;
  15641. this.updateTextureSamplingMode(samplingMode, texture);
  15642. this._internalTexturesCache.push(texture);
  15643. return texture;
  15644. };
  15645. /**
  15646. * Update the sampling mode of a given texture
  15647. * @param samplingMode defines the required sampling mode
  15648. * @param texture defines the texture to update
  15649. */
  15650. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15651. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15652. if (texture.isCube) {
  15653. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15654. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15655. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15656. }
  15657. else if (texture.is3D) {
  15658. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15659. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15660. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15661. }
  15662. else {
  15663. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15664. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15665. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15666. }
  15667. texture.samplingMode = samplingMode;
  15668. };
  15669. /**
  15670. * Update the content of a dynamic texture
  15671. * @param texture defines the texture to update
  15672. * @param canvas defines the canvas containing the source
  15673. * @param invertY defines if data must be stored with Y axis inverted
  15674. * @param premulAlpha defines if alpha is stored as premultiplied
  15675. * @param format defines the format of the data
  15676. */
  15677. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15678. if (premulAlpha === void 0) { premulAlpha = false; }
  15679. if (!texture) {
  15680. return;
  15681. }
  15682. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15683. this._unpackFlipY(invertY);
  15684. if (premulAlpha) {
  15685. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15686. }
  15687. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15688. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15689. if (texture.generateMipMaps) {
  15690. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15691. }
  15692. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15693. if (premulAlpha) {
  15694. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15695. }
  15696. texture.isReady = true;
  15697. };
  15698. /**
  15699. * Update a video texture
  15700. * @param texture defines the texture to update
  15701. * @param video defines the video element to use
  15702. * @param invertY defines if data must be stored with Y axis inverted
  15703. */
  15704. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15705. if (!texture || texture._isDisabled) {
  15706. return;
  15707. }
  15708. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15709. this._unpackFlipY(!invertY); // Video are upside down by default
  15710. try {
  15711. // Testing video texture support
  15712. if (this._videoTextureSupported === undefined) {
  15713. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15714. if (this._gl.getError() !== 0) {
  15715. this._videoTextureSupported = false;
  15716. }
  15717. else {
  15718. this._videoTextureSupported = true;
  15719. }
  15720. }
  15721. // Copy video through the current working canvas if video texture is not supported
  15722. if (!this._videoTextureSupported) {
  15723. if (!texture._workingCanvas) {
  15724. texture._workingCanvas = document.createElement("canvas");
  15725. var context = texture._workingCanvas.getContext("2d");
  15726. if (!context) {
  15727. throw new Error("Unable to get 2d context");
  15728. }
  15729. texture._workingContext = context;
  15730. texture._workingCanvas.width = texture.width;
  15731. texture._workingCanvas.height = texture.height;
  15732. }
  15733. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15734. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15735. }
  15736. else {
  15737. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15738. }
  15739. if (texture.generateMipMaps) {
  15740. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15741. }
  15742. if (!wasPreviouslyBound) {
  15743. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15744. }
  15745. // this.resetTextureCache();
  15746. texture.isReady = true;
  15747. }
  15748. catch (ex) {
  15749. // Something unexpected
  15750. // Let's disable the texture
  15751. texture._isDisabled = true;
  15752. }
  15753. };
  15754. /**
  15755. * Updates a depth texture Comparison Mode and Function.
  15756. * If the comparison Function is equal to 0, the mode will be set to none.
  15757. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15758. * @param texture The texture to set the comparison function for
  15759. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15760. */
  15761. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15762. if (this.webGLVersion === 1) {
  15763. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15764. return;
  15765. }
  15766. var gl = this._gl;
  15767. if (texture.isCube) {
  15768. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15769. if (comparisonFunction === 0) {
  15770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15771. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15772. }
  15773. else {
  15774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15776. }
  15777. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15778. }
  15779. else {
  15780. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15781. if (comparisonFunction === 0) {
  15782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15783. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15784. }
  15785. else {
  15786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15787. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15788. }
  15789. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15790. }
  15791. texture._comparisonFunction = comparisonFunction;
  15792. };
  15793. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15794. var width = size.width || size;
  15795. var height = size.height || size;
  15796. internalTexture.baseWidth = width;
  15797. internalTexture.baseHeight = height;
  15798. internalTexture.width = width;
  15799. internalTexture.height = height;
  15800. internalTexture.isReady = true;
  15801. internalTexture.samples = 1;
  15802. internalTexture.generateMipMaps = false;
  15803. internalTexture._generateDepthBuffer = true;
  15804. internalTexture._generateStencilBuffer = generateStencil;
  15805. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15806. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15807. internalTexture._comparisonFunction = comparisonFunction;
  15808. var gl = this._gl;
  15809. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15810. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15811. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15812. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15813. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15814. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15815. if (comparisonFunction === 0) {
  15816. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15817. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15818. }
  15819. else {
  15820. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15821. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15822. }
  15823. };
  15824. /**
  15825. * Creates a depth stencil texture.
  15826. * This is only available in WebGL 2 or with the depth texture extension available.
  15827. * @param size The size of face edge in the texture.
  15828. * @param options The options defining the texture.
  15829. * @returns The texture
  15830. */
  15831. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15832. if (options.isCube) {
  15833. var width = size.width || size;
  15834. return this._createDepthStencilCubeTexture(width, options);
  15835. }
  15836. else {
  15837. return this._createDepthStencilTexture(size, options);
  15838. }
  15839. };
  15840. /**
  15841. * Creates a depth stencil texture.
  15842. * This is only available in WebGL 2 or with the depth texture extension available.
  15843. * @param size The size of face edge in the texture.
  15844. * @param options The options defining the texture.
  15845. * @returns The texture
  15846. */
  15847. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15848. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15849. if (!this._caps.depthTextureExtension) {
  15850. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15851. return internalTexture;
  15852. }
  15853. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15854. var gl = this._gl;
  15855. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15856. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15857. if (this.webGLVersion > 1) {
  15858. if (internalOptions.generateStencil) {
  15859. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15860. }
  15861. else {
  15862. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15863. }
  15864. }
  15865. else {
  15866. if (internalOptions.generateStencil) {
  15867. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15868. }
  15869. else {
  15870. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15871. }
  15872. }
  15873. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15874. return internalTexture;
  15875. };
  15876. /**
  15877. * Creates a depth stencil cube texture.
  15878. * This is only available in WebGL 2.
  15879. * @param size The size of face edge in the cube texture.
  15880. * @param options The options defining the cube texture.
  15881. * @returns The cube texture
  15882. */
  15883. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15884. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15885. internalTexture.isCube = true;
  15886. if (this.webGLVersion === 1) {
  15887. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15888. return internalTexture;
  15889. }
  15890. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15891. var gl = this._gl;
  15892. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15893. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15894. // Create the depth/stencil buffer
  15895. for (var face = 0; face < 6; face++) {
  15896. if (internalOptions.generateStencil) {
  15897. 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);
  15898. }
  15899. else {
  15900. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15901. }
  15902. }
  15903. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15904. return internalTexture;
  15905. };
  15906. /**
  15907. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15908. * @param renderTarget The render target to set the frame buffer for
  15909. */
  15910. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15911. // Create the framebuffer
  15912. var internalTexture = renderTarget.getInternalTexture();
  15913. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15914. return;
  15915. }
  15916. var gl = this._gl;
  15917. var depthStencilTexture = renderTarget.depthStencilTexture;
  15918. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15919. if (depthStencilTexture.isCube) {
  15920. if (depthStencilTexture._generateStencilBuffer) {
  15921. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15922. }
  15923. else {
  15924. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15925. }
  15926. }
  15927. else {
  15928. if (depthStencilTexture._generateStencilBuffer) {
  15929. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15930. }
  15931. else {
  15932. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15933. }
  15934. }
  15935. this.bindUnboundFramebuffer(null);
  15936. };
  15937. /**
  15938. * Creates a new render target texture
  15939. * @param size defines the size of the texture
  15940. * @param options defines the options used to create the texture
  15941. * @returns a new render target texture stored in an InternalTexture
  15942. */
  15943. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15944. var fullOptions = new RenderTargetCreationOptions();
  15945. if (options !== undefined && typeof options === "object") {
  15946. fullOptions.generateMipMaps = options.generateMipMaps;
  15947. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15948. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15949. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15950. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15951. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15952. }
  15953. else {
  15954. fullOptions.generateMipMaps = options;
  15955. fullOptions.generateDepthBuffer = true;
  15956. fullOptions.generateStencilBuffer = false;
  15957. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15958. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15959. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15960. }
  15961. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15962. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15963. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15964. }
  15965. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15966. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15967. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15968. }
  15969. var gl = this._gl;
  15970. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15971. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15972. var width = size.width || size;
  15973. var height = size.height || size;
  15974. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15975. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15976. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15977. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15978. }
  15979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15981. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15982. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15983. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15984. // Create the framebuffer
  15985. var currentFrameBuffer = this._currentFramebuffer;
  15986. var framebuffer = gl.createFramebuffer();
  15987. this.bindUnboundFramebuffer(framebuffer);
  15988. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15989. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15990. if (fullOptions.generateMipMaps) {
  15991. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15992. }
  15993. // Unbind
  15994. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15995. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15996. this.bindUnboundFramebuffer(currentFrameBuffer);
  15997. texture._framebuffer = framebuffer;
  15998. texture.baseWidth = width;
  15999. texture.baseHeight = height;
  16000. texture.width = width;
  16001. texture.height = height;
  16002. texture.isReady = true;
  16003. texture.samples = 1;
  16004. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16005. texture.samplingMode = fullOptions.samplingMode;
  16006. texture.type = fullOptions.type;
  16007. texture.format = fullOptions.format;
  16008. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16009. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16010. // this.resetTextureCache();
  16011. this._internalTexturesCache.push(texture);
  16012. return texture;
  16013. };
  16014. /**
  16015. * Create a multi render target texture
  16016. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16017. * @param size defines the size of the texture
  16018. * @param options defines the creation options
  16019. * @returns the cube texture as an InternalTexture
  16020. */
  16021. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16022. var generateMipMaps = false;
  16023. var generateDepthBuffer = true;
  16024. var generateStencilBuffer = false;
  16025. var generateDepthTexture = false;
  16026. var textureCount = 1;
  16027. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16028. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16029. var types = new Array();
  16030. var samplingModes = new Array();
  16031. if (options !== undefined) {
  16032. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16033. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16034. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16035. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16036. textureCount = options.textureCount || 1;
  16037. if (options.types) {
  16038. types = options.types;
  16039. }
  16040. if (options.samplingModes) {
  16041. samplingModes = options.samplingModes;
  16042. }
  16043. }
  16044. var gl = this._gl;
  16045. // Create the framebuffer
  16046. var framebuffer = gl.createFramebuffer();
  16047. this.bindUnboundFramebuffer(framebuffer);
  16048. var width = size.width || size;
  16049. var height = size.height || size;
  16050. var textures = [];
  16051. var attachments = [];
  16052. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16053. for (var i = 0; i < textureCount; i++) {
  16054. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16055. var type = types[i] || defaultType;
  16056. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16057. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16058. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16059. }
  16060. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16061. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16062. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16063. }
  16064. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16065. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16066. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16067. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16068. }
  16069. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16070. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16071. textures.push(texture);
  16072. attachments.push(attachment);
  16073. gl.activeTexture(gl["TEXTURE" + i]);
  16074. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16079. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16080. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16081. if (generateMipMaps) {
  16082. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16083. }
  16084. // Unbind
  16085. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16086. texture._framebuffer = framebuffer;
  16087. texture._depthStencilBuffer = depthStencilBuffer;
  16088. texture.baseWidth = width;
  16089. texture.baseHeight = height;
  16090. texture.width = width;
  16091. texture.height = height;
  16092. texture.isReady = true;
  16093. texture.samples = 1;
  16094. texture.generateMipMaps = generateMipMaps;
  16095. texture.samplingMode = samplingMode;
  16096. texture.type = type;
  16097. texture._generateDepthBuffer = generateDepthBuffer;
  16098. texture._generateStencilBuffer = generateStencilBuffer;
  16099. texture._attachments = attachments;
  16100. this._internalTexturesCache.push(texture);
  16101. }
  16102. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16103. // Depth texture
  16104. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16105. gl.activeTexture(gl.TEXTURE0);
  16106. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16109. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16110. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16111. 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);
  16112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16113. depthTexture._framebuffer = framebuffer;
  16114. depthTexture.baseWidth = width;
  16115. depthTexture.baseHeight = height;
  16116. depthTexture.width = width;
  16117. depthTexture.height = height;
  16118. depthTexture.isReady = true;
  16119. depthTexture.samples = 1;
  16120. depthTexture.generateMipMaps = generateMipMaps;
  16121. depthTexture.samplingMode = gl.NEAREST;
  16122. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16123. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16124. textures.push(depthTexture);
  16125. this._internalTexturesCache.push(depthTexture);
  16126. }
  16127. gl.drawBuffers(attachments);
  16128. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16129. this.bindUnboundFramebuffer(null);
  16130. this.resetTextureCache();
  16131. return textures;
  16132. };
  16133. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16134. if (samples === void 0) { samples = 1; }
  16135. var depthStencilBuffer = null;
  16136. var gl = this._gl;
  16137. // Create the depth/stencil buffer
  16138. if (generateStencilBuffer) {
  16139. depthStencilBuffer = gl.createRenderbuffer();
  16140. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16141. if (samples > 1) {
  16142. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16143. }
  16144. else {
  16145. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16146. }
  16147. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16148. }
  16149. else if (generateDepthBuffer) {
  16150. depthStencilBuffer = gl.createRenderbuffer();
  16151. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16152. if (samples > 1) {
  16153. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16154. }
  16155. else {
  16156. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16157. }
  16158. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16159. }
  16160. return depthStencilBuffer;
  16161. };
  16162. /**
  16163. * Updates the sample count of a render target texture
  16164. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16165. * @param texture defines the texture to update
  16166. * @param samples defines the sample count to set
  16167. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16168. */
  16169. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16170. if (this.webGLVersion < 2 || !texture) {
  16171. return 1;
  16172. }
  16173. if (texture.samples === samples) {
  16174. return samples;
  16175. }
  16176. var gl = this._gl;
  16177. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16178. // Dispose previous render buffers
  16179. if (texture._depthStencilBuffer) {
  16180. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16181. texture._depthStencilBuffer = null;
  16182. }
  16183. if (texture._MSAAFramebuffer) {
  16184. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16185. texture._MSAAFramebuffer = null;
  16186. }
  16187. if (texture._MSAARenderBuffer) {
  16188. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16189. texture._MSAARenderBuffer = null;
  16190. }
  16191. if (samples > 1) {
  16192. var framebuffer = gl.createFramebuffer();
  16193. if (!framebuffer) {
  16194. throw new Error("Unable to create multi sampled framebuffer");
  16195. }
  16196. texture._MSAAFramebuffer = framebuffer;
  16197. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16198. var colorRenderbuffer = gl.createRenderbuffer();
  16199. if (!colorRenderbuffer) {
  16200. throw new Error("Unable to create multi sampled framebuffer");
  16201. }
  16202. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16203. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16204. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16205. texture._MSAARenderBuffer = colorRenderbuffer;
  16206. }
  16207. else {
  16208. this.bindUnboundFramebuffer(texture._framebuffer);
  16209. }
  16210. texture.samples = samples;
  16211. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16212. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16213. this.bindUnboundFramebuffer(null);
  16214. return samples;
  16215. };
  16216. /**
  16217. * Update the sample count for a given multiple render target texture
  16218. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16219. * @param textures defines the textures to update
  16220. * @param samples defines the sample count to set
  16221. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16222. */
  16223. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16224. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16225. return 1;
  16226. }
  16227. if (textures[0].samples === samples) {
  16228. return samples;
  16229. }
  16230. var gl = this._gl;
  16231. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16232. // Dispose previous render buffers
  16233. if (textures[0]._depthStencilBuffer) {
  16234. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16235. textures[0]._depthStencilBuffer = null;
  16236. }
  16237. if (textures[0]._MSAAFramebuffer) {
  16238. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16239. textures[0]._MSAAFramebuffer = null;
  16240. }
  16241. for (var i = 0; i < textures.length; i++) {
  16242. if (textures[i]._MSAARenderBuffer) {
  16243. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16244. textures[i]._MSAARenderBuffer = null;
  16245. }
  16246. }
  16247. if (samples > 1) {
  16248. var framebuffer = gl.createFramebuffer();
  16249. if (!framebuffer) {
  16250. throw new Error("Unable to create multi sampled framebuffer");
  16251. }
  16252. this.bindUnboundFramebuffer(framebuffer);
  16253. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16254. var attachments = [];
  16255. for (var i = 0; i < textures.length; i++) {
  16256. var texture = textures[i];
  16257. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16258. var colorRenderbuffer = gl.createRenderbuffer();
  16259. if (!colorRenderbuffer) {
  16260. throw new Error("Unable to create multi sampled framebuffer");
  16261. }
  16262. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16263. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16264. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16265. texture._MSAAFramebuffer = framebuffer;
  16266. texture._MSAARenderBuffer = colorRenderbuffer;
  16267. texture.samples = samples;
  16268. texture._depthStencilBuffer = depthStencilBuffer;
  16269. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16270. attachments.push(attachment);
  16271. }
  16272. gl.drawBuffers(attachments);
  16273. }
  16274. else {
  16275. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16276. }
  16277. this.bindUnboundFramebuffer(null);
  16278. return samples;
  16279. };
  16280. /** @hidden */
  16281. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16282. if (faceIndex === void 0) { faceIndex = 0; }
  16283. if (lod === void 0) { lod = 0; }
  16284. var gl = this._gl;
  16285. var target = gl.TEXTURE_2D;
  16286. if (texture.isCube) {
  16287. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16288. }
  16289. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16290. };
  16291. /** @hidden */
  16292. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16293. if (faceIndex === void 0) { faceIndex = 0; }
  16294. if (lod === void 0) { lod = 0; }
  16295. var gl = this._gl;
  16296. var textureType = this._getWebGLTextureType(texture.type);
  16297. var format = this._getInternalFormat(texture.format);
  16298. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16299. this._unpackFlipY(texture.invertY);
  16300. var target = gl.TEXTURE_2D;
  16301. if (texture.isCube) {
  16302. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16303. }
  16304. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16305. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16306. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16307. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16308. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16309. };
  16310. /** @hidden */
  16311. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16312. if (faceIndex === void 0) { faceIndex = 0; }
  16313. if (lod === void 0) { lod = 0; }
  16314. var gl = this._gl;
  16315. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16316. this._bindTextureDirectly(bindTarget, texture, true);
  16317. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16318. this._bindTextureDirectly(bindTarget, null, true);
  16319. };
  16320. /** @hidden */
  16321. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16322. if (faceIndex === void 0) { faceIndex = 0; }
  16323. if (lod === void 0) { lod = 0; }
  16324. var gl = this._gl;
  16325. var textureType = this._getWebGLTextureType(texture.type);
  16326. var format = this._getInternalFormat(texture.format);
  16327. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16328. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16329. this._bindTextureDirectly(bindTarget, texture, true);
  16330. this._unpackFlipY(texture.invertY);
  16331. var target = gl.TEXTURE_2D;
  16332. if (texture.isCube) {
  16333. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16334. }
  16335. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16336. this._bindTextureDirectly(bindTarget, null, true);
  16337. };
  16338. /**
  16339. * Creates a new render target cube texture
  16340. * @param size defines the size of the texture
  16341. * @param options defines the options used to create the texture
  16342. * @returns a new render target cube texture stored in an InternalTexture
  16343. */
  16344. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16345. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16346. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16347. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16348. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16349. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16350. }
  16351. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16352. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16353. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16354. }
  16355. var gl = this._gl;
  16356. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16357. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16358. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16359. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16360. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16361. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16362. }
  16363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16364. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16365. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16367. for (var face = 0; face < 6; face++) {
  16368. 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);
  16369. }
  16370. // Create the framebuffer
  16371. var framebuffer = gl.createFramebuffer();
  16372. this.bindUnboundFramebuffer(framebuffer);
  16373. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16374. // MipMaps
  16375. if (fullOptions.generateMipMaps) {
  16376. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16377. }
  16378. // Unbind
  16379. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16380. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16381. this.bindUnboundFramebuffer(null);
  16382. texture._framebuffer = framebuffer;
  16383. texture.width = size;
  16384. texture.height = size;
  16385. texture.isReady = true;
  16386. texture.isCube = true;
  16387. texture.samples = 1;
  16388. texture.generateMipMaps = fullOptions.generateMipMaps;
  16389. texture.samplingMode = fullOptions.samplingMode;
  16390. texture.type = fullOptions.type;
  16391. texture.format = fullOptions.format;
  16392. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16393. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16394. this._internalTexturesCache.push(texture);
  16395. return texture;
  16396. };
  16397. /**
  16398. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16399. * @param rootUrl defines the url where the file to load is located
  16400. * @param scene defines the current scene
  16401. * @param lodScale defines scale to apply to the mip map selection
  16402. * @param lodOffset defines offset to apply to the mip map selection
  16403. * @param onLoad defines an optional callback raised when the texture is loaded
  16404. * @param onError defines an optional callback raised if there is an issue to load the texture
  16405. * @param format defines the format of the data
  16406. * @param forcedExtension defines the extension to use to pick the right loader
  16407. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16408. * @returns the cube texture as an InternalTexture
  16409. */
  16410. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16411. var _this = this;
  16412. if (onLoad === void 0) { onLoad = null; }
  16413. if (onError === void 0) { onError = null; }
  16414. if (forcedExtension === void 0) { forcedExtension = null; }
  16415. if (createPolynomials === void 0) { createPolynomials = true; }
  16416. var callback = function (loadData) {
  16417. if (!loadData) {
  16418. if (onLoad) {
  16419. onLoad(null);
  16420. }
  16421. return;
  16422. }
  16423. var texture = loadData.texture;
  16424. if (!createPolynomials) {
  16425. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16426. }
  16427. else if (loadData.info.sphericalPolynomial) {
  16428. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16429. }
  16430. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16431. if (_this._caps.textureLOD) {
  16432. // Do not add extra process if texture lod is supported.
  16433. if (onLoad) {
  16434. onLoad(texture);
  16435. }
  16436. return;
  16437. }
  16438. var mipSlices = 3;
  16439. var gl = _this._gl;
  16440. var width = loadData.width;
  16441. if (!width) {
  16442. return;
  16443. }
  16444. var textures = [];
  16445. for (var i = 0; i < mipSlices; i++) {
  16446. //compute LOD from even spacing in smoothness (matching shader calculation)
  16447. var smoothness = i / (mipSlices - 1);
  16448. var roughness = 1 - smoothness;
  16449. var minLODIndex = lodOffset; // roughness = 0
  16450. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16451. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16452. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16453. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16454. glTextureFromLod.type = texture.type;
  16455. glTextureFromLod.format = texture.format;
  16456. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16457. glTextureFromLod.height = glTextureFromLod.width;
  16458. glTextureFromLod.isCube = true;
  16459. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16464. if (loadData.isDDS) {
  16465. var info = loadData.info;
  16466. var data = loadData.data;
  16467. _this._unpackFlipY(info.isCompressed);
  16468. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16469. }
  16470. else {
  16471. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16472. }
  16473. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16474. // Wrap in a base texture for easy binding.
  16475. var lodTexture = new BABYLON.BaseTexture(scene);
  16476. lodTexture.isCube = true;
  16477. lodTexture._texture = glTextureFromLod;
  16478. glTextureFromLod.isReady = true;
  16479. textures.push(lodTexture);
  16480. }
  16481. texture._lodTextureHigh = textures[2];
  16482. texture._lodTextureMid = textures[1];
  16483. texture._lodTextureLow = textures[0];
  16484. if (onLoad) {
  16485. onLoad(texture);
  16486. }
  16487. };
  16488. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16489. };
  16490. /**
  16491. * Creates a cube texture
  16492. * @param rootUrl defines the url where the files to load is located
  16493. * @param scene defines the current scene
  16494. * @param files defines the list of files to load (1 per face)
  16495. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16496. * @param onLoad defines an optional callback raised when the texture is loaded
  16497. * @param onError defines an optional callback raised if there is an issue to load the texture
  16498. * @param format defines the format of the data
  16499. * @param forcedExtension defines the extension to use to pick the right loader
  16500. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16501. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16502. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16503. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16504. * @returns the cube texture as an InternalTexture
  16505. */
  16506. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16507. var _this = this;
  16508. if (onLoad === void 0) { onLoad = null; }
  16509. if (onError === void 0) { onError = null; }
  16510. if (forcedExtension === void 0) { forcedExtension = null; }
  16511. if (createPolynomials === void 0) { createPolynomials = false; }
  16512. if (lodScale === void 0) { lodScale = 0; }
  16513. if (lodOffset === void 0) { lodOffset = 0; }
  16514. if (fallback === void 0) { fallback = null; }
  16515. var gl = this._gl;
  16516. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16517. texture.isCube = true;
  16518. texture.url = rootUrl;
  16519. texture.generateMipMaps = !noMipmap;
  16520. texture._lodGenerationScale = lodScale;
  16521. texture._lodGenerationOffset = lodOffset;
  16522. if (!this._doNotHandleContextLost) {
  16523. texture._extension = forcedExtension;
  16524. texture._files = files;
  16525. }
  16526. var lastDot = rootUrl.lastIndexOf('.');
  16527. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16528. var loader = null;
  16529. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16530. var availableLoader = _a[_i];
  16531. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16532. loader = availableLoader;
  16533. break;
  16534. }
  16535. }
  16536. var onInternalError = function (request, exception) {
  16537. if (loader) {
  16538. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16539. if (fallbackUrl) {
  16540. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16541. }
  16542. }
  16543. if (onError && request) {
  16544. onError(request.status + " " + request.statusText, exception);
  16545. }
  16546. };
  16547. if (loader) {
  16548. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16549. var onloaddata = function (data) {
  16550. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16551. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16552. };
  16553. if (files && files.length === 6) {
  16554. if (loader.supportCascades) {
  16555. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16556. }
  16557. else if (onError) {
  16558. onError("Textures type does not support cascades.");
  16559. }
  16560. }
  16561. else {
  16562. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16563. }
  16564. }
  16565. else {
  16566. if (!files) {
  16567. throw new Error("Cannot load cubemap because files were not defined");
  16568. }
  16569. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16570. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16571. var height = width;
  16572. _this._prepareWorkingCanvas();
  16573. if (!_this._workingCanvas || !_this._workingContext) {
  16574. return;
  16575. }
  16576. _this._workingCanvas.width = width;
  16577. _this._workingCanvas.height = height;
  16578. var faces = [
  16579. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16580. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16581. ];
  16582. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16583. _this._unpackFlipY(false);
  16584. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16585. for (var index = 0; index < faces.length; index++) {
  16586. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16587. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16588. }
  16589. if (!noMipmap) {
  16590. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16591. }
  16592. _this._setCubeMapTextureParams(!noMipmap);
  16593. texture.width = width;
  16594. texture.height = height;
  16595. texture.isReady = true;
  16596. if (format) {
  16597. texture.format = format;
  16598. }
  16599. texture.onLoadedObservable.notifyObservers(texture);
  16600. texture.onLoadedObservable.clear();
  16601. if (onLoad) {
  16602. onLoad();
  16603. }
  16604. }, files, onError);
  16605. }
  16606. this._internalTexturesCache.push(texture);
  16607. return texture;
  16608. };
  16609. /**
  16610. * @hidden
  16611. */
  16612. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16613. var gl = this._gl;
  16614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16616. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16617. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16618. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16619. // this.resetTextureCache();
  16620. };
  16621. /**
  16622. * Update a raw cube texture
  16623. * @param texture defines the texture to udpdate
  16624. * @param data defines the data to store
  16625. * @param format defines the data format
  16626. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16627. * @param invertY defines if data must be stored with Y axis inverted
  16628. * @param compression defines the compression used (null by default)
  16629. * @param level defines which level of the texture to update
  16630. */
  16631. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16632. if (compression === void 0) { compression = null; }
  16633. if (level === void 0) { level = 0; }
  16634. texture._bufferViewArray = data;
  16635. texture.format = format;
  16636. texture.type = type;
  16637. texture.invertY = invertY;
  16638. texture._compression = compression;
  16639. var gl = this._gl;
  16640. var textureType = this._getWebGLTextureType(type);
  16641. var internalFormat = this._getInternalFormat(format);
  16642. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16643. var needConversion = false;
  16644. if (internalFormat === gl.RGB) {
  16645. internalFormat = gl.RGBA;
  16646. needConversion = true;
  16647. }
  16648. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16649. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16650. if (texture.width % 4 !== 0) {
  16651. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16652. }
  16653. // Data are known to be in +X +Y +Z -X -Y -Z
  16654. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16655. var faceData = data[faceIndex];
  16656. if (compression) {
  16657. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16658. }
  16659. else {
  16660. if (needConversion) {
  16661. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16662. }
  16663. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16664. }
  16665. }
  16666. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16667. if (isPot && texture.generateMipMaps && level === 0) {
  16668. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16669. }
  16670. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16671. // this.resetTextureCache();
  16672. texture.isReady = true;
  16673. };
  16674. /**
  16675. * Creates a new raw cube texture
  16676. * @param data defines the array of data to use to create each face
  16677. * @param size defines the size of the textures
  16678. * @param format defines the format of the data
  16679. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16680. * @param generateMipMaps defines if the engine should generate the mip levels
  16681. * @param invertY defines if data must be stored with Y axis inverted
  16682. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16683. * @param compression defines the compression used (null by default)
  16684. * @returns the cube texture as an InternalTexture
  16685. */
  16686. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16687. if (compression === void 0) { compression = null; }
  16688. var gl = this._gl;
  16689. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16690. texture.isCube = true;
  16691. texture.format = format;
  16692. texture.type = type;
  16693. if (!this._doNotHandleContextLost) {
  16694. texture._bufferViewArray = data;
  16695. }
  16696. var textureType = this._getWebGLTextureType(type);
  16697. var internalFormat = this._getInternalFormat(format);
  16698. if (internalFormat === gl.RGB) {
  16699. internalFormat = gl.RGBA;
  16700. }
  16701. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16702. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16703. generateMipMaps = false;
  16704. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16705. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16706. }
  16707. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16708. generateMipMaps = false;
  16709. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16710. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16711. }
  16712. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16713. generateMipMaps = false;
  16714. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16715. }
  16716. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16717. generateMipMaps = false;
  16718. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16719. }
  16720. var width = size;
  16721. var height = width;
  16722. texture.width = width;
  16723. texture.height = height;
  16724. // Double check on POT to generate Mips.
  16725. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16726. if (!isPot) {
  16727. generateMipMaps = false;
  16728. }
  16729. // Upload data if needed. The texture won't be ready until then.
  16730. if (data) {
  16731. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16732. }
  16733. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16734. // Filters
  16735. if (data && generateMipMaps) {
  16736. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16737. }
  16738. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16739. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16740. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16741. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16742. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16743. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16744. texture.generateMipMaps = generateMipMaps;
  16745. return texture;
  16746. };
  16747. /**
  16748. * Creates a new raw cube texture from a specified url
  16749. * @param url defines the url where the data is located
  16750. * @param scene defines the current scene
  16751. * @param size defines the size of the textures
  16752. * @param format defines the format of the data
  16753. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16754. * @param noMipmap defines if the engine should avoid generating the mip levels
  16755. * @param callback defines a callback used to extract texture data from loaded data
  16756. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16757. * @param onLoad defines a callback called when texture is loaded
  16758. * @param onError defines a callback called if there is an error
  16759. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16760. * @param invertY defines if data must be stored with Y axis inverted
  16761. * @returns the cube texture as an InternalTexture
  16762. */
  16763. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16764. var _this = this;
  16765. if (onLoad === void 0) { onLoad = null; }
  16766. if (onError === void 0) { onError = null; }
  16767. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16768. if (invertY === void 0) { invertY = false; }
  16769. var gl = this._gl;
  16770. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16771. scene._addPendingData(texture);
  16772. texture.url = url;
  16773. this._internalTexturesCache.push(texture);
  16774. var onerror = function (request, exception) {
  16775. scene._removePendingData(texture);
  16776. if (onError && request) {
  16777. onError(request.status + " " + request.statusText, exception);
  16778. }
  16779. };
  16780. var internalCallback = function (data) {
  16781. var width = texture.width;
  16782. var faceDataArrays = callback(data);
  16783. if (!faceDataArrays) {
  16784. return;
  16785. }
  16786. if (mipmapGenerator) {
  16787. var textureType = _this._getWebGLTextureType(type);
  16788. var internalFormat = _this._getInternalFormat(format);
  16789. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16790. var needConversion = false;
  16791. if (internalFormat === gl.RGB) {
  16792. internalFormat = gl.RGBA;
  16793. needConversion = true;
  16794. }
  16795. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16796. _this._unpackFlipY(false);
  16797. var mipData = mipmapGenerator(faceDataArrays);
  16798. for (var level = 0; level < mipData.length; level++) {
  16799. var mipSize = width >> level;
  16800. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16801. var mipFaceData = mipData[level][faceIndex];
  16802. if (needConversion) {
  16803. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16804. }
  16805. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16806. }
  16807. }
  16808. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16809. }
  16810. else {
  16811. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16812. }
  16813. texture.isReady = true;
  16814. // this.resetTextureCache();
  16815. scene._removePendingData(texture);
  16816. if (onLoad) {
  16817. onLoad();
  16818. }
  16819. };
  16820. this._loadFile(url, function (data) {
  16821. internalCallback(data);
  16822. }, undefined, scene.database, true, onerror);
  16823. return texture;
  16824. };
  16825. /**
  16826. * Update a raw 3D texture
  16827. * @param texture defines the texture to update
  16828. * @param data defines the data to store
  16829. * @param format defines the data format
  16830. * @param invertY defines if data must be stored with Y axis inverted
  16831. * @param compression defines the used compression (can be null)
  16832. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16833. */
  16834. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16835. if (compression === void 0) { compression = null; }
  16836. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16837. var internalType = this._getWebGLTextureType(textureType);
  16838. var internalFormat = this._getInternalFormat(format);
  16839. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16840. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16841. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16842. if (!this._doNotHandleContextLost) {
  16843. texture._bufferView = data;
  16844. texture.format = format;
  16845. texture.invertY = invertY;
  16846. texture._compression = compression;
  16847. }
  16848. if (texture.width % 4 !== 0) {
  16849. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16850. }
  16851. if (compression && data) {
  16852. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16853. }
  16854. else {
  16855. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16856. }
  16857. if (texture.generateMipMaps) {
  16858. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16859. }
  16860. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16861. // this.resetTextureCache();
  16862. texture.isReady = true;
  16863. };
  16864. /**
  16865. * Creates a new raw 3D texture
  16866. * @param data defines the data used to create the texture
  16867. * @param width defines the width of the texture
  16868. * @param height defines the height of the texture
  16869. * @param depth defines the depth of the texture
  16870. * @param format defines the format of the texture
  16871. * @param generateMipMaps defines if the engine must generate mip levels
  16872. * @param invertY defines if data must be stored with Y axis inverted
  16873. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16874. * @param compression defines the compressed used (can be null)
  16875. * @param textureType defines the compressed used (can be null)
  16876. * @returns a new raw 3D texture (stored in an InternalTexture)
  16877. */
  16878. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16879. if (compression === void 0) { compression = null; }
  16880. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16881. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16882. texture.baseWidth = width;
  16883. texture.baseHeight = height;
  16884. texture.baseDepth = depth;
  16885. texture.width = width;
  16886. texture.height = height;
  16887. texture.depth = depth;
  16888. texture.format = format;
  16889. texture.type = textureType;
  16890. texture.generateMipMaps = generateMipMaps;
  16891. texture.samplingMode = samplingMode;
  16892. texture.is3D = true;
  16893. if (!this._doNotHandleContextLost) {
  16894. texture._bufferView = data;
  16895. }
  16896. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16897. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16898. // Filters
  16899. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16900. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16901. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16902. if (generateMipMaps) {
  16903. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16904. }
  16905. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16906. this._internalTexturesCache.push(texture);
  16907. return texture;
  16908. };
  16909. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16910. var gl = this._gl;
  16911. if (!gl) {
  16912. return;
  16913. }
  16914. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16915. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16916. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16917. if (!noMipmap && !isCompressed) {
  16918. gl.generateMipmap(gl.TEXTURE_2D);
  16919. }
  16920. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16921. // this.resetTextureCache();
  16922. if (scene) {
  16923. scene._removePendingData(texture);
  16924. }
  16925. texture.onLoadedObservable.notifyObservers(texture);
  16926. texture.onLoadedObservable.clear();
  16927. };
  16928. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16929. var _this = this;
  16930. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16931. var maxTextureSize = this.getCaps().maxTextureSize;
  16932. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16933. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16934. var gl = this._gl;
  16935. if (!gl) {
  16936. return;
  16937. }
  16938. if (!texture._webGLTexture) {
  16939. // this.resetTextureCache();
  16940. if (scene) {
  16941. scene._removePendingData(texture);
  16942. }
  16943. return;
  16944. }
  16945. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16946. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16947. texture.baseWidth = width;
  16948. texture.baseHeight = height;
  16949. texture.width = potWidth;
  16950. texture.height = potHeight;
  16951. texture.isReady = true;
  16952. if (processFunction(potWidth, potHeight, function () {
  16953. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16954. })) {
  16955. // Returning as texture needs extra async steps
  16956. return;
  16957. }
  16958. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16959. };
  16960. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16961. // Create new RGBA data container.
  16962. var rgbaData;
  16963. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16964. rgbaData = new Float32Array(width * height * 4);
  16965. }
  16966. else {
  16967. rgbaData = new Uint32Array(width * height * 4);
  16968. }
  16969. // Convert each pixel.
  16970. for (var x = 0; x < width; x++) {
  16971. for (var y = 0; y < height; y++) {
  16972. var index = (y * width + x) * 3;
  16973. var newIndex = (y * width + x) * 4;
  16974. // Map Old Value to new value.
  16975. rgbaData[newIndex + 0] = rgbData[index + 0];
  16976. rgbaData[newIndex + 1] = rgbData[index + 1];
  16977. rgbaData[newIndex + 2] = rgbData[index + 2];
  16978. // Add fully opaque alpha channel.
  16979. rgbaData[newIndex + 3] = 1;
  16980. }
  16981. }
  16982. return rgbaData;
  16983. };
  16984. /** @hidden */
  16985. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16986. var gl = this._gl;
  16987. if (texture._framebuffer) {
  16988. gl.deleteFramebuffer(texture._framebuffer);
  16989. texture._framebuffer = null;
  16990. }
  16991. if (texture._depthStencilBuffer) {
  16992. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16993. texture._depthStencilBuffer = null;
  16994. }
  16995. if (texture._MSAAFramebuffer) {
  16996. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16997. texture._MSAAFramebuffer = null;
  16998. }
  16999. if (texture._MSAARenderBuffer) {
  17000. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17001. texture._MSAARenderBuffer = null;
  17002. }
  17003. };
  17004. /** @hidden */
  17005. Engine.prototype._releaseTexture = function (texture) {
  17006. var gl = this._gl;
  17007. this._releaseFramebufferObjects(texture);
  17008. gl.deleteTexture(texture._webGLTexture);
  17009. // Unbind channels
  17010. this.unbindAllTextures();
  17011. var index = this._internalTexturesCache.indexOf(texture);
  17012. if (index !== -1) {
  17013. this._internalTexturesCache.splice(index, 1);
  17014. }
  17015. // Integrated fixed lod samplers.
  17016. if (texture._lodTextureHigh) {
  17017. texture._lodTextureHigh.dispose();
  17018. }
  17019. if (texture._lodTextureMid) {
  17020. texture._lodTextureMid.dispose();
  17021. }
  17022. if (texture._lodTextureLow) {
  17023. texture._lodTextureLow.dispose();
  17024. }
  17025. // Set output texture of post process to null if the texture has been released/disposed
  17026. this.scenes.forEach(function (scene) {
  17027. scene.postProcesses.forEach(function (postProcess) {
  17028. if (postProcess._outputTexture == texture) {
  17029. postProcess._outputTexture = null;
  17030. }
  17031. });
  17032. scene.cameras.forEach(function (camera) {
  17033. camera._postProcesses.forEach(function (postProcess) {
  17034. if (postProcess) {
  17035. if (postProcess._outputTexture == texture) {
  17036. postProcess._outputTexture = null;
  17037. }
  17038. }
  17039. });
  17040. });
  17041. });
  17042. };
  17043. Engine.prototype.setProgram = function (program) {
  17044. if (this._currentProgram !== program) {
  17045. this._gl.useProgram(program);
  17046. this._currentProgram = program;
  17047. }
  17048. };
  17049. /**
  17050. * Binds an effect to the webGL context
  17051. * @param effect defines the effect to bind
  17052. */
  17053. Engine.prototype.bindSamplers = function (effect) {
  17054. this.setProgram(effect.getProgram());
  17055. var samplers = effect.getSamplers();
  17056. for (var index = 0; index < samplers.length; index++) {
  17057. var uniform = effect.getUniform(samplers[index]);
  17058. if (uniform) {
  17059. this._boundUniforms[index] = uniform;
  17060. }
  17061. }
  17062. this._currentEffect = null;
  17063. };
  17064. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17065. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17066. return;
  17067. }
  17068. // Remove
  17069. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17070. // Bind last to it
  17071. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17072. // Bind to dummy
  17073. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17074. };
  17075. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17076. if (!internalTexture) {
  17077. return -1;
  17078. }
  17079. internalTexture._initialSlot = channel;
  17080. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17081. if (channel !== internalTexture._designatedSlot) {
  17082. this._textureCollisions.addCount(1, false);
  17083. }
  17084. }
  17085. else {
  17086. if (channel !== internalTexture._designatedSlot) {
  17087. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17088. return internalTexture._designatedSlot;
  17089. }
  17090. else {
  17091. // No slot for this texture, let's pick a new one (if we find a free slot)
  17092. if (this._nextFreeTextureSlots.length) {
  17093. return this._nextFreeTextureSlots[0];
  17094. }
  17095. // We need to recycle the oldest bound texture, sorry.
  17096. this._textureCollisions.addCount(1, false);
  17097. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17098. }
  17099. }
  17100. }
  17101. return channel;
  17102. };
  17103. Engine.prototype._linkTrackers = function (previous, next) {
  17104. previous.next = next;
  17105. next.previous = previous;
  17106. };
  17107. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17108. var currentSlot = internalTexture._designatedSlot;
  17109. if (currentSlot === -1) {
  17110. return -1;
  17111. }
  17112. internalTexture._designatedSlot = -1;
  17113. if (this.disableTextureBindingOptimization) {
  17114. return -1;
  17115. }
  17116. // Remove from bound list
  17117. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17118. // Free the slot
  17119. this._boundTexturesCache[currentSlot] = null;
  17120. this._nextFreeTextureSlots.push(currentSlot);
  17121. return currentSlot;
  17122. };
  17123. Engine.prototype._activateCurrentTexture = function () {
  17124. if (this._currentTextureChannel !== this._activeChannel) {
  17125. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17126. this._currentTextureChannel = this._activeChannel;
  17127. }
  17128. };
  17129. /** @hidden */
  17130. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17131. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17132. if (force === void 0) { force = false; }
  17133. var wasPreviouslyBound = false;
  17134. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17135. this._activeChannel = texture._designatedSlot;
  17136. }
  17137. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17138. var isTextureForRendering = texture && texture._initialSlot > -1;
  17139. if (currentTextureBound !== texture || force) {
  17140. if (currentTextureBound) {
  17141. this._removeDesignatedSlot(currentTextureBound);
  17142. }
  17143. this._activateCurrentTexture();
  17144. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17145. this._boundTexturesCache[this._activeChannel] = texture;
  17146. if (texture) {
  17147. if (!this.disableTextureBindingOptimization) {
  17148. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17149. if (slotIndex > -1) {
  17150. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17151. }
  17152. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17153. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17154. }
  17155. texture._designatedSlot = this._activeChannel;
  17156. }
  17157. }
  17158. else if (forTextureDataUpdate) {
  17159. wasPreviouslyBound = true;
  17160. this._activateCurrentTexture();
  17161. }
  17162. if (isTextureForRendering && !forTextureDataUpdate) {
  17163. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17164. }
  17165. return wasPreviouslyBound;
  17166. };
  17167. /** @hidden */
  17168. Engine.prototype._bindTexture = function (channel, texture) {
  17169. if (channel < 0) {
  17170. return;
  17171. }
  17172. if (texture) {
  17173. channel = this._getCorrectTextureChannel(channel, texture);
  17174. }
  17175. this._activeChannel = channel;
  17176. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17177. };
  17178. /**
  17179. * Sets a texture to the webGL context from a postprocess
  17180. * @param channel defines the channel to use
  17181. * @param postProcess defines the source postprocess
  17182. */
  17183. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17184. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17185. };
  17186. /**
  17187. * Binds the output of the passed in post process to the texture channel specified
  17188. * @param channel The channel the texture should be bound to
  17189. * @param postProcess The post process which's output should be bound
  17190. */
  17191. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17192. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17193. };
  17194. /**
  17195. * Unbind all textures from the webGL context
  17196. */
  17197. Engine.prototype.unbindAllTextures = function () {
  17198. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17199. this._activeChannel = channel;
  17200. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17201. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17202. if (this.webGLVersion > 1) {
  17203. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17204. }
  17205. }
  17206. };
  17207. /**
  17208. * Sets a texture to the according uniform.
  17209. * @param channel The texture channel
  17210. * @param uniform The uniform to set
  17211. * @param texture The texture to apply
  17212. */
  17213. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17214. if (channel < 0) {
  17215. return;
  17216. }
  17217. if (uniform) {
  17218. this._boundUniforms[channel] = uniform;
  17219. }
  17220. this._setTexture(channel, texture);
  17221. };
  17222. /**
  17223. * Sets a depth stencil texture from a render target to the according uniform.
  17224. * @param channel The texture channel
  17225. * @param uniform The uniform to set
  17226. * @param texture The render target texture containing the depth stencil texture to apply
  17227. */
  17228. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17229. if (channel < 0) {
  17230. return;
  17231. }
  17232. if (uniform) {
  17233. this._boundUniforms[channel] = uniform;
  17234. }
  17235. if (!texture || !texture.depthStencilTexture) {
  17236. this._setTexture(channel, null);
  17237. }
  17238. else {
  17239. this._setTexture(channel, texture, false, true);
  17240. }
  17241. };
  17242. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17243. var uniform = this._boundUniforms[sourceSlot];
  17244. if (uniform._currentState === destination) {
  17245. return;
  17246. }
  17247. this._gl.uniform1i(uniform, destination);
  17248. uniform._currentState = destination;
  17249. };
  17250. Engine.prototype._getTextureWrapMode = function (mode) {
  17251. switch (mode) {
  17252. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17253. return this._gl.REPEAT;
  17254. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17255. return this._gl.CLAMP_TO_EDGE;
  17256. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17257. return this._gl.MIRRORED_REPEAT;
  17258. }
  17259. return this._gl.REPEAT;
  17260. };
  17261. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17262. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17263. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17264. // Not ready?
  17265. if (!texture) {
  17266. if (this._boundTexturesCache[channel] != null) {
  17267. this._activeChannel = channel;
  17268. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17269. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17270. if (this.webGLVersion > 1) {
  17271. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17272. }
  17273. }
  17274. return false;
  17275. }
  17276. // Video
  17277. if (texture.video) {
  17278. this._activeChannel = channel;
  17279. texture.update();
  17280. }
  17281. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17282. texture.delayLoad();
  17283. return false;
  17284. }
  17285. var internalTexture;
  17286. if (depthStencilTexture) {
  17287. internalTexture = texture.depthStencilTexture;
  17288. }
  17289. else if (texture.isReady()) {
  17290. internalTexture = texture.getInternalTexture();
  17291. }
  17292. else if (texture.isCube) {
  17293. internalTexture = this.emptyCubeTexture;
  17294. }
  17295. else if (texture.is3D) {
  17296. internalTexture = this.emptyTexture3D;
  17297. }
  17298. else {
  17299. internalTexture = this.emptyTexture;
  17300. }
  17301. if (!isPartOfTextureArray) {
  17302. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17303. }
  17304. var needToBind = true;
  17305. if (this._boundTexturesCache[channel] === internalTexture) {
  17306. this._moveBoundTextureOnTop(internalTexture);
  17307. if (!isPartOfTextureArray) {
  17308. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17309. }
  17310. needToBind = false;
  17311. }
  17312. this._activeChannel = channel;
  17313. if (internalTexture && internalTexture.is3D) {
  17314. if (needToBind) {
  17315. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17316. }
  17317. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17318. internalTexture._cachedWrapU = texture.wrapU;
  17319. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17320. }
  17321. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17322. internalTexture._cachedWrapV = texture.wrapV;
  17323. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17324. }
  17325. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17326. internalTexture._cachedWrapR = texture.wrapR;
  17327. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17328. }
  17329. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17330. }
  17331. else if (internalTexture && internalTexture.isCube) {
  17332. if (needToBind) {
  17333. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17334. }
  17335. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17336. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17337. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17338. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17339. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17340. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17341. }
  17342. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17343. }
  17344. else {
  17345. if (needToBind) {
  17346. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17347. }
  17348. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17349. internalTexture._cachedWrapU = texture.wrapU;
  17350. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17351. }
  17352. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17353. internalTexture._cachedWrapV = texture.wrapV;
  17354. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17355. }
  17356. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17357. }
  17358. return true;
  17359. };
  17360. /**
  17361. * Sets an array of texture to the webGL context
  17362. * @param channel defines the channel where the texture array must be set
  17363. * @param uniform defines the associated uniform location
  17364. * @param textures defines the array of textures to bind
  17365. */
  17366. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17367. if (channel < 0 || !uniform) {
  17368. return;
  17369. }
  17370. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17371. this._textureUnits = new Int32Array(textures.length);
  17372. }
  17373. for (var i = 0; i < textures.length; i++) {
  17374. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17375. }
  17376. this._gl.uniform1iv(uniform, this._textureUnits);
  17377. for (var index = 0; index < textures.length; index++) {
  17378. this._setTexture(this._textureUnits[index], textures[index], true);
  17379. }
  17380. };
  17381. /** @hidden */
  17382. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17383. var internalTexture = texture.getInternalTexture();
  17384. if (!internalTexture) {
  17385. return;
  17386. }
  17387. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17388. var value = texture.anisotropicFilteringLevel;
  17389. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17390. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17391. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17392. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17393. }
  17394. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17395. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17396. internalTexture._cachedAnisotropicFilteringLevel = value;
  17397. }
  17398. };
  17399. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17400. this._bindTextureDirectly(target, texture, true, true);
  17401. this._gl.texParameterf(target, parameter, value);
  17402. };
  17403. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17404. if (texture) {
  17405. this._bindTextureDirectly(target, texture, true, true);
  17406. }
  17407. this._gl.texParameteri(target, parameter, value);
  17408. };
  17409. /**
  17410. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17411. * @param x defines the x coordinate of the rectangle where pixels must be read
  17412. * @param y defines the y coordinate of the rectangle where pixels must be read
  17413. * @param width defines the width of the rectangle where pixels must be read
  17414. * @param height defines the height of the rectangle where pixels must be read
  17415. * @returns a Uint8Array containing RGBA colors
  17416. */
  17417. Engine.prototype.readPixels = function (x, y, width, height) {
  17418. var data = new Uint8Array(height * width * 4);
  17419. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17420. return data;
  17421. };
  17422. /**
  17423. * Add an externaly attached data from its key.
  17424. * This method call will fail and return false, if such key already exists.
  17425. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17426. * @param key the unique key that identifies the data
  17427. * @param data the data object to associate to the key for this Engine instance
  17428. * @return true if no such key were already present and the data was added successfully, false otherwise
  17429. */
  17430. Engine.prototype.addExternalData = function (key, data) {
  17431. if (!this._externalData) {
  17432. this._externalData = new BABYLON.StringDictionary();
  17433. }
  17434. return this._externalData.add(key, data);
  17435. };
  17436. /**
  17437. * Get an externaly attached data from its key
  17438. * @param key the unique key that identifies the data
  17439. * @return the associated data, if present (can be null), or undefined if not present
  17440. */
  17441. Engine.prototype.getExternalData = function (key) {
  17442. if (!this._externalData) {
  17443. this._externalData = new BABYLON.StringDictionary();
  17444. }
  17445. return this._externalData.get(key);
  17446. };
  17447. /**
  17448. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17449. * @param key the unique key that identifies the data
  17450. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17451. * @return the associated data, can be null if the factory returned null.
  17452. */
  17453. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17454. if (!this._externalData) {
  17455. this._externalData = new BABYLON.StringDictionary();
  17456. }
  17457. return this._externalData.getOrAddWithFactory(key, factory);
  17458. };
  17459. /**
  17460. * Remove an externaly attached data from the Engine instance
  17461. * @param key the unique key that identifies the data
  17462. * @return true if the data was successfully removed, false if it doesn't exist
  17463. */
  17464. Engine.prototype.removeExternalData = function (key) {
  17465. if (!this._externalData) {
  17466. this._externalData = new BABYLON.StringDictionary();
  17467. }
  17468. return this._externalData.remove(key);
  17469. };
  17470. /**
  17471. * Unbind all vertex attributes from the webGL context
  17472. */
  17473. Engine.prototype.unbindAllAttributes = function () {
  17474. if (this._mustWipeVertexAttributes) {
  17475. this._mustWipeVertexAttributes = false;
  17476. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17477. this._gl.disableVertexAttribArray(i);
  17478. this._vertexAttribArraysEnabled[i] = false;
  17479. this._currentBufferPointers[i].active = false;
  17480. }
  17481. return;
  17482. }
  17483. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17484. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17485. continue;
  17486. }
  17487. this._gl.disableVertexAttribArray(i);
  17488. this._vertexAttribArraysEnabled[i] = false;
  17489. this._currentBufferPointers[i].active = false;
  17490. }
  17491. };
  17492. /**
  17493. * 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
  17494. */
  17495. Engine.prototype.releaseEffects = function () {
  17496. for (var name in this._compiledEffects) {
  17497. this._deleteProgram(this._compiledEffects[name]._program);
  17498. }
  17499. this._compiledEffects = {};
  17500. };
  17501. /**
  17502. * Dispose and release all associated resources
  17503. */
  17504. Engine.prototype.dispose = function () {
  17505. this.hideLoadingUI();
  17506. this.stopRenderLoop();
  17507. // Release postProcesses
  17508. while (this.postProcesses.length) {
  17509. this.postProcesses[0].dispose();
  17510. }
  17511. // Empty texture
  17512. if (this._emptyTexture) {
  17513. this._releaseTexture(this._emptyTexture);
  17514. this._emptyTexture = null;
  17515. }
  17516. if (this._emptyCubeTexture) {
  17517. this._releaseTexture(this._emptyCubeTexture);
  17518. this._emptyCubeTexture = null;
  17519. }
  17520. // Rescale PP
  17521. if (this._rescalePostProcess) {
  17522. this._rescalePostProcess.dispose();
  17523. }
  17524. // Release scenes
  17525. while (this.scenes.length) {
  17526. this.scenes[0].dispose();
  17527. }
  17528. // Release audio engine
  17529. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17530. Engine.audioEngine.dispose();
  17531. }
  17532. // Release effects
  17533. this.releaseEffects();
  17534. // Unbind
  17535. this.unbindAllAttributes();
  17536. this._boundUniforms = [];
  17537. if (this._dummyFramebuffer) {
  17538. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17539. }
  17540. //WebVR
  17541. this.disableVR();
  17542. // Events
  17543. if (BABYLON.Tools.IsWindowObjectExist()) {
  17544. window.removeEventListener("blur", this._onBlur);
  17545. window.removeEventListener("focus", this._onFocus);
  17546. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17547. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17548. if (this._renderingCanvas) {
  17549. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17550. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17551. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17552. if (!this._doNotHandleContextLost) {
  17553. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17554. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17555. }
  17556. }
  17557. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17558. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17559. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17560. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17561. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17562. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17563. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17564. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17565. if (this._onVrDisplayConnect) {
  17566. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17567. if (this._onVrDisplayDisconnect) {
  17568. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17569. }
  17570. if (this._onVrDisplayPresentChange) {
  17571. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17572. }
  17573. this._onVrDisplayConnect = null;
  17574. this._onVrDisplayDisconnect = null;
  17575. }
  17576. }
  17577. // Remove from Instances
  17578. var index = Engine.Instances.indexOf(this);
  17579. if (index >= 0) {
  17580. Engine.Instances.splice(index, 1);
  17581. }
  17582. this._workingCanvas = null;
  17583. this._workingContext = null;
  17584. this._currentBufferPointers = [];
  17585. this._renderingCanvas = null;
  17586. this._currentProgram = null;
  17587. this._bindedRenderFunction = null;
  17588. this.onResizeObservable.clear();
  17589. this.onCanvasBlurObservable.clear();
  17590. this.onCanvasFocusObservable.clear();
  17591. this.onCanvasPointerOutObservable.clear();
  17592. this.onBeginFrameObservable.clear();
  17593. this.onEndFrameObservable.clear();
  17594. BABYLON.Effect.ResetCache();
  17595. // Abort active requests
  17596. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17597. var request = _a[_i];
  17598. request.abort();
  17599. }
  17600. };
  17601. // Loading screen
  17602. /**
  17603. * Display the loading screen
  17604. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17605. */
  17606. Engine.prototype.displayLoadingUI = function () {
  17607. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17608. return;
  17609. }
  17610. var loadingScreen = this.loadingScreen;
  17611. if (loadingScreen) {
  17612. loadingScreen.displayLoadingUI();
  17613. }
  17614. };
  17615. /**
  17616. * Hide the loading screen
  17617. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17618. */
  17619. Engine.prototype.hideLoadingUI = function () {
  17620. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17621. return;
  17622. }
  17623. var loadingScreen = this.loadingScreen;
  17624. if (loadingScreen) {
  17625. loadingScreen.hideLoadingUI();
  17626. }
  17627. };
  17628. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17629. /**
  17630. * Gets the current loading screen object
  17631. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17632. */
  17633. get: function () {
  17634. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  17635. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17636. }
  17637. return this._loadingScreen;
  17638. },
  17639. /**
  17640. * Sets the current loading screen object
  17641. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17642. */
  17643. set: function (loadingScreen) {
  17644. this._loadingScreen = loadingScreen;
  17645. },
  17646. enumerable: true,
  17647. configurable: true
  17648. });
  17649. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17650. /**
  17651. * Sets the current loading screen text
  17652. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17653. */
  17654. set: function (text) {
  17655. this.loadingScreen.loadingUIText = text;
  17656. },
  17657. enumerable: true,
  17658. configurable: true
  17659. });
  17660. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17661. /**
  17662. * Sets the current loading screen background color
  17663. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17664. */
  17665. set: function (color) {
  17666. this.loadingScreen.loadingUIBackgroundColor = color;
  17667. },
  17668. enumerable: true,
  17669. configurable: true
  17670. });
  17671. /**
  17672. * Attach a new callback raised when context lost event is fired
  17673. * @param callback defines the callback to call
  17674. */
  17675. Engine.prototype.attachContextLostEvent = function (callback) {
  17676. if (this._renderingCanvas) {
  17677. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17678. }
  17679. };
  17680. /**
  17681. * Attach a new callback raised when context restored event is fired
  17682. * @param callback defines the callback to call
  17683. */
  17684. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17685. if (this._renderingCanvas) {
  17686. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17687. }
  17688. };
  17689. /**
  17690. * Gets the source code of the vertex shader associated with a specific webGL program
  17691. * @param program defines the program to use
  17692. * @returns a string containing the source code of the vertex shader associated with the program
  17693. */
  17694. Engine.prototype.getVertexShaderSource = function (program) {
  17695. var shaders = this._gl.getAttachedShaders(program);
  17696. if (!shaders) {
  17697. return null;
  17698. }
  17699. return this._gl.getShaderSource(shaders[0]);
  17700. };
  17701. /**
  17702. * Gets the source code of the fragment shader associated with a specific webGL program
  17703. * @param program defines the program to use
  17704. * @returns a string containing the source code of the fragment shader associated with the program
  17705. */
  17706. Engine.prototype.getFragmentShaderSource = function (program) {
  17707. var shaders = this._gl.getAttachedShaders(program);
  17708. if (!shaders) {
  17709. return null;
  17710. }
  17711. return this._gl.getShaderSource(shaders[1]);
  17712. };
  17713. /**
  17714. * Get the current error code of the webGL context
  17715. * @returns the error code
  17716. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17717. */
  17718. Engine.prototype.getError = function () {
  17719. return this._gl.getError();
  17720. };
  17721. // FPS
  17722. /**
  17723. * Gets the current framerate
  17724. * @returns a number representing the framerate
  17725. */
  17726. Engine.prototype.getFps = function () {
  17727. return this._fps;
  17728. };
  17729. /**
  17730. * Gets the time spent between current and previous frame
  17731. * @returns a number representing the delta time in ms
  17732. */
  17733. Engine.prototype.getDeltaTime = function () {
  17734. return this._deltaTime;
  17735. };
  17736. Engine.prototype._measureFps = function () {
  17737. this._performanceMonitor.sampleFrame();
  17738. this._fps = this._performanceMonitor.averageFPS;
  17739. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17740. };
  17741. /** @hidden */
  17742. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17743. if (faceIndex === void 0) { faceIndex = -1; }
  17744. if (level === void 0) { level = 0; }
  17745. if (buffer === void 0) { buffer = null; }
  17746. var gl = this._gl;
  17747. if (!this._dummyFramebuffer) {
  17748. var dummy = gl.createFramebuffer();
  17749. if (!dummy) {
  17750. throw new Error("Unable to create dummy framebuffer");
  17751. }
  17752. this._dummyFramebuffer = dummy;
  17753. }
  17754. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17755. if (faceIndex > -1) {
  17756. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17757. }
  17758. else {
  17759. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17760. }
  17761. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17762. switch (readType) {
  17763. case gl.UNSIGNED_BYTE:
  17764. if (!buffer) {
  17765. buffer = new Uint8Array(4 * width * height);
  17766. }
  17767. readType = gl.UNSIGNED_BYTE;
  17768. break;
  17769. default:
  17770. if (!buffer) {
  17771. buffer = new Float32Array(4 * width * height);
  17772. }
  17773. readType = gl.FLOAT;
  17774. break;
  17775. }
  17776. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17777. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17778. return buffer;
  17779. };
  17780. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17781. if (this._webGLVersion > 1) {
  17782. return this._caps.colorBufferFloat;
  17783. }
  17784. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17785. };
  17786. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17787. if (this._webGLVersion > 1) {
  17788. return this._caps.colorBufferFloat;
  17789. }
  17790. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17791. };
  17792. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17793. Engine.prototype._canRenderToFramebuffer = function (type) {
  17794. var gl = this._gl;
  17795. //clear existing errors
  17796. while (gl.getError() !== gl.NO_ERROR) { }
  17797. var successful = true;
  17798. var texture = gl.createTexture();
  17799. gl.bindTexture(gl.TEXTURE_2D, texture);
  17800. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17801. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17802. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17803. var fb = gl.createFramebuffer();
  17804. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17805. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17806. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17807. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17808. successful = successful && (gl.getError() === gl.NO_ERROR);
  17809. //try render by clearing frame buffer's color buffer
  17810. if (successful) {
  17811. gl.clear(gl.COLOR_BUFFER_BIT);
  17812. successful = successful && (gl.getError() === gl.NO_ERROR);
  17813. }
  17814. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17815. if (successful) {
  17816. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17817. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17818. var readFormat = gl.RGBA;
  17819. var readType = gl.UNSIGNED_BYTE;
  17820. var buffer = new Uint8Array(4);
  17821. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17822. successful = successful && (gl.getError() === gl.NO_ERROR);
  17823. }
  17824. //clean up
  17825. gl.deleteTexture(texture);
  17826. gl.deleteFramebuffer(fb);
  17827. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17828. //clear accumulated errors
  17829. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17830. return successful;
  17831. };
  17832. /** @hidden */
  17833. Engine.prototype._getWebGLTextureType = function (type) {
  17834. if (this._webGLVersion === 1) {
  17835. switch (type) {
  17836. case Engine.TEXTURETYPE_FLOAT:
  17837. return this._gl.FLOAT;
  17838. case Engine.TEXTURETYPE_HALF_FLOAT:
  17839. return this._gl.HALF_FLOAT_OES;
  17840. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17841. return this._gl.UNSIGNED_BYTE;
  17842. }
  17843. return this._gl.UNSIGNED_BYTE;
  17844. }
  17845. switch (type) {
  17846. case Engine.TEXTURETYPE_BYTE:
  17847. return this._gl.BYTE;
  17848. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17849. return this._gl.UNSIGNED_BYTE;
  17850. case Engine.TEXTURETYPE_SHORT:
  17851. return this._gl.SHORT;
  17852. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17853. return this._gl.UNSIGNED_SHORT;
  17854. case Engine.TEXTURETYPE_INT:
  17855. return this._gl.INT;
  17856. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17857. return this._gl.UNSIGNED_INT;
  17858. case Engine.TEXTURETYPE_FLOAT:
  17859. return this._gl.FLOAT;
  17860. case Engine.TEXTURETYPE_HALF_FLOAT:
  17861. return this._gl.HALF_FLOAT;
  17862. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17863. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17864. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17865. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17866. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17867. return this._gl.UNSIGNED_SHORT_5_6_5;
  17868. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17869. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17870. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17871. return this._gl.UNSIGNED_INT_24_8;
  17872. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17873. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17874. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17875. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17876. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17877. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17878. }
  17879. return this._gl.UNSIGNED_BYTE;
  17880. };
  17881. Engine.prototype._getInternalFormat = function (format) {
  17882. var internalFormat = this._gl.RGBA;
  17883. switch (format) {
  17884. case Engine.TEXTUREFORMAT_ALPHA:
  17885. internalFormat = this._gl.ALPHA;
  17886. break;
  17887. case Engine.TEXTUREFORMAT_LUMINANCE:
  17888. internalFormat = this._gl.LUMINANCE;
  17889. break;
  17890. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17891. internalFormat = this._gl.LUMINANCE_ALPHA;
  17892. break;
  17893. case Engine.TEXTUREFORMAT_RED:
  17894. internalFormat = this._gl.RED;
  17895. break;
  17896. case Engine.TEXTUREFORMAT_RG:
  17897. internalFormat = this._gl.RG;
  17898. break;
  17899. case Engine.TEXTUREFORMAT_RGB:
  17900. internalFormat = this._gl.RGB;
  17901. break;
  17902. case Engine.TEXTUREFORMAT_RGBA:
  17903. internalFormat = this._gl.RGBA;
  17904. break;
  17905. }
  17906. if (this._webGLVersion > 1) {
  17907. switch (format) {
  17908. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17909. internalFormat = this._gl.RED_INTEGER;
  17910. break;
  17911. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17912. internalFormat = this._gl.RG_INTEGER;
  17913. break;
  17914. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17915. internalFormat = this._gl.RGB_INTEGER;
  17916. break;
  17917. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17918. internalFormat = this._gl.RGBA_INTEGER;
  17919. break;
  17920. }
  17921. }
  17922. return internalFormat;
  17923. };
  17924. /** @hidden */
  17925. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17926. if (this._webGLVersion === 1) {
  17927. if (format !== undefined) {
  17928. switch (format) {
  17929. case Engine.TEXTUREFORMAT_ALPHA:
  17930. return this._gl.ALPHA;
  17931. case Engine.TEXTUREFORMAT_LUMINANCE:
  17932. return this._gl.LUMINANCE;
  17933. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17934. return this._gl.LUMINANCE_ALPHA;
  17935. }
  17936. }
  17937. return this._gl.RGBA;
  17938. }
  17939. switch (type) {
  17940. case Engine.TEXTURETYPE_BYTE:
  17941. switch (format) {
  17942. case Engine.TEXTUREFORMAT_RED:
  17943. return this._gl.R8_SNORM;
  17944. case Engine.TEXTUREFORMAT_RG:
  17945. return this._gl.RG8_SNORM;
  17946. case Engine.TEXTUREFORMAT_RGB:
  17947. return this._gl.RGB8_SNORM;
  17948. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17949. return this._gl.R8I;
  17950. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17951. return this._gl.RG8I;
  17952. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17953. return this._gl.RGB8I;
  17954. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17955. return this._gl.RGBA8I;
  17956. default:
  17957. return this._gl.RGBA8_SNORM;
  17958. }
  17959. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17960. switch (format) {
  17961. case Engine.TEXTUREFORMAT_RED:
  17962. return this._gl.R8;
  17963. case Engine.TEXTUREFORMAT_RG:
  17964. return this._gl.RG8;
  17965. case Engine.TEXTUREFORMAT_RGB:
  17966. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17967. case Engine.TEXTUREFORMAT_RGBA:
  17968. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17969. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17970. return this._gl.R8UI;
  17971. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17972. return this._gl.RG8UI;
  17973. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17974. return this._gl.RGB8UI;
  17975. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17976. return this._gl.RGBA8UI;
  17977. default:
  17978. return this._gl.RGBA8;
  17979. }
  17980. case Engine.TEXTURETYPE_SHORT:
  17981. switch (format) {
  17982. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17983. return this._gl.R16I;
  17984. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17985. return this._gl.RG16I;
  17986. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17987. return this._gl.RGB16I;
  17988. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17989. return this._gl.RGBA16I;
  17990. default:
  17991. return this._gl.RGBA16I;
  17992. }
  17993. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17994. switch (format) {
  17995. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17996. return this._gl.R16UI;
  17997. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17998. return this._gl.RG16UI;
  17999. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18000. return this._gl.RGB16UI;
  18001. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18002. return this._gl.RGBA16UI;
  18003. default:
  18004. return this._gl.RGBA16UI;
  18005. }
  18006. case Engine.TEXTURETYPE_INT:
  18007. switch (format) {
  18008. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18009. return this._gl.R32I;
  18010. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18011. return this._gl.RG32I;
  18012. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18013. return this._gl.RGB32I;
  18014. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18015. return this._gl.RGBA32I;
  18016. default:
  18017. return this._gl.RGBA32I;
  18018. }
  18019. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18020. switch (format) {
  18021. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18022. return this._gl.R32UI;
  18023. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18024. return this._gl.RG32UI;
  18025. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18026. return this._gl.RGB32UI;
  18027. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18028. return this._gl.RGBA32UI;
  18029. default:
  18030. return this._gl.RGBA32UI;
  18031. }
  18032. case Engine.TEXTURETYPE_FLOAT:
  18033. switch (format) {
  18034. case Engine.TEXTUREFORMAT_RED:
  18035. return this._gl.R32F; // By default. Other possibility is R16F.
  18036. case Engine.TEXTUREFORMAT_RG:
  18037. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18038. case Engine.TEXTUREFORMAT_RGB:
  18039. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18040. case Engine.TEXTUREFORMAT_RGBA:
  18041. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18042. default:
  18043. return this._gl.RGBA32F;
  18044. }
  18045. case Engine.TEXTURETYPE_HALF_FLOAT:
  18046. switch (format) {
  18047. case Engine.TEXTUREFORMAT_RED:
  18048. return this._gl.R16F;
  18049. case Engine.TEXTUREFORMAT_RG:
  18050. return this._gl.RG16F;
  18051. case Engine.TEXTUREFORMAT_RGB:
  18052. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18053. case Engine.TEXTUREFORMAT_RGBA:
  18054. return this._gl.RGBA16F;
  18055. default:
  18056. return this._gl.RGBA16F;
  18057. }
  18058. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18059. return this._gl.RGB565;
  18060. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18061. return this._gl.R11F_G11F_B10F;
  18062. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18063. return this._gl.RGB9_E5;
  18064. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18065. return this._gl.RGBA4;
  18066. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18067. return this._gl.RGB5_A1;
  18068. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18069. switch (format) {
  18070. case Engine.TEXTUREFORMAT_RGBA:
  18071. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18072. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18073. return this._gl.RGB10_A2UI;
  18074. default:
  18075. return this._gl.RGB10_A2;
  18076. }
  18077. }
  18078. return this._gl.RGBA8;
  18079. };
  18080. /** @hidden */
  18081. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18082. if (type === Engine.TEXTURETYPE_FLOAT) {
  18083. return this._gl.RGBA32F;
  18084. }
  18085. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18086. return this._gl.RGBA16F;
  18087. }
  18088. return this._gl.RGBA8;
  18089. };
  18090. /** @hidden */
  18091. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  18092. var _this = this;
  18093. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  18094. this._activeRequests.push(request);
  18095. request.onCompleteObservable.add(function (request) {
  18096. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18097. });
  18098. return request;
  18099. };
  18100. /** @hidden */
  18101. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  18102. var _this = this;
  18103. return new Promise(function (resolve, reject) {
  18104. _this._loadFile(url, function (data) {
  18105. resolve(data);
  18106. }, undefined, database, useArrayBuffer, function (request, exception) {
  18107. reject(exception);
  18108. });
  18109. });
  18110. };
  18111. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18112. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18113. var onload = function (data) {
  18114. loadedFiles[index] = data;
  18115. loadedFiles._internalCount++;
  18116. if (loadedFiles._internalCount === 6) {
  18117. onfinish(loadedFiles);
  18118. }
  18119. };
  18120. var onerror = function (request, exception) {
  18121. if (onErrorCallBack && request) {
  18122. onErrorCallBack(request.status + " " + request.statusText, exception);
  18123. }
  18124. };
  18125. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18126. };
  18127. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18128. if (onError === void 0) { onError = null; }
  18129. var loadedFiles = [];
  18130. loadedFiles._internalCount = 0;
  18131. for (var index = 0; index < 6; index++) {
  18132. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18133. }
  18134. };
  18135. // Statics
  18136. /**
  18137. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18138. * @returns true if the engine can be created
  18139. * @ignorenaming
  18140. */
  18141. Engine.isSupported = function () {
  18142. try {
  18143. var tempcanvas = document.createElement("canvas");
  18144. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18145. return gl != null && !!window.WebGLRenderingContext;
  18146. }
  18147. catch (e) {
  18148. return false;
  18149. }
  18150. };
  18151. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18152. Engine.ExceptionList = [
  18153. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18154. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18155. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18156. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18157. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18158. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18159. ];
  18160. /** Gets the list of created engines */
  18161. Engine.Instances = new Array();
  18162. /**
  18163. * Hidden
  18164. */
  18165. Engine._TextureLoaders = [];
  18166. // Const statics
  18167. /** Defines that alpha blending is disabled */
  18168. Engine.ALPHA_DISABLE = 0;
  18169. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18170. Engine.ALPHA_ADD = 1;
  18171. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18172. Engine.ALPHA_COMBINE = 2;
  18173. /** Defines that alpha blending to DEST - SRC * DEST */
  18174. Engine.ALPHA_SUBTRACT = 3;
  18175. /** Defines that alpha blending to SRC * DEST */
  18176. Engine.ALPHA_MULTIPLY = 4;
  18177. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18178. Engine.ALPHA_MAXIMIZED = 5;
  18179. /** Defines that alpha blending to SRC + DEST */
  18180. Engine.ALPHA_ONEONE = 6;
  18181. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18182. Engine.ALPHA_PREMULTIPLIED = 7;
  18183. /**
  18184. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18185. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18186. */
  18187. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18188. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18189. Engine.ALPHA_INTERPOLATE = 9;
  18190. /**
  18191. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18192. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18193. */
  18194. Engine.ALPHA_SCREENMODE = 10;
  18195. /** Defines that the ressource is not delayed*/
  18196. Engine.DELAYLOADSTATE_NONE = 0;
  18197. /** Defines that the ressource was successfully delay loaded */
  18198. Engine.DELAYLOADSTATE_LOADED = 1;
  18199. /** Defines that the ressource is currently delay loading */
  18200. Engine.DELAYLOADSTATE_LOADING = 2;
  18201. /** Defines that the ressource is delayed and has not started loading */
  18202. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18203. // Depht or Stencil test Constants.
  18204. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18205. Engine.NEVER = 0x0200;
  18206. /** 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 */
  18207. Engine.ALWAYS = 0x0207;
  18208. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18209. Engine.LESS = 0x0201;
  18210. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18211. Engine.EQUAL = 0x0202;
  18212. /** 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 */
  18213. Engine.LEQUAL = 0x0203;
  18214. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18215. Engine.GREATER = 0x0204;
  18216. /** 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 */
  18217. Engine.GEQUAL = 0x0206;
  18218. /** 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 */
  18219. Engine.NOTEQUAL = 0x0205;
  18220. // Stencil Actions Constants.
  18221. /** Passed to stencilOperation to specify that stencil value must be kept */
  18222. Engine.KEEP = 0x1E00;
  18223. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18224. Engine.REPLACE = 0x1E01;
  18225. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18226. Engine.INCR = 0x1E02;
  18227. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18228. Engine.DECR = 0x1E03;
  18229. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18230. Engine.INVERT = 0x150A;
  18231. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18232. Engine.INCR_WRAP = 0x8507;
  18233. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18234. Engine.DECR_WRAP = 0x8508;
  18235. /** Texture is not repeating outside of 0..1 UVs */
  18236. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18237. /** Texture is repeating outside of 0..1 UVs */
  18238. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18239. /** Texture is repeating and mirrored */
  18240. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18241. /** ALPHA */
  18242. Engine.TEXTUREFORMAT_ALPHA = 0;
  18243. /** LUMINANCE */
  18244. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18245. /** LUMINANCE_ALPHA */
  18246. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18247. /** RGB */
  18248. Engine.TEXTUREFORMAT_RGB = 4;
  18249. /** RGBA */
  18250. Engine.TEXTUREFORMAT_RGBA = 5;
  18251. /** RED */
  18252. Engine.TEXTUREFORMAT_RED = 6;
  18253. /** RED (2nd reference) */
  18254. Engine.TEXTUREFORMAT_R = 6;
  18255. /** RG */
  18256. Engine.TEXTUREFORMAT_RG = 7;
  18257. /** RED_INTEGER */
  18258. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18259. /** RED_INTEGER (2nd reference) */
  18260. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18261. /** RG_INTEGER */
  18262. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18263. /** RGB_INTEGER */
  18264. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18265. /** RGBA_INTEGER */
  18266. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18267. /** UNSIGNED_BYTE */
  18268. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18269. /** UNSIGNED_BYTE (2nd reference) */
  18270. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18271. /** FLOAT */
  18272. Engine.TEXTURETYPE_FLOAT = 1;
  18273. /** HALF_FLOAT */
  18274. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18275. /** BYTE */
  18276. Engine.TEXTURETYPE_BYTE = 3;
  18277. /** SHORT */
  18278. Engine.TEXTURETYPE_SHORT = 4;
  18279. /** UNSIGNED_SHORT */
  18280. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18281. /** INT */
  18282. Engine.TEXTURETYPE_INT = 6;
  18283. /** UNSIGNED_INT */
  18284. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18285. /** UNSIGNED_SHORT_4_4_4_4 */
  18286. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18287. /** UNSIGNED_SHORT_5_5_5_1 */
  18288. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18289. /** UNSIGNED_SHORT_5_6_5 */
  18290. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18291. /** UNSIGNED_INT_2_10_10_10_REV */
  18292. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18293. /** UNSIGNED_INT_24_8 */
  18294. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18295. /** UNSIGNED_INT_10F_11F_11F_REV */
  18296. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18297. /** UNSIGNED_INT_5_9_9_9_REV */
  18298. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18299. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18300. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18301. /** nearest is mag = nearest and min = nearest and mip = linear */
  18302. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18303. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18304. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18305. /** Trilinear is mag = linear and min = linear and mip = linear */
  18306. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18307. /** nearest is mag = nearest and min = nearest and mip = linear */
  18308. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18309. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18310. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18311. /** Trilinear is mag = linear and min = linear and mip = linear */
  18312. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18313. /** mag = nearest and min = nearest and mip = nearest */
  18314. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18315. /** mag = nearest and min = linear and mip = nearest */
  18316. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18317. /** mag = nearest and min = linear and mip = linear */
  18318. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18319. /** mag = nearest and min = linear and mip = none */
  18320. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18321. /** mag = nearest and min = nearest and mip = none */
  18322. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18323. /** mag = linear and min = nearest and mip = nearest */
  18324. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18325. /** mag = linear and min = nearest and mip = linear */
  18326. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18327. /** mag = linear and min = linear and mip = none */
  18328. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18329. /** mag = linear and min = nearest and mip = none */
  18330. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18331. /** Explicit coordinates mode */
  18332. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18333. /** Spherical coordinates mode */
  18334. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18335. /** Planar coordinates mode */
  18336. Engine.TEXTURE_PLANAR_MODE = 2;
  18337. /** Cubic coordinates mode */
  18338. Engine.TEXTURE_CUBIC_MODE = 3;
  18339. /** Projection coordinates mode */
  18340. Engine.TEXTURE_PROJECTION_MODE = 4;
  18341. /** Skybox coordinates mode */
  18342. Engine.TEXTURE_SKYBOX_MODE = 5;
  18343. /** Inverse Cubic coordinates mode */
  18344. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18345. /** Equirectangular coordinates mode */
  18346. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18347. /** Equirectangular Fixed coordinates mode */
  18348. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18349. /** Equirectangular Fixed Mirrored coordinates mode */
  18350. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18351. // Texture rescaling mode
  18352. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18353. Engine.SCALEMODE_FLOOR = 1;
  18354. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18355. Engine.SCALEMODE_NEAREST = 2;
  18356. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18357. Engine.SCALEMODE_CEILING = 3;
  18358. // Updatable statics so stick with vars here
  18359. /**
  18360. * Gets or sets the epsilon value used by collision engine
  18361. */
  18362. Engine.CollisionsEpsilon = 0.001;
  18363. /**
  18364. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18365. */
  18366. Engine.CodeRepository = "src/";
  18367. /**
  18368. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18369. */
  18370. Engine.ShadersRepository = "src/Shaders/";
  18371. return Engine;
  18372. }());
  18373. BABYLON.Engine = Engine;
  18374. })(BABYLON || (BABYLON = {}));
  18375. //# sourceMappingURL=babylon.engine.js.map
  18376. var BABYLON;
  18377. (function (BABYLON) {
  18378. /**
  18379. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18380. */
  18381. var Node = /** @class */ (function () {
  18382. /**
  18383. * Creates a new Node
  18384. * @param name the name and id to be given to this node
  18385. * @param scene the scene this node will be added to
  18386. */
  18387. function Node(name, scene) {
  18388. if (scene === void 0) { scene = null; }
  18389. /**
  18390. * Gets or sets a string used to store user defined state for the node
  18391. */
  18392. this.state = "";
  18393. /**
  18394. * Gets or sets an object used to store user defined information for the node
  18395. */
  18396. this.metadata = null;
  18397. /**
  18398. * Gets or sets a boolean used to define if the node must be serialized
  18399. */
  18400. this.doNotSerialize = false;
  18401. /** @hidden */
  18402. this._isDisposed = false;
  18403. /**
  18404. * Gets a list of Animations associated with the node
  18405. */
  18406. this.animations = new Array();
  18407. this._ranges = {};
  18408. this._isEnabled = true;
  18409. this._isParentEnabled = true;
  18410. this._isReady = true;
  18411. /** @hidden */
  18412. this._currentRenderId = -1;
  18413. this._parentRenderId = -1;
  18414. this._childRenderId = -1;
  18415. /** @hidden */
  18416. this._worldMatrix = BABYLON.Matrix.Identity();
  18417. /** @hidden */
  18418. this._worldMatrixDeterminant = 0;
  18419. /** @hidden */
  18420. this._sceneRootNodesIndex = -1;
  18421. this._animationPropertiesOverride = null;
  18422. /**
  18423. * An event triggered when the mesh is disposed
  18424. */
  18425. this.onDisposeObservable = new BABYLON.Observable();
  18426. // Behaviors
  18427. this._behaviors = new Array();
  18428. this.name = name;
  18429. this.id = name;
  18430. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18431. this.uniqueId = this._scene.getUniqueId();
  18432. this._initCache();
  18433. this.addToSceneRootNodes();
  18434. }
  18435. /**
  18436. * Add a new node constructor
  18437. * @param type defines the type name of the node to construct
  18438. * @param constructorFunc defines the constructor function
  18439. */
  18440. Node.AddNodeConstructor = function (type, constructorFunc) {
  18441. this._NodeConstructors[type] = constructorFunc;
  18442. };
  18443. /**
  18444. * Returns a node constructor based on type name
  18445. * @param type defines the type name
  18446. * @param name defines the new node name
  18447. * @param scene defines the hosting scene
  18448. * @param options defines optional options to transmit to constructors
  18449. * @returns the new constructor or null
  18450. */
  18451. Node.Construct = function (type, name, scene, options) {
  18452. var constructorFunc = this._NodeConstructors[type];
  18453. if (!constructorFunc) {
  18454. return null;
  18455. }
  18456. return constructorFunc(name, scene, options);
  18457. };
  18458. /**
  18459. * Gets a boolean indicating if the node has been disposed
  18460. * @returns true if the node was disposed
  18461. */
  18462. Node.prototype.isDisposed = function () {
  18463. return this._isDisposed;
  18464. };
  18465. Object.defineProperty(Node.prototype, "parent", {
  18466. get: function () {
  18467. return this._parentNode;
  18468. },
  18469. /**
  18470. * Gets or sets the parent of the node
  18471. */
  18472. set: function (parent) {
  18473. if (this._parentNode === parent) {
  18474. return;
  18475. }
  18476. var previousParentNode = this._parentNode;
  18477. // Remove self from list of children of parent
  18478. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18479. var index = this._parentNode._children.indexOf(this);
  18480. if (index !== -1) {
  18481. this._parentNode._children.splice(index, 1);
  18482. }
  18483. if (!parent) {
  18484. this.addToSceneRootNodes();
  18485. }
  18486. }
  18487. // Store new parent
  18488. this._parentNode = parent;
  18489. // Add as child to new parent
  18490. if (this._parentNode) {
  18491. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18492. this._parentNode._children = new Array();
  18493. }
  18494. this._parentNode._children.push(this);
  18495. if (!previousParentNode) {
  18496. this.removeFromSceneRootNodes();
  18497. }
  18498. }
  18499. // Enabled state
  18500. this._syncParentEnabledState();
  18501. },
  18502. enumerable: true,
  18503. configurable: true
  18504. });
  18505. Node.prototype.addToSceneRootNodes = function () {
  18506. if (this._sceneRootNodesIndex === -1) {
  18507. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18508. this._scene.rootNodes.push(this);
  18509. }
  18510. };
  18511. Node.prototype.removeFromSceneRootNodes = function () {
  18512. if (this._sceneRootNodesIndex !== -1) {
  18513. var rootNodes = this._scene.rootNodes;
  18514. var lastIdx = rootNodes.length - 1;
  18515. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18516. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18517. this._scene.rootNodes.pop();
  18518. this._sceneRootNodesIndex = -1;
  18519. }
  18520. };
  18521. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18522. /**
  18523. * Gets or sets the animation properties override
  18524. */
  18525. get: function () {
  18526. if (!this._animationPropertiesOverride) {
  18527. return this._scene.animationPropertiesOverride;
  18528. }
  18529. return this._animationPropertiesOverride;
  18530. },
  18531. set: function (value) {
  18532. this._animationPropertiesOverride = value;
  18533. },
  18534. enumerable: true,
  18535. configurable: true
  18536. });
  18537. /**
  18538. * Gets a string idenfifying the name of the class
  18539. * @returns "Node" string
  18540. */
  18541. Node.prototype.getClassName = function () {
  18542. return "Node";
  18543. };
  18544. Object.defineProperty(Node.prototype, "onDispose", {
  18545. /**
  18546. * Sets a callback that will be raised when the node will be disposed
  18547. */
  18548. set: function (callback) {
  18549. if (this._onDisposeObserver) {
  18550. this.onDisposeObservable.remove(this._onDisposeObserver);
  18551. }
  18552. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18553. },
  18554. enumerable: true,
  18555. configurable: true
  18556. });
  18557. /**
  18558. * Gets the scene of the node
  18559. * @returns a scene
  18560. */
  18561. Node.prototype.getScene = function () {
  18562. return this._scene;
  18563. };
  18564. /**
  18565. * Gets the engine of the node
  18566. * @returns a Engine
  18567. */
  18568. Node.prototype.getEngine = function () {
  18569. return this._scene.getEngine();
  18570. };
  18571. /**
  18572. * Attach a behavior to the node
  18573. * @see http://doc.babylonjs.com/features/behaviour
  18574. * @param behavior defines the behavior to attach
  18575. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18576. * @returns the current Node
  18577. */
  18578. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18579. var _this = this;
  18580. if (attachImmediately === void 0) { attachImmediately = false; }
  18581. var index = this._behaviors.indexOf(behavior);
  18582. if (index !== -1) {
  18583. return this;
  18584. }
  18585. behavior.init();
  18586. if (this._scene.isLoading && !attachImmediately) {
  18587. // We defer the attach when the scene will be loaded
  18588. this._scene.onDataLoadedObservable.addOnce(function () {
  18589. behavior.attach(_this);
  18590. });
  18591. }
  18592. else {
  18593. behavior.attach(this);
  18594. }
  18595. this._behaviors.push(behavior);
  18596. return this;
  18597. };
  18598. /**
  18599. * Remove an attached behavior
  18600. * @see http://doc.babylonjs.com/features/behaviour
  18601. * @param behavior defines the behavior to attach
  18602. * @returns the current Node
  18603. */
  18604. Node.prototype.removeBehavior = function (behavior) {
  18605. var index = this._behaviors.indexOf(behavior);
  18606. if (index === -1) {
  18607. return this;
  18608. }
  18609. this._behaviors[index].detach();
  18610. this._behaviors.splice(index, 1);
  18611. return this;
  18612. };
  18613. Object.defineProperty(Node.prototype, "behaviors", {
  18614. /**
  18615. * Gets the list of attached behaviors
  18616. * @see http://doc.babylonjs.com/features/behaviour
  18617. */
  18618. get: function () {
  18619. return this._behaviors;
  18620. },
  18621. enumerable: true,
  18622. configurable: true
  18623. });
  18624. /**
  18625. * Gets an attached behavior by name
  18626. * @param name defines the name of the behavior to look for
  18627. * @see http://doc.babylonjs.com/features/behaviour
  18628. * @returns null if behavior was not found else the requested behavior
  18629. */
  18630. Node.prototype.getBehaviorByName = function (name) {
  18631. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18632. var behavior = _a[_i];
  18633. if (behavior.name === name) {
  18634. return behavior;
  18635. }
  18636. }
  18637. return null;
  18638. };
  18639. /**
  18640. * Returns the latest update of the World matrix
  18641. * @returns a Matrix
  18642. */
  18643. Node.prototype.getWorldMatrix = function () {
  18644. if (this._currentRenderId !== this._scene.getRenderId()) {
  18645. this.computeWorldMatrix();
  18646. }
  18647. return this._worldMatrix;
  18648. };
  18649. /** @hidden */
  18650. Node.prototype._getWorldMatrixDeterminant = function () {
  18651. return this._worldMatrixDeterminant;
  18652. };
  18653. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18654. /**
  18655. * Returns directly the latest state of the mesh World matrix.
  18656. * A Matrix is returned.
  18657. */
  18658. get: function () {
  18659. return this._worldMatrix;
  18660. },
  18661. enumerable: true,
  18662. configurable: true
  18663. });
  18664. // override it in derived class if you add new variables to the cache
  18665. // and call the parent class method
  18666. /** @hidden */
  18667. Node.prototype._initCache = function () {
  18668. this._cache = {};
  18669. this._cache.parent = undefined;
  18670. };
  18671. /** @hidden */
  18672. Node.prototype.updateCache = function (force) {
  18673. if (!force && this.isSynchronized()) {
  18674. return;
  18675. }
  18676. this._cache.parent = this.parent;
  18677. this._updateCache();
  18678. };
  18679. // override it in derived class if you add new variables to the cache
  18680. // and call the parent class method if !ignoreParentClass
  18681. /** @hidden */
  18682. Node.prototype._updateCache = function (ignoreParentClass) {
  18683. };
  18684. // override it in derived class if you add new variables to the cache
  18685. /** @hidden */
  18686. Node.prototype._isSynchronized = function () {
  18687. return true;
  18688. };
  18689. /** @hidden */
  18690. Node.prototype._markSyncedWithParent = function () {
  18691. if (this._parentNode) {
  18692. this._parentRenderId = this._parentNode._childRenderId;
  18693. }
  18694. };
  18695. /** @hidden */
  18696. Node.prototype.isSynchronizedWithParent = function () {
  18697. if (!this._parentNode) {
  18698. return true;
  18699. }
  18700. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18701. return false;
  18702. }
  18703. return this._parentNode.isSynchronized();
  18704. };
  18705. /** @hidden */
  18706. Node.prototype.isSynchronized = function () {
  18707. if (this._cache.parent != this._parentNode) {
  18708. this._cache.parent = this._parentNode;
  18709. return false;
  18710. }
  18711. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18712. return false;
  18713. }
  18714. return this._isSynchronized();
  18715. };
  18716. /**
  18717. * Is this node ready to be used/rendered
  18718. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18719. * @return true if the node is ready
  18720. */
  18721. Node.prototype.isReady = function (completeCheck) {
  18722. if (completeCheck === void 0) { completeCheck = false; }
  18723. return this._isReady;
  18724. };
  18725. /**
  18726. * Is this node enabled?
  18727. * 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
  18728. * @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
  18729. * @return whether this node (and its parent) is enabled
  18730. */
  18731. Node.prototype.isEnabled = function (checkAncestors) {
  18732. if (checkAncestors === void 0) { checkAncestors = true; }
  18733. if (checkAncestors === false) {
  18734. return this._isEnabled;
  18735. }
  18736. if (!this._isEnabled) {
  18737. return false;
  18738. }
  18739. return this._isParentEnabled;
  18740. };
  18741. /** @hidden */
  18742. Node.prototype._syncParentEnabledState = function () {
  18743. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18744. if (this._children) {
  18745. this._children.forEach(function (c) {
  18746. c._syncParentEnabledState(); // Force children to update accordingly
  18747. });
  18748. }
  18749. };
  18750. /**
  18751. * Set the enabled state of this node
  18752. * @param value defines the new enabled state
  18753. */
  18754. Node.prototype.setEnabled = function (value) {
  18755. this._isEnabled = value;
  18756. this._syncParentEnabledState();
  18757. };
  18758. /**
  18759. * Is this node a descendant of the given node?
  18760. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18761. * @param ancestor defines the parent node to inspect
  18762. * @returns a boolean indicating if this node is a descendant of the given node
  18763. */
  18764. Node.prototype.isDescendantOf = function (ancestor) {
  18765. if (this.parent) {
  18766. if (this.parent === ancestor) {
  18767. return true;
  18768. }
  18769. return this.parent.isDescendantOf(ancestor);
  18770. }
  18771. return false;
  18772. };
  18773. /** @hidden */
  18774. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18775. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18776. if (!this._children) {
  18777. return;
  18778. }
  18779. for (var index = 0; index < this._children.length; index++) {
  18780. var item = this._children[index];
  18781. if (!predicate || predicate(item)) {
  18782. results.push(item);
  18783. }
  18784. if (!directDescendantsOnly) {
  18785. item._getDescendants(results, false, predicate);
  18786. }
  18787. }
  18788. };
  18789. /**
  18790. * Will return all nodes that have this node as ascendant
  18791. * @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
  18792. * @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
  18793. * @return all children nodes of all types
  18794. */
  18795. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18796. var results = new Array();
  18797. this._getDescendants(results, directDescendantsOnly, predicate);
  18798. return results;
  18799. };
  18800. /**
  18801. * Get all child-meshes of this node
  18802. * @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
  18803. * @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
  18804. * @returns an array of AbstractMesh
  18805. */
  18806. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18807. var results = [];
  18808. this._getDescendants(results, directDescendantsOnly, function (node) {
  18809. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18810. });
  18811. return results;
  18812. };
  18813. /**
  18814. * Get all child-transformNodes of this node
  18815. * @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
  18816. * @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
  18817. * @returns an array of TransformNode
  18818. */
  18819. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18820. var results = [];
  18821. this._getDescendants(results, directDescendantsOnly, function (node) {
  18822. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18823. });
  18824. return results;
  18825. };
  18826. /**
  18827. * Get all direct children of this node
  18828. * @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
  18829. * @returns an array of Node
  18830. */
  18831. Node.prototype.getChildren = function (predicate) {
  18832. return this.getDescendants(true, predicate);
  18833. };
  18834. /** @hidden */
  18835. Node.prototype._setReady = function (state) {
  18836. if (state === this._isReady) {
  18837. return;
  18838. }
  18839. if (!state) {
  18840. this._isReady = false;
  18841. return;
  18842. }
  18843. if (this.onReady) {
  18844. this.onReady(this);
  18845. }
  18846. this._isReady = true;
  18847. };
  18848. /**
  18849. * Get an animation by name
  18850. * @param name defines the name of the animation to look for
  18851. * @returns null if not found else the requested animation
  18852. */
  18853. Node.prototype.getAnimationByName = function (name) {
  18854. for (var i = 0; i < this.animations.length; i++) {
  18855. var animation = this.animations[i];
  18856. if (animation.name === name) {
  18857. return animation;
  18858. }
  18859. }
  18860. return null;
  18861. };
  18862. /**
  18863. * Creates an animation range for this node
  18864. * @param name defines the name of the range
  18865. * @param from defines the starting key
  18866. * @param to defines the end key
  18867. */
  18868. Node.prototype.createAnimationRange = function (name, from, to) {
  18869. // check name not already in use
  18870. if (!this._ranges[name]) {
  18871. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18872. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18873. if (this.animations[i]) {
  18874. this.animations[i].createRange(name, from, to);
  18875. }
  18876. }
  18877. }
  18878. };
  18879. /**
  18880. * Delete a specific animation range
  18881. * @param name defines the name of the range to delete
  18882. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18883. */
  18884. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18885. if (deleteFrames === void 0) { deleteFrames = true; }
  18886. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18887. if (this.animations[i]) {
  18888. this.animations[i].deleteRange(name, deleteFrames);
  18889. }
  18890. }
  18891. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18892. };
  18893. /**
  18894. * Get an animation range by name
  18895. * @param name defines the name of the animation range to look for
  18896. * @returns null if not found else the requested animation range
  18897. */
  18898. Node.prototype.getAnimationRange = function (name) {
  18899. return this._ranges[name];
  18900. };
  18901. /**
  18902. * Will start the animation sequence
  18903. * @param name defines the range frames for animation sequence
  18904. * @param loop defines if the animation should loop (false by default)
  18905. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18906. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18907. * @returns the object created for this animation. If range does not exist, it will return null
  18908. */
  18909. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18910. var range = this.getAnimationRange(name);
  18911. if (!range) {
  18912. return null;
  18913. }
  18914. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18915. };
  18916. /**
  18917. * Serialize animation ranges into a JSON compatible object
  18918. * @returns serialization object
  18919. */
  18920. Node.prototype.serializeAnimationRanges = function () {
  18921. var serializationRanges = [];
  18922. for (var name in this._ranges) {
  18923. var localRange = this._ranges[name];
  18924. if (!localRange) {
  18925. continue;
  18926. }
  18927. var range = {};
  18928. range.name = name;
  18929. range.from = localRange.from;
  18930. range.to = localRange.to;
  18931. serializationRanges.push(range);
  18932. }
  18933. return serializationRanges;
  18934. };
  18935. /**
  18936. * Computes the world matrix of the node
  18937. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18938. * @returns the world matrix
  18939. */
  18940. Node.prototype.computeWorldMatrix = function (force) {
  18941. if (!this._worldMatrix) {
  18942. this._worldMatrix = BABYLON.Matrix.Identity();
  18943. }
  18944. return this._worldMatrix;
  18945. };
  18946. /**
  18947. * Releases resources associated with this node.
  18948. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18949. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18950. */
  18951. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18952. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18953. if (!doNotRecurse) {
  18954. var nodes = this.getDescendants(true);
  18955. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18956. var node = nodes_1[_i];
  18957. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18958. }
  18959. }
  18960. else {
  18961. var transformNodes = this.getChildTransformNodes(true);
  18962. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18963. var transformNode = transformNodes_1[_a];
  18964. transformNode.parent = null;
  18965. transformNode.computeWorldMatrix(true);
  18966. }
  18967. }
  18968. if (!this.parent) {
  18969. this.removeFromSceneRootNodes();
  18970. }
  18971. else {
  18972. this.parent = null;
  18973. }
  18974. // Callback
  18975. this.onDisposeObservable.notifyObservers(this);
  18976. this.onDisposeObservable.clear();
  18977. // Behaviors
  18978. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18979. var behavior = _c[_b];
  18980. behavior.detach();
  18981. }
  18982. this._behaviors = [];
  18983. this._isDisposed = true;
  18984. };
  18985. /**
  18986. * Parse animation range data from a serialization object and store them into a given node
  18987. * @param node defines where to store the animation ranges
  18988. * @param parsedNode defines the serialization object to read data from
  18989. * @param scene defines the hosting scene
  18990. */
  18991. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18992. if (parsedNode.ranges) {
  18993. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18994. var data = parsedNode.ranges[index];
  18995. node.createAnimationRange(data.name, data.from, data.to);
  18996. }
  18997. }
  18998. };
  18999. Node._NodeConstructors = {};
  19000. __decorate([
  19001. BABYLON.serialize()
  19002. ], Node.prototype, "name", void 0);
  19003. __decorate([
  19004. BABYLON.serialize()
  19005. ], Node.prototype, "id", void 0);
  19006. __decorate([
  19007. BABYLON.serialize()
  19008. ], Node.prototype, "uniqueId", void 0);
  19009. __decorate([
  19010. BABYLON.serialize()
  19011. ], Node.prototype, "state", void 0);
  19012. __decorate([
  19013. BABYLON.serialize()
  19014. ], Node.prototype, "metadata", void 0);
  19015. return Node;
  19016. }());
  19017. BABYLON.Node = Node;
  19018. })(BABYLON || (BABYLON = {}));
  19019. //# sourceMappingURL=babylon.node.js.map
  19020. var BABYLON;
  19021. (function (BABYLON) {
  19022. // This matrix is used as a value to reset the bounding box.
  19023. var _identityMatrix = BABYLON.Matrix.Identity();
  19024. /**
  19025. * Class used to store bounding sphere information
  19026. */
  19027. var BoundingSphere = /** @class */ (function () {
  19028. /**
  19029. * Creates a new bounding sphere
  19030. * @param min defines the minimum vector (in local space)
  19031. * @param max defines the maximum vector (in local space)
  19032. */
  19033. function BoundingSphere(min, max) {
  19034. /**
  19035. * Gets the center of the bounding sphere in local space
  19036. */
  19037. this.center = BABYLON.Vector3.Zero();
  19038. /**
  19039. * Gets the center of the bounding sphere in world space
  19040. */
  19041. this.centerWorld = BABYLON.Vector3.Zero();
  19042. /**
  19043. * Gets the minimum vector in local space
  19044. */
  19045. this.minimum = BABYLON.Vector3.Zero();
  19046. /**
  19047. * Gets the maximum vector in local space
  19048. */
  19049. this.maximum = BABYLON.Vector3.Zero();
  19050. this.reConstruct(min, max);
  19051. }
  19052. /**
  19053. * Recreates the entire bounding sphere from scratch
  19054. * @param min defines the new minimum vector (in local space)
  19055. * @param max defines the new maximum vector (in local space)
  19056. */
  19057. BoundingSphere.prototype.reConstruct = function (min, max) {
  19058. this.minimum.copyFrom(min);
  19059. this.maximum.copyFrom(max);
  19060. var distance = BABYLON.Vector3.Distance(min, max);
  19061. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  19062. this.radius = distance * 0.5;
  19063. this.centerWorld.set(0, 0, 0);
  19064. this._update(_identityMatrix);
  19065. };
  19066. /**
  19067. * Scale the current bounding sphere by applying a scale factor
  19068. * @param factor defines the scale factor to apply
  19069. * @returns the current bounding box
  19070. */
  19071. BoundingSphere.prototype.scale = function (factor) {
  19072. var newRadius = this.radius * factor;
  19073. var tempRadiusVector = BABYLON.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
  19074. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
  19075. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
  19076. this.reConstruct(min, max);
  19077. return this;
  19078. };
  19079. // Methods
  19080. /** @hidden */
  19081. BoundingSphere.prototype._update = function (world) {
  19082. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  19083. var tempVector = BABYLON.Tmp.Vector3[0];
  19084. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  19085. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19086. };
  19087. /**
  19088. * Tests if the bounding sphere is intersecting the frustum planes
  19089. * @param frustumPlanes defines the frustum planes to test
  19090. * @returns true if there is an intersection
  19091. */
  19092. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19093. for (var i = 0; i < 6; i++) {
  19094. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
  19095. return false;
  19096. }
  19097. }
  19098. return true;
  19099. };
  19100. /**
  19101. * Tests if a point is inside the bounding sphere
  19102. * @param point defines the point to test
  19103. * @returns true if the point is inside the bounding sphere
  19104. */
  19105. BoundingSphere.prototype.intersectsPoint = function (point) {
  19106. var x = this.centerWorld.x - point.x;
  19107. var y = this.centerWorld.y - point.y;
  19108. var z = this.centerWorld.z - point.z;
  19109. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19110. if (this.radiusWorld < distance) {
  19111. return false;
  19112. }
  19113. return true;
  19114. };
  19115. // Statics
  19116. /**
  19117. * Checks if two sphere intersct
  19118. * @param sphere0 sphere 0
  19119. * @param sphere1 sphere 1
  19120. * @returns true if the speres intersect
  19121. */
  19122. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19123. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  19124. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  19125. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  19126. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19127. if (sphere0.radiusWorld + sphere1.radiusWorld < distance) {
  19128. return false;
  19129. }
  19130. return true;
  19131. };
  19132. return BoundingSphere;
  19133. }());
  19134. BABYLON.BoundingSphere = BoundingSphere;
  19135. })(BABYLON || (BABYLON = {}));
  19136. //# sourceMappingURL=babylon.boundingSphere.js.map
  19137. var BABYLON;
  19138. (function (BABYLON) {
  19139. /**
  19140. * Class used to store bounding box information
  19141. */
  19142. var BoundingBox = /** @class */ (function () {
  19143. /**
  19144. * Creates a new bounding box
  19145. * @param min defines the minimum vector (in local space)
  19146. * @param max defines the maximum vector (in local space)
  19147. */
  19148. function BoundingBox(min, max) {
  19149. /**
  19150. * Gets the 8 vectors representing the bounding box in local space
  19151. */
  19152. 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()];
  19153. /**
  19154. * Gets the center of the bounding box in local space
  19155. */
  19156. this.center = BABYLON.Vector3.Zero();
  19157. /**
  19158. * Gets the center of the bounding box in world space
  19159. */
  19160. this.centerWorld = BABYLON.Vector3.Zero();
  19161. /**
  19162. * Gets the extend size in local space
  19163. */
  19164. this.extendSize = BABYLON.Vector3.Zero();
  19165. /**
  19166. * Gets the extend size in world space
  19167. */
  19168. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19169. /**
  19170. * Gets the OBB (object bounding box) directions
  19171. */
  19172. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19173. /**
  19174. * Gets the 8 vectors representing the bounding box in world space
  19175. */
  19176. 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()];
  19177. /**
  19178. * Gets the minimum vector in world space
  19179. */
  19180. this.minimumWorld = BABYLON.Vector3.Zero();
  19181. /**
  19182. * Gets the maximum vector in world space
  19183. */
  19184. this.maximumWorld = BABYLON.Vector3.Zero();
  19185. /**
  19186. * Gets the minimum vector in local space
  19187. */
  19188. this.minimum = BABYLON.Vector3.Zero();
  19189. /**
  19190. * Gets the maximum vector in local space
  19191. */
  19192. this.maximum = BABYLON.Vector3.Zero();
  19193. this.reConstruct(min, max);
  19194. }
  19195. // Methods
  19196. /**
  19197. * Recreates the entire bounding box from scratch
  19198. * @param min defines the new minimum vector (in local space)
  19199. * @param max defines the new maximum vector (in local space)
  19200. */
  19201. BoundingBox.prototype.reConstruct = function (min, max) {
  19202. this.minimum.copyFrom(min);
  19203. this.maximum.copyFrom(max);
  19204. // Bounding vectors
  19205. this.vectors[0].copyFrom(this.minimum);
  19206. this.vectors[1].copyFrom(this.maximum);
  19207. this.vectors[2].copyFrom(this.minimum);
  19208. this.vectors[3].copyFrom(this.minimum);
  19209. this.vectors[4].copyFrom(this.minimum);
  19210. this.vectors[5].copyFrom(this.maximum);
  19211. this.vectors[6].copyFrom(this.maximum);
  19212. this.vectors[7].copyFrom(this.maximum);
  19213. this.vectors[2].x = this.maximum.x;
  19214. this.vectors[3].y = this.maximum.y;
  19215. this.vectors[4].z = this.maximum.z;
  19216. this.vectors[5].z = this.minimum.z;
  19217. this.vectors[6].x = this.minimum.x;
  19218. this.vectors[7].y = this.minimum.y;
  19219. // OBB
  19220. this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
  19221. this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
  19222. for (var index = 0; index < 3; index++) {
  19223. this.directions[index].copyFromFloats(0, 0, 0);
  19224. }
  19225. // World
  19226. for (var index = 0; index < 8; index++) {
  19227. this.vectorsWorld[index].copyFromFloats(0, 0, 0);
  19228. }
  19229. this.minimumWorld.copyFromFloats(0, 0, 0);
  19230. this.maximumWorld.copyFromFloats(0, 0, 0);
  19231. this.centerWorld.copyFromFloats(0, 0, 0);
  19232. this.extendSizeWorld.copyFromFloats(0, 0, 0);
  19233. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  19234. };
  19235. /**
  19236. * Scale the current bounding box by applying a scale factor
  19237. * @param factor defines the scale factor to apply
  19238. * @returns the current bounding box
  19239. */
  19240. BoundingBox.prototype.scale = function (factor) {
  19241. var diff = BABYLON.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
  19242. var distance = diff.length() * factor;
  19243. diff.normalize();
  19244. var newRadius = diff.scaleInPlace(distance * 0.5);
  19245. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
  19246. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
  19247. this.reConstruct(min, max);
  19248. return this;
  19249. };
  19250. /**
  19251. * Gets the world matrix of the bounding box
  19252. * @returns a matrix
  19253. */
  19254. BoundingBox.prototype.getWorldMatrix = function () {
  19255. return this._worldMatrix;
  19256. };
  19257. /**
  19258. * Sets the world matrix stored in the bounding box
  19259. * @param matrix defines the matrix to store
  19260. * @returns current bounding box
  19261. */
  19262. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19263. this._worldMatrix.copyFrom(matrix);
  19264. return this;
  19265. };
  19266. /** @hidden */
  19267. BoundingBox.prototype._update = function (world) {
  19268. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19269. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19270. for (var index = 0; index < 8; index++) {
  19271. var v = this.vectorsWorld[index];
  19272. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19273. this.minimumWorld.minimizeInPlace(v);
  19274. this.maximumWorld.maximizeInPlace(v);
  19275. }
  19276. // Extend
  19277. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19278. this.extendSizeWorld.scaleInPlace(0.5);
  19279. // OBB
  19280. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19281. this.centerWorld.scaleInPlace(0.5);
  19282. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19283. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19284. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19285. this._worldMatrix = world;
  19286. };
  19287. /**
  19288. * Tests if the bounding box is intersecting the frustum planes
  19289. * @param frustumPlanes defines the frustum planes to test
  19290. * @returns true if there is an intersection
  19291. */
  19292. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19293. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19294. };
  19295. /**
  19296. * Tests if the bounding box is entirely inside the frustum planes
  19297. * @param frustumPlanes defines the frustum planes to test
  19298. * @returns true if there is an inclusion
  19299. */
  19300. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19301. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19302. };
  19303. /**
  19304. * Tests if a point is inside the bounding box
  19305. * @param point defines the point to test
  19306. * @returns true if the point is inside the bounding box
  19307. */
  19308. BoundingBox.prototype.intersectsPoint = function (point) {
  19309. var delta = -BABYLON.Epsilon;
  19310. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x) {
  19311. return false;
  19312. }
  19313. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y) {
  19314. return false;
  19315. }
  19316. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z) {
  19317. return false;
  19318. }
  19319. return true;
  19320. };
  19321. /**
  19322. * Tests if the bounding box intersects with a bounding sphere
  19323. * @param sphere defines the sphere to test
  19324. * @returns true if there is an intersection
  19325. */
  19326. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19327. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19328. };
  19329. /**
  19330. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19331. * @param min defines the min vector to use
  19332. * @param max defines the max vector to use
  19333. * @returns true if there is an intersection
  19334. */
  19335. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19336. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x) {
  19337. return false;
  19338. }
  19339. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y) {
  19340. return false;
  19341. }
  19342. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z) {
  19343. return false;
  19344. }
  19345. return true;
  19346. };
  19347. // Statics
  19348. /**
  19349. * Tests if two bounding boxes are intersections
  19350. * @param box0 defines the first box to test
  19351. * @param box1 defines the second box to test
  19352. * @returns true if there is an intersection
  19353. */
  19354. BoundingBox.Intersects = function (box0, box1) {
  19355. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x) {
  19356. return false;
  19357. }
  19358. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y) {
  19359. return false;
  19360. }
  19361. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z) {
  19362. return false;
  19363. }
  19364. return true;
  19365. };
  19366. /**
  19367. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19368. * @param minPoint defines the minimum vector of the bounding box
  19369. * @param maxPoint defines the maximum vector of the bounding box
  19370. * @param sphereCenter defines the sphere center
  19371. * @param sphereRadius defines the sphere radius
  19372. * @returns true if there is an intersection
  19373. */
  19374. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19375. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19376. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19377. return (num <= (sphereRadius * sphereRadius));
  19378. };
  19379. /**
  19380. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19381. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19382. * @param frustumPlanes defines the frustum planes to test
  19383. * @return true if there is an inclusion
  19384. */
  19385. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19386. for (var p = 0; p < 6; p++) {
  19387. for (var i = 0; i < 8; i++) {
  19388. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19389. return false;
  19390. }
  19391. }
  19392. }
  19393. return true;
  19394. };
  19395. /**
  19396. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19397. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19398. * @param frustumPlanes defines the frustum planes to test
  19399. * @return true if there is an intersection
  19400. */
  19401. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19402. for (var p = 0; p < 6; p++) {
  19403. var inCount = 8;
  19404. for (var i = 0; i < 8; i++) {
  19405. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19406. --inCount;
  19407. }
  19408. else {
  19409. break;
  19410. }
  19411. }
  19412. if (inCount === 0) {
  19413. return false;
  19414. }
  19415. }
  19416. return true;
  19417. };
  19418. return BoundingBox;
  19419. }());
  19420. BABYLON.BoundingBox = BoundingBox;
  19421. })(BABYLON || (BABYLON = {}));
  19422. //# sourceMappingURL=babylon.boundingBox.js.map
  19423. var BABYLON;
  19424. (function (BABYLON) {
  19425. var computeBoxExtents = function (axis, box) {
  19426. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19427. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19428. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19429. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19430. var r = r0 + r1 + r2;
  19431. return {
  19432. min: p - r,
  19433. max: p + r
  19434. };
  19435. };
  19436. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19437. var axisOverlap = function (axis, box0, box1) {
  19438. var result0 = computeBoxExtents(axis, box0);
  19439. var result1 = computeBoxExtents(axis, box1);
  19440. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19441. };
  19442. /**
  19443. * Info for a bounding data of a mesh
  19444. */
  19445. var BoundingInfo = /** @class */ (function () {
  19446. /**
  19447. * Constructs bounding info
  19448. * @param minimum min vector of the bounding box/sphere
  19449. * @param maximum max vector of the bounding box/sphere
  19450. */
  19451. function BoundingInfo(minimum, maximum) {
  19452. this._isLocked = false;
  19453. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19454. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19455. }
  19456. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19457. /**
  19458. * min vector of the bounding box/sphere
  19459. */
  19460. get: function () {
  19461. return this.boundingBox.minimum;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19467. /**
  19468. * max vector of the bounding box/sphere
  19469. */
  19470. get: function () {
  19471. return this.boundingBox.maximum;
  19472. },
  19473. enumerable: true,
  19474. configurable: true
  19475. });
  19476. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19477. /**
  19478. * If the info is locked and won't be updated to avoid perf overhead
  19479. */
  19480. get: function () {
  19481. return this._isLocked;
  19482. },
  19483. set: function (value) {
  19484. this._isLocked = value;
  19485. },
  19486. enumerable: true,
  19487. configurable: true
  19488. });
  19489. // Methods
  19490. /**
  19491. * Updates the boudning sphere and box
  19492. * @param world world matrix to be used to update
  19493. */
  19494. BoundingInfo.prototype.update = function (world) {
  19495. if (this._isLocked) {
  19496. return;
  19497. }
  19498. this.boundingBox._update(world);
  19499. this.boundingSphere._update(world);
  19500. };
  19501. /**
  19502. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19503. * @param center New center of the bounding info
  19504. * @param extend New extend of the bounding info
  19505. * @returns the current bounding info
  19506. */
  19507. BoundingInfo.prototype.centerOn = function (center, extend) {
  19508. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19509. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19510. this.boundingBox.reConstruct(minimum, maximum);
  19511. this.boundingSphere.reConstruct(minimum, maximum);
  19512. return this;
  19513. };
  19514. /**
  19515. * Scale the current bounding info by applying a scale factor
  19516. * @param factor defines the scale factor to apply
  19517. * @returns the current bounding info
  19518. */
  19519. BoundingInfo.prototype.scale = function (factor) {
  19520. this.boundingBox.scale(factor);
  19521. this.boundingSphere.scale(factor);
  19522. return this;
  19523. };
  19524. /**
  19525. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19526. * @param frustumPlanes defines the frustum to test
  19527. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19528. * @returns true if the bounding info is in the frustum planes
  19529. */
  19530. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19531. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19532. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19533. return false;
  19534. }
  19535. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19536. return true;
  19537. }
  19538. return this.boundingBox.isInFrustum(frustumPlanes);
  19539. };
  19540. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19541. /**
  19542. * Gets the world distance between the min and max points of the bounding box
  19543. */
  19544. get: function () {
  19545. var boundingBox = this.boundingBox;
  19546. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19547. return size.length();
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. /**
  19553. * Checks if a cullable object (mesh...) is in the camera frustum
  19554. * Unlike isInFrustum this cheks the full bounding box
  19555. * @param frustumPlanes Camera near/planes
  19556. * @returns true if the object is in frustum otherwise false
  19557. */
  19558. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19559. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19560. };
  19561. /** @hidden */
  19562. BoundingInfo.prototype._checkCollision = function (collider) {
  19563. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19564. };
  19565. /**
  19566. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19567. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19568. * @param point the point to check intersection with
  19569. * @returns if the point intersects
  19570. */
  19571. BoundingInfo.prototype.intersectsPoint = function (point) {
  19572. if (!this.boundingSphere.centerWorld) {
  19573. return false;
  19574. }
  19575. if (!this.boundingSphere.intersectsPoint(point)) {
  19576. return false;
  19577. }
  19578. if (!this.boundingBox.intersectsPoint(point)) {
  19579. return false;
  19580. }
  19581. return true;
  19582. };
  19583. /**
  19584. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19585. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19586. * @param boundingInfo the bounding info to check intersection with
  19587. * @param precise if the intersection should be done using OBB
  19588. * @returns if the bounding info intersects
  19589. */
  19590. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19591. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19592. return false;
  19593. }
  19594. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19595. return false;
  19596. }
  19597. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19598. return false;
  19599. }
  19600. if (!precise) {
  19601. return true;
  19602. }
  19603. var box0 = this.boundingBox;
  19604. var box1 = boundingInfo.boundingBox;
  19605. if (!axisOverlap(box0.directions[0], box0, box1)) {
  19606. return false;
  19607. }
  19608. if (!axisOverlap(box0.directions[1], box0, box1)) {
  19609. return false;
  19610. }
  19611. if (!axisOverlap(box0.directions[2], box0, box1)) {
  19612. return false;
  19613. }
  19614. if (!axisOverlap(box1.directions[0], box0, box1)) {
  19615. return false;
  19616. }
  19617. if (!axisOverlap(box1.directions[1], box0, box1)) {
  19618. return false;
  19619. }
  19620. if (!axisOverlap(box1.directions[2], box0, box1)) {
  19621. return false;
  19622. }
  19623. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  19624. return false;
  19625. }
  19626. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  19627. return false;
  19628. }
  19629. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  19630. return false;
  19631. }
  19632. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  19633. return false;
  19634. }
  19635. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  19636. return false;
  19637. }
  19638. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  19639. return false;
  19640. }
  19641. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  19642. return false;
  19643. }
  19644. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  19645. return false;
  19646. }
  19647. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  19648. return false;
  19649. }
  19650. return true;
  19651. };
  19652. return BoundingInfo;
  19653. }());
  19654. BABYLON.BoundingInfo = BoundingInfo;
  19655. })(BABYLON || (BABYLON = {}));
  19656. //# sourceMappingURL=babylon.boundingInfo.js.map
  19657. var BABYLON;
  19658. (function (BABYLON) {
  19659. /**
  19660. * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
  19661. * @see https://doc.babylonjs.com/how_to/transformnode
  19662. */
  19663. var TransformNode = /** @class */ (function (_super) {
  19664. __extends(TransformNode, _super);
  19665. function TransformNode(name, scene, isPure) {
  19666. if (scene === void 0) { scene = null; }
  19667. if (isPure === void 0) { isPure = true; }
  19668. var _this = _super.call(this, name, scene) || this;
  19669. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19670. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19671. _this._up = new BABYLON.Vector3(0, 1, 0);
  19672. _this._right = new BABYLON.Vector3(1, 0, 0);
  19673. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19674. // Properties
  19675. _this._position = BABYLON.Vector3.Zero();
  19676. _this._rotation = BABYLON.Vector3.Zero();
  19677. _this._scaling = BABYLON.Vector3.One();
  19678. _this._isDirty = false;
  19679. /**
  19680. * Set the billboard mode. Default is 0.
  19681. *
  19682. * | Value | Type | Description |
  19683. * | --- | --- | --- |
  19684. * | 0 | BILLBOARDMODE_NONE | |
  19685. * | 1 | BILLBOARDMODE_X | |
  19686. * | 2 | BILLBOARDMODE_Y | |
  19687. * | 4 | BILLBOARDMODE_Z | |
  19688. * | 7 | BILLBOARDMODE_ALL | |
  19689. *
  19690. */
  19691. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19692. /**
  19693. * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
  19694. */
  19695. _this.scalingDeterminant = 1;
  19696. /**
  19697. * Sets the distance of the object to max, often used by skybox
  19698. */
  19699. _this.infiniteDistance = false;
  19700. /**
  19701. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19702. * By default the system will update normals to compensate
  19703. */
  19704. _this.ignoreNonUniformScaling = false;
  19705. _this._localWorld = BABYLON.Matrix.Zero();
  19706. _this._absolutePosition = BABYLON.Vector3.Zero();
  19707. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19708. _this._postMultiplyPivotMatrix = false;
  19709. _this._isWorldMatrixFrozen = false;
  19710. /**
  19711. * An event triggered after the world matrix is updated
  19712. */
  19713. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19714. _this._nonUniformScaling = false;
  19715. if (isPure) {
  19716. _this.getScene().addTransformNode(_this);
  19717. }
  19718. return _this;
  19719. }
  19720. /**
  19721. * Gets a string identifying the name of the class
  19722. * @returns "TransformNode" string
  19723. */
  19724. TransformNode.prototype.getClassName = function () {
  19725. return "TransformNode";
  19726. };
  19727. Object.defineProperty(TransformNode.prototype, "position", {
  19728. /**
  19729. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19730. */
  19731. get: function () {
  19732. return this._position;
  19733. },
  19734. set: function (newPosition) {
  19735. this._position = newPosition;
  19736. this._isDirty = true;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(TransformNode.prototype, "rotation", {
  19742. /**
  19743. * 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)).
  19744. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19745. */
  19746. get: function () {
  19747. return this._rotation;
  19748. },
  19749. set: function (newRotation) {
  19750. this._rotation = newRotation;
  19751. this._isDirty = true;
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. Object.defineProperty(TransformNode.prototype, "scaling", {
  19757. /**
  19758. * 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)).
  19759. */
  19760. get: function () {
  19761. return this._scaling;
  19762. },
  19763. set: function (newScaling) {
  19764. this._scaling = newScaling;
  19765. this._isDirty = true;
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19771. /**
  19772. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19773. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19774. */
  19775. get: function () {
  19776. return this._rotationQuaternion;
  19777. },
  19778. set: function (quaternion) {
  19779. this._rotationQuaternion = quaternion;
  19780. //reset the rotation vector.
  19781. if (quaternion && this.rotation.length()) {
  19782. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19783. }
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(TransformNode.prototype, "forward", {
  19789. /**
  19790. * The forward direction of that transform in world space.
  19791. */
  19792. get: function () {
  19793. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(TransformNode.prototype, "up", {
  19799. /**
  19800. * The up direction of that transform in world space.
  19801. */
  19802. get: function () {
  19803. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(TransformNode.prototype, "right", {
  19809. /**
  19810. * The right direction of that transform in world space.
  19811. */
  19812. get: function () {
  19813. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. /**
  19819. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19820. * @param matrix the matrix to copy the pose from
  19821. * @returns this TransformNode.
  19822. */
  19823. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19824. this._poseMatrix.copyFrom(matrix);
  19825. return this;
  19826. };
  19827. /**
  19828. * Returns the mesh Pose matrix.
  19829. * @returns the pose matrix
  19830. */
  19831. TransformNode.prototype.getPoseMatrix = function () {
  19832. return this._poseMatrix;
  19833. };
  19834. /** @hidden */
  19835. TransformNode.prototype._isSynchronized = function () {
  19836. if (this._isDirty) {
  19837. return false;
  19838. }
  19839. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19840. return false;
  19841. }
  19842. if (this._cache.pivotMatrixUpdated) {
  19843. return false;
  19844. }
  19845. if (this.infiniteDistance) {
  19846. return false;
  19847. }
  19848. if (!this._cache.position.equals(this._position)) {
  19849. return false;
  19850. }
  19851. if (this._rotationQuaternion) {
  19852. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  19853. return false;
  19854. }
  19855. }
  19856. if (!this._cache.rotation.equals(this._rotation)) {
  19857. return false;
  19858. }
  19859. if (!this._cache.scaling.equals(this._scaling)) {
  19860. return false;
  19861. }
  19862. return true;
  19863. };
  19864. /** @hidden */
  19865. TransformNode.prototype._initCache = function () {
  19866. _super.prototype._initCache.call(this);
  19867. this._cache.localMatrixUpdated = false;
  19868. this._cache.position = BABYLON.Vector3.Zero();
  19869. this._cache.scaling = BABYLON.Vector3.Zero();
  19870. this._cache.rotation = BABYLON.Vector3.Zero();
  19871. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19872. this._cache.billboardMode = -1;
  19873. };
  19874. /**
  19875. * Flag the transform node as dirty (Forcing it to update everything)
  19876. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  19877. * @returns this transform node
  19878. */
  19879. TransformNode.prototype.markAsDirty = function (property) {
  19880. if (property === "rotation") {
  19881. this.rotationQuaternion = null;
  19882. }
  19883. this._currentRenderId = Number.MAX_VALUE;
  19884. this._isDirty = true;
  19885. return this;
  19886. };
  19887. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19888. /**
  19889. * Returns the current mesh absolute position.
  19890. * Returns a Vector3.
  19891. */
  19892. get: function () {
  19893. return this._absolutePosition;
  19894. },
  19895. enumerable: true,
  19896. configurable: true
  19897. });
  19898. /**
  19899. * Sets a new matrix to apply before all other transformation
  19900. * @param matrix defines the transform matrix
  19901. * @returns the current TransformNode
  19902. */
  19903. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19904. return this.setPivotMatrix(matrix, false);
  19905. };
  19906. /**
  19907. * Sets a new pivot matrix to the current node
  19908. * @param matrix defines the new pivot matrix to use
  19909. * @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
  19910. * @returns the current TransformNode
  19911. */
  19912. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19913. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19914. this._pivotMatrix = matrix.clone();
  19915. this._cache.pivotMatrixUpdated = true;
  19916. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19917. if (this._postMultiplyPivotMatrix) {
  19918. if (!this._pivotMatrixInverse) {
  19919. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19920. }
  19921. else {
  19922. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19923. }
  19924. }
  19925. return this;
  19926. };
  19927. /**
  19928. * Returns the mesh pivot matrix.
  19929. * Default : Identity.
  19930. * @returns the matrix
  19931. */
  19932. TransformNode.prototype.getPivotMatrix = function () {
  19933. return this._pivotMatrix;
  19934. };
  19935. /**
  19936. * Prevents the World matrix to be computed any longer.
  19937. * @returns the TransformNode.
  19938. */
  19939. TransformNode.prototype.freezeWorldMatrix = function () {
  19940. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19941. this.computeWorldMatrix(true);
  19942. this._isWorldMatrixFrozen = true;
  19943. return this;
  19944. };
  19945. /**
  19946. * Allows back the World matrix computation.
  19947. * @returns the TransformNode.
  19948. */
  19949. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19950. this._isWorldMatrixFrozen = false;
  19951. this.computeWorldMatrix(true);
  19952. return this;
  19953. };
  19954. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19955. /**
  19956. * True if the World matrix has been frozen.
  19957. */
  19958. get: function () {
  19959. return this._isWorldMatrixFrozen;
  19960. },
  19961. enumerable: true,
  19962. configurable: true
  19963. });
  19964. /**
  19965. * Retuns the mesh absolute position in the World.
  19966. * @returns a Vector3.
  19967. */
  19968. TransformNode.prototype.getAbsolutePosition = function () {
  19969. this.computeWorldMatrix();
  19970. return this._absolutePosition;
  19971. };
  19972. /**
  19973. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19974. * @param absolutePosition the absolute position to set
  19975. * @returns the TransformNode.
  19976. */
  19977. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19978. if (!absolutePosition) {
  19979. return this;
  19980. }
  19981. var absolutePositionX;
  19982. var absolutePositionY;
  19983. var absolutePositionZ;
  19984. if (absolutePosition.x === undefined) {
  19985. if (arguments.length < 3) {
  19986. return this;
  19987. }
  19988. absolutePositionX = arguments[0];
  19989. absolutePositionY = arguments[1];
  19990. absolutePositionZ = arguments[2];
  19991. }
  19992. else {
  19993. absolutePositionX = absolutePosition.x;
  19994. absolutePositionY = absolutePosition.y;
  19995. absolutePositionZ = absolutePosition.z;
  19996. }
  19997. if (this.parent) {
  19998. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19999. invertParentWorldMatrix.invert();
  20000. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  20001. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  20002. }
  20003. else {
  20004. this.position.x = absolutePositionX;
  20005. this.position.y = absolutePositionY;
  20006. this.position.z = absolutePositionZ;
  20007. }
  20008. return this;
  20009. };
  20010. /**
  20011. * Sets the mesh position in its local space.
  20012. * @param vector3 the position to set in localspace
  20013. * @returns the TransformNode.
  20014. */
  20015. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20016. this.computeWorldMatrix();
  20017. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  20018. return this;
  20019. };
  20020. /**
  20021. * Returns the mesh position in the local space from the current World matrix values.
  20022. * @returns a new Vector3.
  20023. */
  20024. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20025. this.computeWorldMatrix();
  20026. var invLocalWorldMatrix = this._localWorld.clone();
  20027. invLocalWorldMatrix.invert();
  20028. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20029. };
  20030. /**
  20031. * Translates the mesh along the passed Vector3 in its local space.
  20032. * @param vector3 the distance to translate in localspace
  20033. * @returns the TransformNode.
  20034. */
  20035. TransformNode.prototype.locallyTranslate = function (vector3) {
  20036. this.computeWorldMatrix(true);
  20037. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  20038. return this;
  20039. };
  20040. /**
  20041. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20042. * @param targetPoint the position (must be in same space as current mesh) to look at
  20043. * @param yawCor optional yaw (y-axis) correction in radians
  20044. * @param pitchCor optional pitch (x-axis) correction in radians
  20045. * @param rollCor optional roll (z-axis) correction in radians
  20046. * @param space the choosen space of the target
  20047. * @returns the TransformNode.
  20048. */
  20049. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20050. if (yawCor === void 0) { yawCor = 0; }
  20051. if (pitchCor === void 0) { pitchCor = 0; }
  20052. if (rollCor === void 0) { rollCor = 0; }
  20053. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20054. var dv = TransformNode._lookAtVectorCache;
  20055. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20056. targetPoint.subtractToRef(pos, dv);
  20057. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  20058. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  20059. var pitch = Math.atan2(dv.y, len);
  20060. if (this.rotationQuaternion) {
  20061. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20062. }
  20063. else {
  20064. this.rotation.x = pitch + pitchCor;
  20065. this.rotation.y = yaw + yawCor;
  20066. this.rotation.z = rollCor;
  20067. }
  20068. return this;
  20069. };
  20070. /**
  20071. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20072. * This Vector3 is expressed in the World space.
  20073. * @param localAxis axis to rotate
  20074. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20075. */
  20076. TransformNode.prototype.getDirection = function (localAxis) {
  20077. var result = BABYLON.Vector3.Zero();
  20078. this.getDirectionToRef(localAxis, result);
  20079. return result;
  20080. };
  20081. /**
  20082. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20083. * localAxis is expressed in the mesh local space.
  20084. * result is computed in the Wordl space from the mesh World matrix.
  20085. * @param localAxis axis to rotate
  20086. * @param result the resulting transformnode
  20087. * @returns this TransformNode.
  20088. */
  20089. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20090. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20091. return this;
  20092. };
  20093. /**
  20094. * Sets a new pivot point to the current node
  20095. * @param point defines the new pivot point to use
  20096. * @param space defines if the point is in world or local space (local by default)
  20097. * @returns the current TransformNode
  20098. */
  20099. TransformNode.prototype.setPivotPoint = function (point, space) {
  20100. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20101. if (this.getScene().getRenderId() == 0) {
  20102. this.computeWorldMatrix(true);
  20103. }
  20104. var wm = this.getWorldMatrix();
  20105. if (space == BABYLON.Space.WORLD) {
  20106. var tmat = BABYLON.Tmp.Matrix[0];
  20107. wm.invertToRef(tmat);
  20108. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20109. }
  20110. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20111. };
  20112. /**
  20113. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20114. * @returns the pivot point
  20115. */
  20116. TransformNode.prototype.getPivotPoint = function () {
  20117. var point = BABYLON.Vector3.Zero();
  20118. this.getPivotPointToRef(point);
  20119. return point;
  20120. };
  20121. /**
  20122. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20123. * @param result the vector3 to store the result
  20124. * @returns this TransformNode.
  20125. */
  20126. TransformNode.prototype.getPivotPointToRef = function (result) {
  20127. result.x = -this._pivotMatrix.m[12];
  20128. result.y = -this._pivotMatrix.m[13];
  20129. result.z = -this._pivotMatrix.m[14];
  20130. return this;
  20131. };
  20132. /**
  20133. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20134. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20135. */
  20136. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20137. var point = BABYLON.Vector3.Zero();
  20138. this.getAbsolutePivotPointToRef(point);
  20139. return point;
  20140. };
  20141. /**
  20142. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20143. * @param result vector3 to store the result
  20144. * @returns this TransformNode.
  20145. */
  20146. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20147. result.x = this._pivotMatrix.m[12];
  20148. result.y = this._pivotMatrix.m[13];
  20149. result.z = this._pivotMatrix.m[14];
  20150. this.getPivotPointToRef(result);
  20151. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20152. return this;
  20153. };
  20154. /**
  20155. * Defines the passed node as the parent of the current node.
  20156. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20157. * @param node the node ot set as the parent
  20158. * @returns this TransformNode.
  20159. */
  20160. TransformNode.prototype.setParent = function (node) {
  20161. if (!node && !this.parent) {
  20162. return this;
  20163. }
  20164. if (!node) {
  20165. var rotation = BABYLON.Tmp.Quaternion[0];
  20166. var position = BABYLON.Tmp.Vector3[0];
  20167. var scale = BABYLON.Tmp.Vector3[1];
  20168. if (this.parent && this.parent.computeWorldMatrix) {
  20169. this.parent.computeWorldMatrix(true);
  20170. }
  20171. this.computeWorldMatrix(true);
  20172. this.getWorldMatrix().decompose(scale, rotation, position);
  20173. if (this.rotationQuaternion) {
  20174. this.rotationQuaternion.copyFrom(rotation);
  20175. }
  20176. else {
  20177. rotation.toEulerAnglesToRef(this.rotation);
  20178. }
  20179. this.scaling.x = scale.x;
  20180. this.scaling.y = scale.y;
  20181. this.scaling.z = scale.z;
  20182. this.position.x = position.x;
  20183. this.position.y = position.y;
  20184. this.position.z = position.z;
  20185. }
  20186. else {
  20187. var rotation = BABYLON.Tmp.Quaternion[0];
  20188. var position = BABYLON.Tmp.Vector3[0];
  20189. var scale = BABYLON.Tmp.Vector3[1];
  20190. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20191. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20192. this.computeWorldMatrix(true);
  20193. node.computeWorldMatrix(true);
  20194. node.getWorldMatrix().invertToRef(invParentMatrix);
  20195. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20196. diffMatrix.decompose(scale, rotation, position);
  20197. if (this.rotationQuaternion) {
  20198. this.rotationQuaternion.copyFrom(rotation);
  20199. }
  20200. else {
  20201. rotation.toEulerAnglesToRef(this.rotation);
  20202. }
  20203. this.position.x = position.x;
  20204. this.position.y = position.y;
  20205. this.position.z = position.z;
  20206. this.scaling.x = scale.x;
  20207. this.scaling.y = scale.y;
  20208. this.scaling.z = scale.z;
  20209. }
  20210. this.parent = node;
  20211. return this;
  20212. };
  20213. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20214. /**
  20215. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20216. */
  20217. get: function () {
  20218. return this._nonUniformScaling;
  20219. },
  20220. enumerable: true,
  20221. configurable: true
  20222. });
  20223. /** @hidden */
  20224. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20225. if (this._nonUniformScaling === value) {
  20226. return false;
  20227. }
  20228. this._nonUniformScaling = value;
  20229. return true;
  20230. };
  20231. /**
  20232. * Attach the current TransformNode to another TransformNode associated with a bone
  20233. * @param bone Bone affecting the TransformNode
  20234. * @param affectedTransformNode TransformNode associated with the bone
  20235. * @returns this object
  20236. */
  20237. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20238. this._transformToBoneReferal = affectedTransformNode;
  20239. this.parent = bone;
  20240. if (bone.getWorldMatrix().determinant() < 0) {
  20241. this.scalingDeterminant *= -1;
  20242. }
  20243. return this;
  20244. };
  20245. /**
  20246. * Detach the transform node if its associated with a bone
  20247. * @returns this object
  20248. */
  20249. TransformNode.prototype.detachFromBone = function () {
  20250. if (!this.parent) {
  20251. return this;
  20252. }
  20253. if (this.parent.getWorldMatrix().determinant() < 0) {
  20254. this.scalingDeterminant *= -1;
  20255. }
  20256. this._transformToBoneReferal = null;
  20257. this.parent = null;
  20258. return this;
  20259. };
  20260. /**
  20261. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20262. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20263. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20264. * The passed axis is also normalized.
  20265. * @param axis the axis to rotate around
  20266. * @param amount the amount to rotate in radians
  20267. * @param space Space to rotate in (Default: local)
  20268. * @returns the TransformNode.
  20269. */
  20270. TransformNode.prototype.rotate = function (axis, amount, space) {
  20271. axis.normalize();
  20272. if (!this.rotationQuaternion) {
  20273. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20274. this.rotation = BABYLON.Vector3.Zero();
  20275. }
  20276. var rotationQuaternion;
  20277. if (!space || space === BABYLON.Space.LOCAL) {
  20278. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20279. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20280. }
  20281. else {
  20282. if (this.parent) {
  20283. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20284. invertParentWorldMatrix.invert();
  20285. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20286. }
  20287. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20288. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20289. }
  20290. return this;
  20291. };
  20292. /**
  20293. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20294. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20295. * The passed axis is also normalized. .
  20296. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20297. * @param point the point to rotate around
  20298. * @param axis the axis to rotate around
  20299. * @param amount the amount to rotate in radians
  20300. * @returns the TransformNode
  20301. */
  20302. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20303. axis.normalize();
  20304. if (!this.rotationQuaternion) {
  20305. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20306. this.rotation.copyFromFloats(0, 0, 0);
  20307. }
  20308. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20309. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20310. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20311. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20312. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20313. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20314. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20315. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20316. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20317. return this;
  20318. };
  20319. /**
  20320. * Translates the mesh along the axis vector for the passed distance in the given space.
  20321. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20322. * @param axis the axis to translate in
  20323. * @param distance the distance to translate
  20324. * @param space Space to rotate in (Default: local)
  20325. * @returns the TransformNode.
  20326. */
  20327. TransformNode.prototype.translate = function (axis, distance, space) {
  20328. var displacementVector = axis.scale(distance);
  20329. if (!space || space === BABYLON.Space.LOCAL) {
  20330. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20331. this.setPositionWithLocalVector(tempV3);
  20332. }
  20333. else {
  20334. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20335. }
  20336. return this;
  20337. };
  20338. /**
  20339. * Adds a rotation step to the mesh current rotation.
  20340. * x, y, z are Euler angles expressed in radians.
  20341. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20342. * This means this rotation is made in the mesh local space only.
  20343. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20344. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20345. * ```javascript
  20346. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20347. * ```
  20348. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20349. * 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.
  20350. * @param x Rotation to add
  20351. * @param y Rotation to add
  20352. * @param z Rotation to add
  20353. * @returns the TransformNode.
  20354. */
  20355. TransformNode.prototype.addRotation = function (x, y, z) {
  20356. var rotationQuaternion;
  20357. if (this.rotationQuaternion) {
  20358. rotationQuaternion = this.rotationQuaternion;
  20359. }
  20360. else {
  20361. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20362. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20363. }
  20364. var accumulation = BABYLON.Tmp.Quaternion[0];
  20365. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20366. rotationQuaternion.multiplyInPlace(accumulation);
  20367. if (!this.rotationQuaternion) {
  20368. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20369. }
  20370. return this;
  20371. };
  20372. /**
  20373. * Computes the world matrix of the node
  20374. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20375. * @returns the world matrix
  20376. */
  20377. TransformNode.prototype.computeWorldMatrix = function (force) {
  20378. if (this._isWorldMatrixFrozen) {
  20379. return this._worldMatrix;
  20380. }
  20381. if (!force && this.isSynchronized()) {
  20382. this._currentRenderId = this.getScene().getRenderId();
  20383. return this._worldMatrix;
  20384. }
  20385. this._updateCache();
  20386. this._cache.position.copyFrom(this.position);
  20387. this._cache.scaling.copyFrom(this.scaling);
  20388. this._cache.pivotMatrixUpdated = false;
  20389. this._cache.billboardMode = this.billboardMode;
  20390. this._currentRenderId = this.getScene().getRenderId();
  20391. this._childRenderId = this.getScene().getRenderId();
  20392. this._isDirty = false;
  20393. // Scaling
  20394. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20395. // Rotation
  20396. //rotate, if quaternion is set and rotation was used
  20397. if (this.rotationQuaternion) {
  20398. var len = this.rotation.length();
  20399. if (len) {
  20400. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20401. this.rotation.copyFromFloats(0, 0, 0);
  20402. }
  20403. }
  20404. if (this.rotationQuaternion) {
  20405. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20406. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20407. }
  20408. else {
  20409. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20410. this._cache.rotation.copyFrom(this.rotation);
  20411. }
  20412. // Translation
  20413. var camera = this.getScene().activeCamera;
  20414. if (this.infiniteDistance && !this.parent && camera) {
  20415. var cameraWorldMatrix = camera.getWorldMatrix();
  20416. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20417. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20418. }
  20419. else {
  20420. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20421. }
  20422. // Composing transformations
  20423. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20424. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20425. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20426. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20427. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20428. // Need to decompose each rotation here
  20429. var currentPosition = BABYLON.Tmp.Vector3[3];
  20430. if (this.parent && this.parent.getWorldMatrix) {
  20431. if (this._transformToBoneReferal) {
  20432. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20433. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20434. }
  20435. else {
  20436. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20437. }
  20438. }
  20439. else {
  20440. currentPosition.copyFrom(this.position);
  20441. }
  20442. currentPosition.subtractInPlace(camera.globalPosition);
  20443. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20444. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20445. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20446. }
  20447. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20448. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20449. }
  20450. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20451. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20452. }
  20453. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20454. }
  20455. else {
  20456. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20457. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20458. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20459. }
  20460. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20461. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20462. }
  20463. // Post multiply inverse of pivotMatrix
  20464. if (this._postMultiplyPivotMatrix) {
  20465. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20466. }
  20467. // Local world
  20468. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20469. // Parent
  20470. if (this.parent && this.parent.getWorldMatrix) {
  20471. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20472. if (this._transformToBoneReferal) {
  20473. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20474. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20475. }
  20476. else {
  20477. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20478. }
  20479. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20480. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20481. this._worldMatrix.copyFrom(this._localWorld);
  20482. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20483. }
  20484. else {
  20485. if (this._transformToBoneReferal) {
  20486. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20487. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20488. }
  20489. else {
  20490. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20491. }
  20492. }
  20493. this._markSyncedWithParent();
  20494. }
  20495. else {
  20496. this._worldMatrix.copyFrom(this._localWorld);
  20497. }
  20498. // Normal matrix
  20499. if (!this.ignoreNonUniformScaling) {
  20500. if (this.scaling.isNonUniform) {
  20501. this._updateNonUniformScalingState(true);
  20502. }
  20503. else if (this.parent && this.parent._nonUniformScaling) {
  20504. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20505. }
  20506. else {
  20507. this._updateNonUniformScalingState(false);
  20508. }
  20509. }
  20510. else {
  20511. this._updateNonUniformScalingState(false);
  20512. }
  20513. this._afterComputeWorldMatrix();
  20514. // Absolute position
  20515. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20516. // Callbacks
  20517. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20518. if (!this._poseMatrix) {
  20519. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20520. }
  20521. // Cache the determinant
  20522. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20523. return this._worldMatrix;
  20524. };
  20525. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20526. };
  20527. /**
  20528. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20529. * @param func callback function to add
  20530. *
  20531. * @returns the TransformNode.
  20532. */
  20533. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20534. this.onAfterWorldMatrixUpdateObservable.add(func);
  20535. return this;
  20536. };
  20537. /**
  20538. * Removes a registered callback function.
  20539. * @param func callback function to remove
  20540. * @returns the TransformNode.
  20541. */
  20542. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20543. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20544. return this;
  20545. };
  20546. /**
  20547. * Clone the current transform node
  20548. * @param name Name of the new clone
  20549. * @param newParent New parent for the clone
  20550. * @param doNotCloneChildren Do not clone children hierarchy
  20551. * @returns the new transform node
  20552. */
  20553. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20554. var _this = this;
  20555. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20556. result.name = name;
  20557. result.id = name;
  20558. if (newParent) {
  20559. result.parent = newParent;
  20560. }
  20561. if (!doNotCloneChildren) {
  20562. // Children
  20563. var directDescendants = this.getDescendants(true);
  20564. for (var index = 0; index < directDescendants.length; index++) {
  20565. var child = directDescendants[index];
  20566. if (child.clone) {
  20567. child.clone(name + "." + child.name, result);
  20568. }
  20569. }
  20570. }
  20571. return result;
  20572. };
  20573. /**
  20574. * Serializes the objects information.
  20575. * @param currentSerializationObject defines the object to serialize in
  20576. * @returns the serialized object
  20577. */
  20578. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20579. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20580. serializationObject.type = this.getClassName();
  20581. // Parent
  20582. if (this.parent) {
  20583. serializationObject.parentId = this.parent.id;
  20584. }
  20585. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20586. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20587. }
  20588. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20589. serializationObject.isEnabled = this.isEnabled();
  20590. // Parent
  20591. if (this.parent) {
  20592. serializationObject.parentId = this.parent.id;
  20593. }
  20594. return serializationObject;
  20595. };
  20596. // Statics
  20597. /**
  20598. * Returns a new TransformNode object parsed from the source provided.
  20599. * @param parsedTransformNode is the source.
  20600. * @param scene the scne the object belongs to
  20601. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20602. * @returns a new TransformNode object parsed from the source provided.
  20603. */
  20604. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20605. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20606. if (BABYLON.Tags) {
  20607. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20608. }
  20609. if (parsedTransformNode.localMatrix) {
  20610. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20611. }
  20612. else if (parsedTransformNode.pivotMatrix) {
  20613. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20614. }
  20615. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20616. // Parent
  20617. if (parsedTransformNode.parentId) {
  20618. transformNode._waitingParentId = parsedTransformNode.parentId;
  20619. }
  20620. return transformNode;
  20621. };
  20622. /**
  20623. * Releases resources associated with this transform node.
  20624. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20625. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20626. */
  20627. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20628. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20629. // Animations
  20630. this.getScene().stopAnimation(this);
  20631. // Remove from scene
  20632. this.getScene().removeTransformNode(this);
  20633. this.onAfterWorldMatrixUpdateObservable.clear();
  20634. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20635. };
  20636. // Statics
  20637. /**
  20638. * Object will not rotate to face the camera
  20639. */
  20640. TransformNode.BILLBOARDMODE_NONE = 0;
  20641. /**
  20642. * Object will rotate to face the camera but only on the x axis
  20643. */
  20644. TransformNode.BILLBOARDMODE_X = 1;
  20645. /**
  20646. * Object will rotate to face the camera but only on the y axis
  20647. */
  20648. TransformNode.BILLBOARDMODE_Y = 2;
  20649. /**
  20650. * Object will rotate to face the camera but only on the z axis
  20651. */
  20652. TransformNode.BILLBOARDMODE_Z = 4;
  20653. /**
  20654. * Object will rotate to face the camera
  20655. */
  20656. TransformNode.BILLBOARDMODE_ALL = 7;
  20657. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20658. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20659. __decorate([
  20660. BABYLON.serializeAsVector3("position")
  20661. ], TransformNode.prototype, "_position", void 0);
  20662. __decorate([
  20663. BABYLON.serializeAsVector3("rotation")
  20664. ], TransformNode.prototype, "_rotation", void 0);
  20665. __decorate([
  20666. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20667. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20668. __decorate([
  20669. BABYLON.serializeAsVector3("scaling")
  20670. ], TransformNode.prototype, "_scaling", void 0);
  20671. __decorate([
  20672. BABYLON.serialize()
  20673. ], TransformNode.prototype, "billboardMode", void 0);
  20674. __decorate([
  20675. BABYLON.serialize()
  20676. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20677. __decorate([
  20678. BABYLON.serialize()
  20679. ], TransformNode.prototype, "infiniteDistance", void 0);
  20680. __decorate([
  20681. BABYLON.serialize()
  20682. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20683. return TransformNode;
  20684. }(BABYLON.Node));
  20685. BABYLON.TransformNode = TransformNode;
  20686. })(BABYLON || (BABYLON = {}));
  20687. //# sourceMappingURL=babylon.transformNode.js.map
  20688. var BABYLON;
  20689. (function (BABYLON) {
  20690. /** @hidden */
  20691. var _FacetDataStorage = /** @class */ (function () {
  20692. function _FacetDataStorage() {
  20693. this.facetNb = 0; // facet number
  20694. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20695. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20696. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20697. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20698. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20699. this.subDiv = {
  20700. max: 1,
  20701. X: 1,
  20702. Y: 1,
  20703. Z: 1
  20704. };
  20705. this.facetDepthSort = false; // is the facet depth sort to be computed
  20706. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20707. }
  20708. return _FacetDataStorage;
  20709. }());
  20710. /**
  20711. * Class used to store all common mesh properties
  20712. */
  20713. var AbstractMesh = /** @class */ (function (_super) {
  20714. __extends(AbstractMesh, _super);
  20715. // Constructor
  20716. /**
  20717. * Creates a new AbstractMesh
  20718. * @param name defines the name of the mesh
  20719. * @param scene defines the hosting scene
  20720. */
  20721. function AbstractMesh(name, scene) {
  20722. if (scene === void 0) { scene = null; }
  20723. var _this = _super.call(this, name, scene, false) || this;
  20724. _this._facetData = new _FacetDataStorage();
  20725. /** Gets ot sets the culling strategy to use to find visible meshes */
  20726. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20727. // Events
  20728. /**
  20729. * An event triggered when this mesh collides with another one
  20730. */
  20731. _this.onCollideObservable = new BABYLON.Observable();
  20732. /**
  20733. * An event triggered when the collision's position changes
  20734. */
  20735. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20736. /**
  20737. * An event triggered when material is changed
  20738. */
  20739. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20740. // Properties
  20741. /**
  20742. * Gets or sets the orientation for POV movement & rotation
  20743. */
  20744. _this.definedFacingForward = true;
  20745. _this._visibility = 1.0;
  20746. /** Gets or sets the alpha index used to sort transparent meshes
  20747. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20748. */
  20749. _this.alphaIndex = Number.MAX_VALUE;
  20750. /**
  20751. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20752. */
  20753. _this.isVisible = true;
  20754. /**
  20755. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20756. */
  20757. _this.isPickable = true;
  20758. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20759. _this.showSubMeshesBoundingBox = false;
  20760. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20761. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20762. */
  20763. _this.isBlocker = false;
  20764. /**
  20765. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20766. */
  20767. _this.enablePointerMoveEvents = false;
  20768. /**
  20769. * Specifies the rendering group id for this mesh (0 by default)
  20770. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20771. */
  20772. _this.renderingGroupId = 0;
  20773. _this._receiveShadows = false;
  20774. /** Defines color to use when rendering outline */
  20775. _this.outlineColor = BABYLON.Color3.Red();
  20776. /** Define width to use when rendering outline */
  20777. _this.outlineWidth = 0.02;
  20778. /** Defines color to use when rendering overlay */
  20779. _this.overlayColor = BABYLON.Color3.Red();
  20780. /** Defines alpha to use when rendering overlay */
  20781. _this.overlayAlpha = 0.5;
  20782. _this._hasVertexAlpha = false;
  20783. _this._useVertexColors = true;
  20784. _this._computeBonesUsingShaders = true;
  20785. _this._numBoneInfluencers = 4;
  20786. _this._applyFog = true;
  20787. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20788. _this.useOctreeForRenderingSelection = true;
  20789. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20790. _this.useOctreeForPicking = true;
  20791. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20792. _this.useOctreeForCollisions = true;
  20793. _this._layerMask = 0x0FFFFFFF;
  20794. /**
  20795. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20796. */
  20797. _this.alwaysSelectAsActiveMesh = false;
  20798. /**
  20799. * Gets or sets the current action manager
  20800. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20801. */
  20802. _this.actionManager = null;
  20803. // Collisions
  20804. _this._checkCollisions = false;
  20805. _this._collisionMask = -1;
  20806. _this._collisionGroup = -1;
  20807. /**
  20808. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20809. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20810. */
  20811. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20812. /**
  20813. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20814. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20815. */
  20816. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20817. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20818. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20819. // Edges
  20820. /**
  20821. * Defines edge width used when edgesRenderer is enabled
  20822. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20823. */
  20824. _this.edgesWidth = 1;
  20825. /**
  20826. * Defines edge color used when edgesRenderer is enabled
  20827. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20828. */
  20829. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20830. /** @hidden */
  20831. _this._renderId = 0;
  20832. /** @hidden */
  20833. _this._intersectionsInProgress = new Array();
  20834. /** @hidden */
  20835. _this._unIndexed = false;
  20836. /** @hidden */
  20837. _this._lightSources = new Array();
  20838. /**
  20839. * An event triggered when the mesh is rebuilt.
  20840. */
  20841. _this.onRebuildObservable = new BABYLON.Observable();
  20842. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20843. if (collidedMesh === void 0) { collidedMesh = null; }
  20844. //TODO move this to the collision coordinator!
  20845. if (_this.getScene().workerCollisions) {
  20846. newPosition.multiplyInPlace(_this._collider._radius);
  20847. }
  20848. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20849. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20850. _this.position.addInPlace(_this._diffPositionForCollisions);
  20851. }
  20852. if (collidedMesh) {
  20853. _this.onCollideObservable.notifyObservers(collidedMesh);
  20854. }
  20855. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20856. };
  20857. _this.getScene().addMesh(_this);
  20858. _this._resyncLightSources();
  20859. return _this;
  20860. }
  20861. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20862. /**
  20863. * No billboard
  20864. */
  20865. get: function () {
  20866. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20867. },
  20868. enumerable: true,
  20869. configurable: true
  20870. });
  20871. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20872. /** Billboard on X axis */
  20873. get: function () {
  20874. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20875. },
  20876. enumerable: true,
  20877. configurable: true
  20878. });
  20879. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20880. /** Billboard on Y axis */
  20881. get: function () {
  20882. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20883. },
  20884. enumerable: true,
  20885. configurable: true
  20886. });
  20887. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20888. /** Billboard on Z axis */
  20889. get: function () {
  20890. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20891. },
  20892. enumerable: true,
  20893. configurable: true
  20894. });
  20895. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20896. /** Billboard on all axes */
  20897. get: function () {
  20898. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20899. },
  20900. enumerable: true,
  20901. configurable: true
  20902. });
  20903. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20904. /**
  20905. * Gets the number of facets in the mesh
  20906. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20907. */
  20908. get: function () {
  20909. return this._facetData.facetNb;
  20910. },
  20911. enumerable: true,
  20912. configurable: true
  20913. });
  20914. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20915. /**
  20916. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20917. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20918. */
  20919. get: function () {
  20920. return this._facetData.partitioningSubdivisions;
  20921. },
  20922. set: function (nb) {
  20923. this._facetData.partitioningSubdivisions = nb;
  20924. },
  20925. enumerable: true,
  20926. configurable: true
  20927. });
  20928. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20929. /**
  20930. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20931. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20932. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20933. */
  20934. get: function () {
  20935. return this._facetData.partitioningBBoxRatio;
  20936. },
  20937. set: function (ratio) {
  20938. this._facetData.partitioningBBoxRatio = ratio;
  20939. },
  20940. enumerable: true,
  20941. configurable: true
  20942. });
  20943. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20944. /**
  20945. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20946. * Works only for updatable meshes.
  20947. * Doesn't work with multi-materials
  20948. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20949. */
  20950. get: function () {
  20951. return this._facetData.facetDepthSort;
  20952. },
  20953. set: function (sort) {
  20954. this._facetData.facetDepthSort = sort;
  20955. },
  20956. enumerable: true,
  20957. configurable: true
  20958. });
  20959. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20960. /**
  20961. * The location (Vector3) where the facet depth sort must be computed from.
  20962. * By default, the active camera position.
  20963. * Used only when facet depth sort is enabled
  20964. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20965. */
  20966. get: function () {
  20967. return this._facetData.facetDepthSortFrom;
  20968. },
  20969. set: function (location) {
  20970. this._facetData.facetDepthSortFrom = location;
  20971. },
  20972. enumerable: true,
  20973. configurable: true
  20974. });
  20975. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20976. /**
  20977. * gets a boolean indicating if facetData is enabled
  20978. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20979. */
  20980. get: function () {
  20981. return this._facetData.facetDataEnabled;
  20982. },
  20983. enumerable: true,
  20984. configurable: true
  20985. });
  20986. /** @hidden */
  20987. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20988. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20989. return false;
  20990. }
  20991. this._markSubMeshesAsMiscDirty();
  20992. return true;
  20993. };
  20994. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20995. /** Set a function to call when this mesh collides with another one */
  20996. set: function (callback) {
  20997. if (this._onCollideObserver) {
  20998. this.onCollideObservable.remove(this._onCollideObserver);
  20999. }
  21000. this._onCollideObserver = this.onCollideObservable.add(callback);
  21001. },
  21002. enumerable: true,
  21003. configurable: true
  21004. });
  21005. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21006. /** Set a function to call when the collision's position changes */
  21007. set: function (callback) {
  21008. if (this._onCollisionPositionChangeObserver) {
  21009. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21010. }
  21011. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21012. },
  21013. enumerable: true,
  21014. configurable: true
  21015. });
  21016. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21017. /**
  21018. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21019. */
  21020. get: function () {
  21021. return this._visibility;
  21022. },
  21023. /**
  21024. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21025. */
  21026. set: function (value) {
  21027. if (this._visibility === value) {
  21028. return;
  21029. }
  21030. this._visibility = value;
  21031. this._markSubMeshesAsMiscDirty();
  21032. },
  21033. enumerable: true,
  21034. configurable: true
  21035. });
  21036. Object.defineProperty(AbstractMesh.prototype, "material", {
  21037. /** Gets or sets current material */
  21038. get: function () {
  21039. return this._material;
  21040. },
  21041. set: function (value) {
  21042. if (this._material === value) {
  21043. return;
  21044. }
  21045. this._material = value;
  21046. if (this.onMaterialChangedObservable.hasObservers) {
  21047. this.onMaterialChangedObservable.notifyObservers(this);
  21048. }
  21049. if (!this.subMeshes) {
  21050. return;
  21051. }
  21052. this._unBindEffect();
  21053. },
  21054. enumerable: true,
  21055. configurable: true
  21056. });
  21057. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21058. /**
  21059. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21060. * @see http://doc.babylonjs.com/babylon101/shadows
  21061. */
  21062. get: function () {
  21063. return this._receiveShadows;
  21064. },
  21065. set: function (value) {
  21066. if (this._receiveShadows === value) {
  21067. return;
  21068. }
  21069. this._receiveShadows = value;
  21070. this._markSubMeshesAsLightDirty();
  21071. },
  21072. enumerable: true,
  21073. configurable: true
  21074. });
  21075. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21076. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21077. get: function () {
  21078. return this._hasVertexAlpha;
  21079. },
  21080. set: function (value) {
  21081. if (this._hasVertexAlpha === value) {
  21082. return;
  21083. }
  21084. this._hasVertexAlpha = value;
  21085. this._markSubMeshesAsAttributesDirty();
  21086. this._markSubMeshesAsMiscDirty();
  21087. },
  21088. enumerable: true,
  21089. configurable: true
  21090. });
  21091. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21092. /** 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) */
  21093. get: function () {
  21094. return this._useVertexColors;
  21095. },
  21096. set: function (value) {
  21097. if (this._useVertexColors === value) {
  21098. return;
  21099. }
  21100. this._useVertexColors = value;
  21101. this._markSubMeshesAsAttributesDirty();
  21102. },
  21103. enumerable: true,
  21104. configurable: true
  21105. });
  21106. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21107. /**
  21108. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21109. */
  21110. get: function () {
  21111. return this._computeBonesUsingShaders;
  21112. },
  21113. set: function (value) {
  21114. if (this._computeBonesUsingShaders === value) {
  21115. return;
  21116. }
  21117. this._computeBonesUsingShaders = value;
  21118. this._markSubMeshesAsAttributesDirty();
  21119. },
  21120. enumerable: true,
  21121. configurable: true
  21122. });
  21123. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21124. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21125. get: function () {
  21126. return this._numBoneInfluencers;
  21127. },
  21128. set: function (value) {
  21129. if (this._numBoneInfluencers === value) {
  21130. return;
  21131. }
  21132. this._numBoneInfluencers = value;
  21133. this._markSubMeshesAsAttributesDirty();
  21134. },
  21135. enumerable: true,
  21136. configurable: true
  21137. });
  21138. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21139. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21140. get: function () {
  21141. return this._applyFog;
  21142. },
  21143. set: function (value) {
  21144. if (this._applyFog === value) {
  21145. return;
  21146. }
  21147. this._applyFog = value;
  21148. this._markSubMeshesAsMiscDirty();
  21149. },
  21150. enumerable: true,
  21151. configurable: true
  21152. });
  21153. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21154. /**
  21155. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21156. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21157. */
  21158. get: function () {
  21159. return this._layerMask;
  21160. },
  21161. set: function (value) {
  21162. if (value === this._layerMask) {
  21163. return;
  21164. }
  21165. this._layerMask = value;
  21166. this._resyncLightSources();
  21167. },
  21168. enumerable: true,
  21169. configurable: true
  21170. });
  21171. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21172. /**
  21173. * Gets or sets a collision mask used to mask collisions (default is -1).
  21174. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21175. */
  21176. get: function () {
  21177. return this._collisionMask;
  21178. },
  21179. set: function (mask) {
  21180. this._collisionMask = !isNaN(mask) ? mask : -1;
  21181. },
  21182. enumerable: true,
  21183. configurable: true
  21184. });
  21185. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21186. /**
  21187. * Gets or sets the current collision group mask (-1 by default).
  21188. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21189. */
  21190. get: function () {
  21191. return this._collisionGroup;
  21192. },
  21193. set: function (mask) {
  21194. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21195. },
  21196. enumerable: true,
  21197. configurable: true
  21198. });
  21199. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21200. /** @hidden */
  21201. get: function () {
  21202. return null;
  21203. },
  21204. enumerable: true,
  21205. configurable: true
  21206. });
  21207. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21208. get: function () {
  21209. return this._skeleton;
  21210. },
  21211. /**
  21212. * Gets or sets a skeleton to apply skining transformations
  21213. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21214. */
  21215. set: function (value) {
  21216. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21217. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21218. }
  21219. if (value && value.needInitialSkinMatrix) {
  21220. value._registerMeshWithPoseMatrix(this);
  21221. }
  21222. this._skeleton = value;
  21223. if (!this._skeleton) {
  21224. this._bonesTransformMatrices = null;
  21225. }
  21226. this._markSubMeshesAsAttributesDirty();
  21227. },
  21228. enumerable: true,
  21229. configurable: true
  21230. });
  21231. /**
  21232. * Returns the string "AbstractMesh"
  21233. * @returns "AbstractMesh"
  21234. */
  21235. AbstractMesh.prototype.getClassName = function () {
  21236. return "AbstractMesh";
  21237. };
  21238. /**
  21239. * Gets a string representation of the current mesh
  21240. * @param fullDetails defines a boolean indicating if full details must be included
  21241. * @returns a string representation of the current mesh
  21242. */
  21243. AbstractMesh.prototype.toString = function (fullDetails) {
  21244. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21245. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21246. if (this._skeleton) {
  21247. ret += ", skeleton: " + this._skeleton.name;
  21248. }
  21249. if (fullDetails) {
  21250. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21251. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21252. }
  21253. return ret;
  21254. };
  21255. /** @hidden */
  21256. AbstractMesh.prototype._rebuild = function () {
  21257. this.onRebuildObservable.notifyObservers(this);
  21258. if (this._occlusionQuery) {
  21259. this._occlusionQuery = null;
  21260. }
  21261. if (!this.subMeshes) {
  21262. return;
  21263. }
  21264. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21265. var subMesh = _a[_i];
  21266. subMesh._rebuild();
  21267. }
  21268. };
  21269. /** @hidden */
  21270. AbstractMesh.prototype._resyncLightSources = function () {
  21271. this._lightSources.length = 0;
  21272. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21273. var light = _a[_i];
  21274. if (!light.isEnabled()) {
  21275. continue;
  21276. }
  21277. if (light.canAffectMesh(this)) {
  21278. this._lightSources.push(light);
  21279. }
  21280. }
  21281. this._markSubMeshesAsLightDirty();
  21282. };
  21283. /** @hidden */
  21284. AbstractMesh.prototype._resyncLighSource = function (light) {
  21285. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21286. var index = this._lightSources.indexOf(light);
  21287. if (index === -1) {
  21288. if (!isIn) {
  21289. return;
  21290. }
  21291. this._lightSources.push(light);
  21292. }
  21293. else {
  21294. if (isIn) {
  21295. return;
  21296. }
  21297. this._lightSources.splice(index, 1);
  21298. }
  21299. this._markSubMeshesAsLightDirty();
  21300. };
  21301. /** @hidden */
  21302. AbstractMesh.prototype._unBindEffect = function () {
  21303. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21304. var subMesh = _a[_i];
  21305. subMesh.setEffect(null);
  21306. }
  21307. };
  21308. /** @hidden */
  21309. AbstractMesh.prototype._removeLightSource = function (light) {
  21310. var index = this._lightSources.indexOf(light);
  21311. if (index === -1) {
  21312. return;
  21313. }
  21314. this._lightSources.splice(index, 1);
  21315. this._markSubMeshesAsLightDirty();
  21316. };
  21317. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21318. if (!this.subMeshes) {
  21319. return;
  21320. }
  21321. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21322. var subMesh = _a[_i];
  21323. if (subMesh._materialDefines) {
  21324. func(subMesh._materialDefines);
  21325. }
  21326. }
  21327. };
  21328. /** @hidden */
  21329. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21330. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21331. };
  21332. /** @hidden */
  21333. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21334. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21335. };
  21336. /** @hidden */
  21337. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21338. if (!this.subMeshes) {
  21339. return;
  21340. }
  21341. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21342. var subMesh = _a[_i];
  21343. var material = subMesh.getMaterial();
  21344. if (material) {
  21345. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21346. }
  21347. }
  21348. };
  21349. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21350. /**
  21351. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21352. */
  21353. get: function () {
  21354. return this._scaling;
  21355. },
  21356. set: function (newScaling) {
  21357. this._scaling = newScaling;
  21358. if (this.physicsImpostor) {
  21359. this.physicsImpostor.forceUpdate();
  21360. }
  21361. },
  21362. enumerable: true,
  21363. configurable: true
  21364. });
  21365. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21366. // Methods
  21367. /**
  21368. * Returns true if the mesh is blocked. Implemented by child classes
  21369. */
  21370. get: function () {
  21371. return false;
  21372. },
  21373. enumerable: true,
  21374. configurable: true
  21375. });
  21376. /**
  21377. * Returns the mesh itself by default. Implemented by child classes
  21378. * @param camera defines the camera to use to pick the right LOD level
  21379. * @returns the currentAbstractMesh
  21380. */
  21381. AbstractMesh.prototype.getLOD = function (camera) {
  21382. return this;
  21383. };
  21384. /**
  21385. * Returns 0 by default. Implemented by child classes
  21386. * @returns an integer
  21387. */
  21388. AbstractMesh.prototype.getTotalVertices = function () {
  21389. return 0;
  21390. };
  21391. /**
  21392. * Returns null by default. Implemented by child classes
  21393. * @returns null
  21394. */
  21395. AbstractMesh.prototype.getIndices = function () {
  21396. return null;
  21397. };
  21398. /**
  21399. * Returns the array of the requested vertex data kind. Implemented by child classes
  21400. * @param kind defines the vertex data kind to use
  21401. * @returns null
  21402. */
  21403. AbstractMesh.prototype.getVerticesData = function (kind) {
  21404. return null;
  21405. };
  21406. /**
  21407. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21408. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21409. * Note that a new underlying VertexBuffer object is created each call.
  21410. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21411. * @param kind defines vertex data kind:
  21412. * * BABYLON.VertexBuffer.PositionKind
  21413. * * BABYLON.VertexBuffer.UVKind
  21414. * * BABYLON.VertexBuffer.UV2Kind
  21415. * * BABYLON.VertexBuffer.UV3Kind
  21416. * * BABYLON.VertexBuffer.UV4Kind
  21417. * * BABYLON.VertexBuffer.UV5Kind
  21418. * * BABYLON.VertexBuffer.UV6Kind
  21419. * * BABYLON.VertexBuffer.ColorKind
  21420. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21421. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21422. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21423. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21424. * @param data defines the data source
  21425. * @param updatable defines if the data must be flagged as updatable (or static)
  21426. * @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
  21427. * @returns the current mesh
  21428. */
  21429. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21430. return this;
  21431. };
  21432. /**
  21433. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21434. * If the mesh has no geometry, it is simply returned as it is.
  21435. * @param kind defines vertex data kind:
  21436. * * BABYLON.VertexBuffer.PositionKind
  21437. * * BABYLON.VertexBuffer.UVKind
  21438. * * BABYLON.VertexBuffer.UV2Kind
  21439. * * BABYLON.VertexBuffer.UV3Kind
  21440. * * BABYLON.VertexBuffer.UV4Kind
  21441. * * BABYLON.VertexBuffer.UV5Kind
  21442. * * BABYLON.VertexBuffer.UV6Kind
  21443. * * BABYLON.VertexBuffer.ColorKind
  21444. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21445. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21446. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21447. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21448. * @param data defines the data source
  21449. * @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
  21450. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21451. * @returns the current mesh
  21452. */
  21453. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21454. return this;
  21455. };
  21456. /**
  21457. * Sets the mesh indices,
  21458. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21459. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21460. * @param totalVertices Defines the total number of vertices
  21461. * @returns the current mesh
  21462. */
  21463. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21464. return this;
  21465. };
  21466. /**
  21467. * Gets a boolean indicating if specific vertex data is present
  21468. * @param kind defines the vertex data kind to use
  21469. * @returns true is data kind is present
  21470. */
  21471. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21472. return false;
  21473. };
  21474. /**
  21475. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21476. * @returns a BoundingInfo
  21477. */
  21478. AbstractMesh.prototype.getBoundingInfo = function () {
  21479. if (this._masterMesh) {
  21480. return this._masterMesh.getBoundingInfo();
  21481. }
  21482. if (!this._boundingInfo) {
  21483. // this._boundingInfo is being created here
  21484. this._updateBoundingInfo();
  21485. }
  21486. // cannot be null.
  21487. return this._boundingInfo;
  21488. };
  21489. /**
  21490. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21491. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21492. * @returns the current mesh
  21493. */
  21494. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21495. if (includeDescendants === void 0) { includeDescendants = true; }
  21496. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21497. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21498. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21499. if (maxDimension === 0) {
  21500. return this;
  21501. }
  21502. var scale = 1 / maxDimension;
  21503. this.scaling.scaleInPlace(scale);
  21504. return this;
  21505. };
  21506. /**
  21507. * Overwrite the current bounding info
  21508. * @param boundingInfo defines the new bounding info
  21509. * @returns the current mesh
  21510. */
  21511. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21512. this._boundingInfo = boundingInfo;
  21513. return this;
  21514. };
  21515. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21516. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21517. get: function () {
  21518. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21519. },
  21520. enumerable: true,
  21521. configurable: true
  21522. });
  21523. /** @hidden */
  21524. AbstractMesh.prototype._preActivate = function () {
  21525. };
  21526. /** @hidden */
  21527. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21528. };
  21529. /** @hidden */
  21530. AbstractMesh.prototype._activate = function (renderId) {
  21531. this._renderId = renderId;
  21532. };
  21533. /**
  21534. * Gets the current world matrix
  21535. * @returns a Matrix
  21536. */
  21537. AbstractMesh.prototype.getWorldMatrix = function () {
  21538. if (this._masterMesh) {
  21539. return this._masterMesh.getWorldMatrix();
  21540. }
  21541. return _super.prototype.getWorldMatrix.call(this);
  21542. };
  21543. /** @hidden */
  21544. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21545. if (this._masterMesh) {
  21546. return this._masterMesh._getWorldMatrixDeterminant();
  21547. }
  21548. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21549. };
  21550. // ================================== Point of View Movement =================================
  21551. /**
  21552. * Perform relative position change from the point of view of behind the front of the mesh.
  21553. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21554. * Supports definition of mesh facing forward or backward
  21555. * @param amountRight defines the distance on the right axis
  21556. * @param amountUp defines the distance on the up axis
  21557. * @param amountForward defines the distance on the forward axis
  21558. * @returns the current mesh
  21559. */
  21560. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21561. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21562. return this;
  21563. };
  21564. /**
  21565. * Calculate relative position change from the point of view of behind the front of the mesh.
  21566. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21567. * Supports definition of mesh facing forward or backward
  21568. * @param amountRight defines the distance on the right axis
  21569. * @param amountUp defines the distance on the up axis
  21570. * @param amountForward defines the distance on the forward axis
  21571. * @returns the new displacement vector
  21572. */
  21573. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21574. var rotMatrix = new BABYLON.Matrix();
  21575. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21576. rotQuaternion.toRotationMatrix(rotMatrix);
  21577. var translationDelta = BABYLON.Vector3.Zero();
  21578. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21579. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21580. return translationDelta;
  21581. };
  21582. // ================================== Point of View Rotation =================================
  21583. /**
  21584. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21585. * Supports definition of mesh facing forward or backward
  21586. * @param flipBack defines the flip
  21587. * @param twirlClockwise defines the twirl
  21588. * @param tiltRight defines the tilt
  21589. * @returns the current mesh
  21590. */
  21591. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21592. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21593. return this;
  21594. };
  21595. /**
  21596. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21597. * Supports definition of mesh facing forward or backward.
  21598. * @param flipBack defines the flip
  21599. * @param twirlClockwise defines the twirl
  21600. * @param tiltRight defines the tilt
  21601. * @returns the new rotation vector
  21602. */
  21603. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21604. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21605. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21606. };
  21607. /**
  21608. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21609. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21610. * @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
  21611. * @returns the new bounding vectors
  21612. */
  21613. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21614. if (includeDescendants === void 0) { includeDescendants = true; }
  21615. if (predicate === void 0) { predicate = null; }
  21616. // Ensures that all world matrix will be recomputed.
  21617. this.getScene().incrementRenderId();
  21618. this.computeWorldMatrix(true);
  21619. var min;
  21620. var max;
  21621. var boundingInfo = this.getBoundingInfo();
  21622. if (!this.subMeshes) {
  21623. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21624. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21625. }
  21626. else {
  21627. min = boundingInfo.boundingBox.minimumWorld;
  21628. max = boundingInfo.boundingBox.maximumWorld;
  21629. }
  21630. if (includeDescendants) {
  21631. var descendants = this.getDescendants(false);
  21632. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21633. var descendant = descendants_1[_i];
  21634. var childMesh = descendant;
  21635. childMesh.computeWorldMatrix(true);
  21636. // Filters meshes based on custom predicate function.
  21637. if (predicate && !predicate(childMesh)) {
  21638. continue;
  21639. }
  21640. //make sure we have the needed params to get mix and max
  21641. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21642. continue;
  21643. }
  21644. var childBoundingInfo = childMesh.getBoundingInfo();
  21645. var boundingBox = childBoundingInfo.boundingBox;
  21646. var minBox = boundingBox.minimumWorld;
  21647. var maxBox = boundingBox.maximumWorld;
  21648. BABYLON.Tools.CheckExtends(minBox, min, max);
  21649. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21650. }
  21651. }
  21652. return {
  21653. min: min,
  21654. max: max
  21655. };
  21656. };
  21657. /** @hidden */
  21658. AbstractMesh.prototype._updateBoundingInfo = function () {
  21659. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21660. this._boundingInfo.update(this.worldMatrixFromCache);
  21661. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21662. return this;
  21663. };
  21664. /** @hidden */
  21665. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21666. if (!this.subMeshes) {
  21667. return this;
  21668. }
  21669. var count = this.subMeshes.length;
  21670. for (var subIndex = 0; subIndex < count; subIndex++) {
  21671. var subMesh = this.subMeshes[subIndex];
  21672. if (count > 1 || !subMesh.IsGlobal) {
  21673. subMesh.updateBoundingInfo(matrix);
  21674. }
  21675. }
  21676. return this;
  21677. };
  21678. /** @hidden */
  21679. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21680. // Bounding info
  21681. this._updateBoundingInfo();
  21682. };
  21683. /**
  21684. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21685. * A mesh is in the frustum if its bounding box intersects the frustum
  21686. * @param frustumPlanes defines the frustum to test
  21687. * @returns true if the mesh is in the frustum planes
  21688. */
  21689. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21690. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21691. };
  21692. /**
  21693. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21694. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21695. * @param frustumPlanes defines the frustum to test
  21696. * @returns true if the mesh is completely in the frustum planes
  21697. */
  21698. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21699. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21700. };
  21701. /**
  21702. * True if the mesh intersects another mesh or a SolidParticle object
  21703. * @param mesh defines a target mesh or SolidParticle to test
  21704. * @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)
  21705. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21706. * @returns true if there is an intersection
  21707. */
  21708. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21709. if (precise === void 0) { precise = false; }
  21710. if (!this._boundingInfo || !mesh._boundingInfo) {
  21711. return false;
  21712. }
  21713. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21714. return true;
  21715. }
  21716. if (includeDescendants) {
  21717. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21718. var child = _a[_i];
  21719. if (child.intersectsMesh(mesh, precise, true)) {
  21720. return true;
  21721. }
  21722. }
  21723. }
  21724. return false;
  21725. };
  21726. /**
  21727. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21728. * @param point defines the point to test
  21729. * @returns true if there is an intersection
  21730. */
  21731. AbstractMesh.prototype.intersectsPoint = function (point) {
  21732. if (!this._boundingInfo) {
  21733. return false;
  21734. }
  21735. return this._boundingInfo.intersectsPoint(point);
  21736. };
  21737. /**
  21738. * Gets the position of the current mesh in camera space
  21739. * @param camera defines the camera to use
  21740. * @returns a position
  21741. */
  21742. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21743. if (camera === void 0) { camera = null; }
  21744. if (!camera) {
  21745. camera = this.getScene().activeCamera;
  21746. }
  21747. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21748. };
  21749. /**
  21750. * Returns the distance from the mesh to the active camera
  21751. * @param camera defines the camera to use
  21752. * @returns the distance
  21753. */
  21754. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21755. if (camera === void 0) { camera = null; }
  21756. if (!camera) {
  21757. camera = this.getScene().activeCamera;
  21758. }
  21759. return this.absolutePosition.subtract(camera.position).length();
  21760. };
  21761. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21762. // Collisions
  21763. /**
  21764. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21765. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21766. */
  21767. get: function () {
  21768. return this._checkCollisions;
  21769. },
  21770. set: function (collisionEnabled) {
  21771. this._checkCollisions = collisionEnabled;
  21772. if (this.getScene().workerCollisions) {
  21773. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21774. }
  21775. },
  21776. enumerable: true,
  21777. configurable: true
  21778. });
  21779. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21780. /**
  21781. * Gets Collider object used to compute collisions (not physics)
  21782. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21783. */
  21784. get: function () {
  21785. return this._collider;
  21786. },
  21787. enumerable: true,
  21788. configurable: true
  21789. });
  21790. /**
  21791. * Move the mesh using collision engine
  21792. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21793. * @param displacement defines the requested displacement vector
  21794. * @returns the current mesh
  21795. */
  21796. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21797. var globalPosition = this.getAbsolutePosition();
  21798. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21799. if (!this._collider) {
  21800. this._collider = new BABYLON.Collider();
  21801. }
  21802. this._collider._radius = this.ellipsoid;
  21803. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21804. return this;
  21805. };
  21806. // Collisions
  21807. /** @hidden */
  21808. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21809. this._generatePointsArray();
  21810. if (!this._positions) {
  21811. return this;
  21812. }
  21813. // Transformation
  21814. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21815. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21816. subMesh._lastColliderWorldVertices = [];
  21817. subMesh._trianglePlanes = [];
  21818. var start = subMesh.verticesStart;
  21819. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21820. for (var i = start; i < end; i++) {
  21821. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21822. }
  21823. }
  21824. // Collide
  21825. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21826. if (collider.collisionFound) {
  21827. collider.collidedMesh = this;
  21828. }
  21829. return this;
  21830. };
  21831. /** @hidden */
  21832. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21833. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21834. var len = subMeshes.length;
  21835. for (var index = 0; index < len; index++) {
  21836. var subMesh = subMeshes.data[index];
  21837. // Bounding test
  21838. if (len > 1 && !subMesh._checkCollision(collider)) {
  21839. continue;
  21840. }
  21841. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21842. }
  21843. return this;
  21844. };
  21845. /** @hidden */
  21846. AbstractMesh.prototype._checkCollision = function (collider) {
  21847. // Bounding box test
  21848. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  21849. return this;
  21850. }
  21851. // Transformation matrix
  21852. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21853. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21854. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21855. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21856. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21857. return this;
  21858. };
  21859. // Picking
  21860. /** @hidden */
  21861. AbstractMesh.prototype._generatePointsArray = function () {
  21862. return false;
  21863. };
  21864. /**
  21865. * Checks if the passed Ray intersects with the mesh
  21866. * @param ray defines the ray to use
  21867. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21868. * @returns the picking info
  21869. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21870. */
  21871. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21872. var pickingInfo = new BABYLON.PickingInfo();
  21873. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21874. return pickingInfo;
  21875. }
  21876. if (!this._generatePointsArray()) {
  21877. return pickingInfo;
  21878. }
  21879. var intersectInfo = null;
  21880. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21881. var len = subMeshes.length;
  21882. for (var index = 0; index < len; index++) {
  21883. var subMesh = subMeshes.data[index];
  21884. // Bounding test
  21885. if (len > 1 && !subMesh.canIntersects(ray)) {
  21886. continue;
  21887. }
  21888. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21889. if (currentIntersectInfo) {
  21890. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21891. intersectInfo = currentIntersectInfo;
  21892. intersectInfo.subMeshId = index;
  21893. if (fastCheck) {
  21894. break;
  21895. }
  21896. }
  21897. }
  21898. }
  21899. if (intersectInfo) {
  21900. // Get picked point
  21901. var world = this.getWorldMatrix();
  21902. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21903. var direction = ray.direction.clone();
  21904. direction = direction.scale(intersectInfo.distance);
  21905. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21906. var pickedPoint = worldOrigin.add(worldDirection);
  21907. // Return result
  21908. pickingInfo.hit = true;
  21909. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21910. pickingInfo.pickedPoint = pickedPoint;
  21911. pickingInfo.pickedMesh = this;
  21912. pickingInfo.bu = intersectInfo.bu || 0;
  21913. pickingInfo.bv = intersectInfo.bv || 0;
  21914. pickingInfo.faceId = intersectInfo.faceId;
  21915. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21916. return pickingInfo;
  21917. }
  21918. return pickingInfo;
  21919. };
  21920. /**
  21921. * Clones the current mesh
  21922. * @param name defines the mesh name
  21923. * @param newParent defines the new mesh parent
  21924. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21925. * @returns the new mesh
  21926. */
  21927. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21928. return null;
  21929. };
  21930. /**
  21931. * Disposes all the submeshes of the current meshnp
  21932. * @returns the current mesh
  21933. */
  21934. AbstractMesh.prototype.releaseSubMeshes = function () {
  21935. if (this.subMeshes) {
  21936. while (this.subMeshes.length) {
  21937. this.subMeshes[0].dispose();
  21938. }
  21939. }
  21940. else {
  21941. this.subMeshes = new Array();
  21942. }
  21943. return this;
  21944. };
  21945. /**
  21946. * Releases resources associated with this abstract mesh.
  21947. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21948. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21949. */
  21950. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21951. var _this = this;
  21952. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21953. var index;
  21954. // Smart Array Retainers.
  21955. this.getScene().freeActiveMeshes();
  21956. this.getScene().freeRenderingGroups();
  21957. // Action manager
  21958. if (this.actionManager !== undefined && this.actionManager !== null) {
  21959. this.actionManager.dispose();
  21960. this.actionManager = null;
  21961. }
  21962. // Skeleton
  21963. this._skeleton = null;
  21964. // Intersections in progress
  21965. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21966. var other = this._intersectionsInProgress[index];
  21967. var pos = other._intersectionsInProgress.indexOf(this);
  21968. other._intersectionsInProgress.splice(pos, 1);
  21969. }
  21970. this._intersectionsInProgress = [];
  21971. // Lights
  21972. var lights = this.getScene().lights;
  21973. lights.forEach(function (light) {
  21974. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21975. if (meshIndex !== -1) {
  21976. light.includedOnlyMeshes.splice(meshIndex, 1);
  21977. }
  21978. meshIndex = light.excludedMeshes.indexOf(_this);
  21979. if (meshIndex !== -1) {
  21980. light.excludedMeshes.splice(meshIndex, 1);
  21981. }
  21982. // Shadow generators
  21983. var generator = light.getShadowGenerator();
  21984. if (generator) {
  21985. var shadowMap = generator.getShadowMap();
  21986. if (shadowMap && shadowMap.renderList) {
  21987. meshIndex = shadowMap.renderList.indexOf(_this);
  21988. if (meshIndex !== -1) {
  21989. shadowMap.renderList.splice(meshIndex, 1);
  21990. }
  21991. }
  21992. }
  21993. });
  21994. // SubMeshes
  21995. if (this.getClassName() !== "InstancedMesh") {
  21996. this.releaseSubMeshes();
  21997. }
  21998. // Query
  21999. var engine = this.getScene().getEngine();
  22000. if (this._occlusionQuery) {
  22001. this.isOcclusionQueryInProgress = false;
  22002. engine.deleteQuery(this._occlusionQuery);
  22003. this._occlusionQuery = null;
  22004. }
  22005. // Engine
  22006. engine.wipeCaches();
  22007. // Remove from scene
  22008. this.getScene().removeMesh(this);
  22009. if (disposeMaterialAndTextures) {
  22010. if (this.material) {
  22011. this.material.dispose(false, true);
  22012. }
  22013. }
  22014. if (!doNotRecurse) {
  22015. // Particles
  22016. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22017. if (this.getScene().particleSystems[index].emitter === this) {
  22018. this.getScene().particleSystems[index].dispose();
  22019. index--;
  22020. }
  22021. }
  22022. }
  22023. // facet data
  22024. if (this._facetData.facetDataEnabled) {
  22025. this.disableFacetData();
  22026. }
  22027. this.onAfterWorldMatrixUpdateObservable.clear();
  22028. this.onCollideObservable.clear();
  22029. this.onCollisionPositionChangeObservable.clear();
  22030. this.onRebuildObservable.clear();
  22031. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22032. };
  22033. /**
  22034. * Adds the passed mesh as a child to the current mesh
  22035. * @param mesh defines the child mesh
  22036. * @returns the current mesh
  22037. */
  22038. AbstractMesh.prototype.addChild = function (mesh) {
  22039. mesh.setParent(this);
  22040. return this;
  22041. };
  22042. /**
  22043. * Removes the passed mesh from the current mesh children list
  22044. * @param mesh defines the child mesh
  22045. * @returns the current mesh
  22046. */
  22047. AbstractMesh.prototype.removeChild = function (mesh) {
  22048. mesh.setParent(null);
  22049. return this;
  22050. };
  22051. // Facet data
  22052. /** @hidden */
  22053. AbstractMesh.prototype._initFacetData = function () {
  22054. var data = this._facetData;
  22055. if (!data.facetNormals) {
  22056. data.facetNormals = new Array();
  22057. }
  22058. if (!data.facetPositions) {
  22059. data.facetPositions = new Array();
  22060. }
  22061. if (!data.facetPartitioning) {
  22062. data.facetPartitioning = new Array();
  22063. }
  22064. data.facetNb = (this.getIndices().length / 3) | 0;
  22065. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22066. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22067. for (var f = 0; f < data.facetNb; f++) {
  22068. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22069. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22070. }
  22071. data.facetDataEnabled = true;
  22072. return this;
  22073. };
  22074. /**
  22075. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22076. * This method can be called within the render loop.
  22077. * 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
  22078. * @returns the current mesh
  22079. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22080. */
  22081. AbstractMesh.prototype.updateFacetData = function () {
  22082. var data = this._facetData;
  22083. if (!data.facetDataEnabled) {
  22084. this._initFacetData();
  22085. }
  22086. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22087. var indices = this.getIndices();
  22088. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22089. var bInfo = this.getBoundingInfo();
  22090. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22091. // init arrays, matrix and sort function on first call
  22092. data.facetDepthSortEnabled = true;
  22093. if (indices instanceof Uint16Array) {
  22094. data.depthSortedIndices = new Uint16Array(indices);
  22095. }
  22096. else if (indices instanceof Uint32Array) {
  22097. data.depthSortedIndices = new Uint32Array(indices);
  22098. }
  22099. else {
  22100. var needs32bits = false;
  22101. for (var i = 0; i < indices.length; i++) {
  22102. if (indices[i] > 65535) {
  22103. needs32bits = true;
  22104. break;
  22105. }
  22106. }
  22107. if (needs32bits) {
  22108. data.depthSortedIndices = new Uint32Array(indices);
  22109. }
  22110. else {
  22111. data.depthSortedIndices = new Uint16Array(indices);
  22112. }
  22113. }
  22114. data.facetDepthSortFunction = function (f1, f2) {
  22115. return (f2.sqDistance - f1.sqDistance);
  22116. };
  22117. if (!data.facetDepthSortFrom) {
  22118. var camera = this.getScene().activeCamera;
  22119. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22120. }
  22121. data.depthSortedFacets = [];
  22122. for (var f = 0; f < data.facetNb; f++) {
  22123. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22124. data.depthSortedFacets.push(depthSortedFacet);
  22125. }
  22126. data.invertedMatrix = BABYLON.Matrix.Identity();
  22127. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22128. }
  22129. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22130. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22131. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22132. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22133. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22134. data.subDiv.max = data.partitioningSubdivisions;
  22135. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22136. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22137. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22138. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22139. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22140. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22141. // set the parameters for ComputeNormals()
  22142. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22143. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22144. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22145. data.facetParameters.bInfo = bInfo;
  22146. data.facetParameters.bbSize = data.bbSize;
  22147. data.facetParameters.subDiv = data.subDiv;
  22148. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22149. data.facetParameters.depthSort = data.facetDepthSort;
  22150. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22151. this.computeWorldMatrix(true);
  22152. this._worldMatrix.invertToRef(data.invertedMatrix);
  22153. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22154. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22155. }
  22156. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22157. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22158. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22159. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22160. var l = (data.depthSortedIndices.length / 3) | 0;
  22161. for (var f = 0; f < l; f++) {
  22162. var sind = data.depthSortedFacets[f].ind;
  22163. data.depthSortedIndices[f * 3] = indices[sind];
  22164. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22165. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22166. }
  22167. this.updateIndices(data.depthSortedIndices);
  22168. }
  22169. return this;
  22170. };
  22171. /**
  22172. * Returns the facetLocalNormals array.
  22173. * The normals are expressed in the mesh local spac
  22174. * @returns an array of Vector3
  22175. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22176. */
  22177. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22178. if (!this._facetData.facetNormals) {
  22179. this.updateFacetData();
  22180. }
  22181. return this._facetData.facetNormals;
  22182. };
  22183. /**
  22184. * Returns the facetLocalPositions array.
  22185. * The facet positions are expressed in the mesh local space
  22186. * @returns an array of Vector3
  22187. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22188. */
  22189. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22190. if (!this._facetData.facetPositions) {
  22191. this.updateFacetData();
  22192. }
  22193. return this._facetData.facetPositions;
  22194. };
  22195. /**
  22196. * Returns the facetLocalPartioning array
  22197. * @returns an array of array of numbers
  22198. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22199. */
  22200. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22201. if (!this._facetData.facetPartitioning) {
  22202. this.updateFacetData();
  22203. }
  22204. return this._facetData.facetPartitioning;
  22205. };
  22206. /**
  22207. * Returns the i-th facet position in the world system.
  22208. * This method allocates a new Vector3 per call
  22209. * @param i defines the facet index
  22210. * @returns a new Vector3
  22211. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22212. */
  22213. AbstractMesh.prototype.getFacetPosition = function (i) {
  22214. var pos = BABYLON.Vector3.Zero();
  22215. this.getFacetPositionToRef(i, pos);
  22216. return pos;
  22217. };
  22218. /**
  22219. * Sets the reference Vector3 with the i-th facet position in the world system
  22220. * @param i defines the facet index
  22221. * @param ref defines the target vector
  22222. * @returns the current mesh
  22223. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22224. */
  22225. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22226. var localPos = (this.getFacetLocalPositions())[i];
  22227. var world = this.getWorldMatrix();
  22228. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22229. return this;
  22230. };
  22231. /**
  22232. * Returns the i-th facet normal in the world system.
  22233. * This method allocates a new Vector3 per call
  22234. * @param i defines the facet index
  22235. * @returns a new Vector3
  22236. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22237. */
  22238. AbstractMesh.prototype.getFacetNormal = function (i) {
  22239. var norm = BABYLON.Vector3.Zero();
  22240. this.getFacetNormalToRef(i, norm);
  22241. return norm;
  22242. };
  22243. /**
  22244. * Sets the reference Vector3 with the i-th facet normal in the world system
  22245. * @param i defines the facet index
  22246. * @param ref defines the target vector
  22247. * @returns the current mesh
  22248. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22249. */
  22250. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22251. var localNorm = (this.getFacetLocalNormals())[i];
  22252. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22253. return this;
  22254. };
  22255. /**
  22256. * 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)
  22257. * @param x defines x coordinate
  22258. * @param y defines y coordinate
  22259. * @param z defines z coordinate
  22260. * @returns the array of facet indexes
  22261. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22262. */
  22263. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22264. var bInfo = this.getBoundingInfo();
  22265. var data = this._facetData;
  22266. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22267. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22268. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22269. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22270. return null;
  22271. }
  22272. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22273. };
  22274. /**
  22275. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22276. * @param projected sets as the (x,y,z) world projection on the facet
  22277. * @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
  22278. * @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
  22279. * @param x defines x coordinate
  22280. * @param y defines y coordinate
  22281. * @param z defines z coordinate
  22282. * @returns the face index if found (or null instead)
  22283. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22284. */
  22285. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22286. if (checkFace === void 0) { checkFace = false; }
  22287. if (facing === void 0) { facing = true; }
  22288. var world = this.getWorldMatrix();
  22289. var invMat = BABYLON.Tmp.Matrix[5];
  22290. world.invertToRef(invMat);
  22291. var invVect = BABYLON.Tmp.Vector3[8];
  22292. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22293. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22294. if (projected) {
  22295. // tranform the local computed projected vector to world coordinates
  22296. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22297. }
  22298. return closest;
  22299. };
  22300. /**
  22301. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22302. * @param projected sets as the (x,y,z) local projection on the facet
  22303. * @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
  22304. * @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
  22305. * @param x defines x coordinate
  22306. * @param y defines y coordinate
  22307. * @param z defines z coordinate
  22308. * @returns the face index if found (or null instead)
  22309. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22310. */
  22311. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22312. if (checkFace === void 0) { checkFace = false; }
  22313. if (facing === void 0) { facing = true; }
  22314. var closest = null;
  22315. var tmpx = 0.0;
  22316. var tmpy = 0.0;
  22317. var tmpz = 0.0;
  22318. var d = 0.0; // tmp dot facet normal * facet position
  22319. var t0 = 0.0;
  22320. var projx = 0.0;
  22321. var projy = 0.0;
  22322. var projz = 0.0;
  22323. // Get all the facets in the same partitioning block than (x, y, z)
  22324. var facetPositions = this.getFacetLocalPositions();
  22325. var facetNormals = this.getFacetLocalNormals();
  22326. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22327. if (!facetsInBlock) {
  22328. return null;
  22329. }
  22330. // Get the closest facet to (x, y, z)
  22331. var shortest = Number.MAX_VALUE; // init distance vars
  22332. var tmpDistance = shortest;
  22333. var fib; // current facet in the block
  22334. var norm; // current facet normal
  22335. var p0; // current facet barycenter position
  22336. // loop on all the facets in the current partitioning block
  22337. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22338. fib = facetsInBlock[idx];
  22339. norm = facetNormals[fib];
  22340. p0 = facetPositions[fib];
  22341. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22342. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22343. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22344. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22345. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22346. projx = x + norm.x * t0;
  22347. projy = y + norm.y * t0;
  22348. projz = z + norm.z * t0;
  22349. tmpx = projx - x;
  22350. tmpy = projy - y;
  22351. tmpz = projz - z;
  22352. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22353. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22354. shortest = tmpDistance;
  22355. closest = fib;
  22356. if (projected) {
  22357. projected.x = projx;
  22358. projected.y = projy;
  22359. projected.z = projz;
  22360. }
  22361. }
  22362. }
  22363. }
  22364. return closest;
  22365. };
  22366. /**
  22367. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22368. * @returns the parameters
  22369. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22370. */
  22371. AbstractMesh.prototype.getFacetDataParameters = function () {
  22372. return this._facetData.facetParameters;
  22373. };
  22374. /**
  22375. * Disables the feature FacetData and frees the related memory
  22376. * @returns the current mesh
  22377. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22378. */
  22379. AbstractMesh.prototype.disableFacetData = function () {
  22380. if (this._facetData.facetDataEnabled) {
  22381. this._facetData.facetDataEnabled = false;
  22382. this._facetData.facetPositions = new Array();
  22383. this._facetData.facetNormals = new Array();
  22384. this._facetData.facetPartitioning = new Array();
  22385. this._facetData.facetParameters = null;
  22386. this._facetData.depthSortedIndices = new Uint32Array(0);
  22387. }
  22388. return this;
  22389. };
  22390. /**
  22391. * Updates the AbstractMesh indices array
  22392. * @param indices defines the data source
  22393. * @returns the current mesh
  22394. */
  22395. AbstractMesh.prototype.updateIndices = function (indices) {
  22396. return this;
  22397. };
  22398. /**
  22399. * Creates new normals data for the mesh
  22400. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22401. * @returns the current mesh
  22402. */
  22403. AbstractMesh.prototype.createNormals = function (updatable) {
  22404. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22405. var indices = this.getIndices();
  22406. var normals;
  22407. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22408. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22409. }
  22410. else {
  22411. normals = [];
  22412. }
  22413. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22414. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22415. return this;
  22416. };
  22417. /**
  22418. * Align the mesh with a normal
  22419. * @param normal defines the normal to use
  22420. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22421. * @returns the current mesh
  22422. */
  22423. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22424. if (!upDirection) {
  22425. upDirection = BABYLON.Axis.Y;
  22426. }
  22427. var axisX = BABYLON.Tmp.Vector3[0];
  22428. var axisZ = BABYLON.Tmp.Vector3[1];
  22429. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22430. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22431. if (this.rotationQuaternion) {
  22432. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22433. }
  22434. else {
  22435. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22436. }
  22437. return this;
  22438. };
  22439. /** @hidden */
  22440. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22441. return false;
  22442. };
  22443. /** No occlusion */
  22444. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22445. /** Occlusion set to optimisitic */
  22446. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22447. /** Occlusion set to strict */
  22448. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22449. /** Use an accurante occlusion algorithm */
  22450. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22451. /** Use a conservative occlusion algorithm */
  22452. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22453. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22454. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22455. /** Culling strategy with bounding sphere only and then frustum culling */
  22456. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22457. return AbstractMesh;
  22458. }(BABYLON.TransformNode));
  22459. BABYLON.AbstractMesh = AbstractMesh;
  22460. })(BABYLON || (BABYLON = {}));
  22461. //# sourceMappingURL=babylon.abstractMesh.js.map
  22462. var BABYLON;
  22463. (function (BABYLON) {
  22464. /**
  22465. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22466. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22467. * 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.
  22468. */
  22469. var Light = /** @class */ (function (_super) {
  22470. __extends(Light, _super);
  22471. /**
  22472. * Creates a Light object in the scene.
  22473. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22474. * @param name The firendly name of the light
  22475. * @param scene The scene the light belongs too
  22476. */
  22477. function Light(name, scene) {
  22478. var _this = _super.call(this, name, scene) || this;
  22479. /**
  22480. * Diffuse gives the basic color to an object.
  22481. */
  22482. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22483. /**
  22484. * Specular produces a highlight color on an object.
  22485. * Note: This is note affecting PBR materials.
  22486. */
  22487. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22488. /**
  22489. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22490. * falling off base on range or angle.
  22491. * This can be set to any values in Light.FALLOFF_x.
  22492. *
  22493. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22494. * other types of materials.
  22495. */
  22496. _this.falloffType = Light.FALLOFF_DEFAULT;
  22497. /**
  22498. * Strength of the light.
  22499. * Note: By default it is define in the framework own unit.
  22500. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22501. */
  22502. _this.intensity = 1.0;
  22503. _this._range = Number.MAX_VALUE;
  22504. _this._inverseSquaredRange = 0;
  22505. /**
  22506. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22507. * of light.
  22508. */
  22509. _this._photometricScale = 1.0;
  22510. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22511. _this._radius = 0.00001;
  22512. /**
  22513. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22514. * exceeding the number allowed of the materials.
  22515. */
  22516. _this.renderPriority = 0;
  22517. _this._shadowEnabled = true;
  22518. _this._excludeWithLayerMask = 0;
  22519. _this._includeOnlyWithLayerMask = 0;
  22520. _this._lightmapMode = 0;
  22521. /**
  22522. * @hidden Internal use only.
  22523. */
  22524. _this._excludedMeshesIds = new Array();
  22525. /**
  22526. * @hidden Internal use only.
  22527. */
  22528. _this._includedOnlyMeshesIds = new Array();
  22529. _this.getScene().addLight(_this);
  22530. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22531. _this._buildUniformLayout();
  22532. _this.includedOnlyMeshes = new Array();
  22533. _this.excludedMeshes = new Array();
  22534. _this._resyncMeshes();
  22535. return _this;
  22536. }
  22537. Object.defineProperty(Light.prototype, "range", {
  22538. /**
  22539. * Defines how far from the source the light is impacting in scene units.
  22540. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22541. */
  22542. get: function () {
  22543. return this._range;
  22544. },
  22545. /**
  22546. * Defines how far from the source the light is impacting in scene units.
  22547. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22548. */
  22549. set: function (value) {
  22550. this._range = value;
  22551. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22552. },
  22553. enumerable: true,
  22554. configurable: true
  22555. });
  22556. Object.defineProperty(Light.prototype, "intensityMode", {
  22557. /**
  22558. * Gets the photometric scale used to interpret the intensity.
  22559. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22560. */
  22561. get: function () {
  22562. return this._intensityMode;
  22563. },
  22564. /**
  22565. * Sets the photometric scale used to interpret the intensity.
  22566. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22567. */
  22568. set: function (value) {
  22569. this._intensityMode = value;
  22570. this._computePhotometricScale();
  22571. },
  22572. enumerable: true,
  22573. configurable: true
  22574. });
  22575. Object.defineProperty(Light.prototype, "radius", {
  22576. /**
  22577. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22578. */
  22579. get: function () {
  22580. return this._radius;
  22581. },
  22582. /**
  22583. * sets the light radius used by PBR Materials to simulate soft area lights.
  22584. */
  22585. set: function (value) {
  22586. this._radius = value;
  22587. this._computePhotometricScale();
  22588. },
  22589. enumerable: true,
  22590. configurable: true
  22591. });
  22592. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22593. /**
  22594. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22595. * the current shadow generator.
  22596. */
  22597. get: function () {
  22598. return this._shadowEnabled;
  22599. },
  22600. /**
  22601. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22602. * the current shadow generator.
  22603. */
  22604. set: function (value) {
  22605. if (this._shadowEnabled === value) {
  22606. return;
  22607. }
  22608. this._shadowEnabled = value;
  22609. this._markMeshesAsLightDirty();
  22610. },
  22611. enumerable: true,
  22612. configurable: true
  22613. });
  22614. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22615. /**
  22616. * Gets the only meshes impacted by this light.
  22617. */
  22618. get: function () {
  22619. return this._includedOnlyMeshes;
  22620. },
  22621. /**
  22622. * Sets the only meshes impacted by this light.
  22623. */
  22624. set: function (value) {
  22625. this._includedOnlyMeshes = value;
  22626. this._hookArrayForIncludedOnly(value);
  22627. },
  22628. enumerable: true,
  22629. configurable: true
  22630. });
  22631. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22632. /**
  22633. * Gets the meshes not impacted by this light.
  22634. */
  22635. get: function () {
  22636. return this._excludedMeshes;
  22637. },
  22638. /**
  22639. * Sets the meshes not impacted by this light.
  22640. */
  22641. set: function (value) {
  22642. this._excludedMeshes = value;
  22643. this._hookArrayForExcluded(value);
  22644. },
  22645. enumerable: true,
  22646. configurable: true
  22647. });
  22648. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22649. /**
  22650. * Gets the layer id use to find what meshes are not impacted by the light.
  22651. * Inactive if 0
  22652. */
  22653. get: function () {
  22654. return this._excludeWithLayerMask;
  22655. },
  22656. /**
  22657. * Sets the layer id use to find what meshes are not impacted by the light.
  22658. * Inactive if 0
  22659. */
  22660. set: function (value) {
  22661. this._excludeWithLayerMask = value;
  22662. this._resyncMeshes();
  22663. },
  22664. enumerable: true,
  22665. configurable: true
  22666. });
  22667. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22668. /**
  22669. * Gets the layer id use to find what meshes are impacted by the light.
  22670. * Inactive if 0
  22671. */
  22672. get: function () {
  22673. return this._includeOnlyWithLayerMask;
  22674. },
  22675. /**
  22676. * Sets the layer id use to find what meshes are impacted by the light.
  22677. * Inactive if 0
  22678. */
  22679. set: function (value) {
  22680. this._includeOnlyWithLayerMask = value;
  22681. this._resyncMeshes();
  22682. },
  22683. enumerable: true,
  22684. configurable: true
  22685. });
  22686. Object.defineProperty(Light.prototype, "lightmapMode", {
  22687. /**
  22688. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22689. */
  22690. get: function () {
  22691. return this._lightmapMode;
  22692. },
  22693. /**
  22694. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22695. */
  22696. set: function (value) {
  22697. if (this._lightmapMode === value) {
  22698. return;
  22699. }
  22700. this._lightmapMode = value;
  22701. this._markMeshesAsLightDirty();
  22702. },
  22703. enumerable: true,
  22704. configurable: true
  22705. });
  22706. /**
  22707. * Returns the string "Light".
  22708. * @returns the class name
  22709. */
  22710. Light.prototype.getClassName = function () {
  22711. return "Light";
  22712. };
  22713. /**
  22714. * Converts the light information to a readable string for debug purpose.
  22715. * @param fullDetails Supports for multiple levels of logging within scene loading
  22716. * @returns the human readable light info
  22717. */
  22718. Light.prototype.toString = function (fullDetails) {
  22719. var ret = "Name: " + this.name;
  22720. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22721. if (this.animations) {
  22722. for (var i = 0; i < this.animations.length; i++) {
  22723. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22724. }
  22725. }
  22726. if (fullDetails) {
  22727. }
  22728. return ret;
  22729. };
  22730. /** @hidden */
  22731. Light.prototype._syncParentEnabledState = function () {
  22732. _super.prototype._syncParentEnabledState.call(this);
  22733. this._resyncMeshes();
  22734. };
  22735. /**
  22736. * Set the enabled state of this node.
  22737. * @param value - the new enabled state
  22738. */
  22739. Light.prototype.setEnabled = function (value) {
  22740. _super.prototype.setEnabled.call(this, value);
  22741. this._resyncMeshes();
  22742. };
  22743. /**
  22744. * Returns the Light associated shadow generator if any.
  22745. * @return the associated shadow generator.
  22746. */
  22747. Light.prototype.getShadowGenerator = function () {
  22748. return this._shadowGenerator;
  22749. };
  22750. /**
  22751. * Returns a Vector3, the absolute light position in the World.
  22752. * @returns the world space position of the light
  22753. */
  22754. Light.prototype.getAbsolutePosition = function () {
  22755. return BABYLON.Vector3.Zero();
  22756. };
  22757. /**
  22758. * Specifies if the light will affect the passed mesh.
  22759. * @param mesh The mesh to test against the light
  22760. * @return true the mesh is affected otherwise, false.
  22761. */
  22762. Light.prototype.canAffectMesh = function (mesh) {
  22763. if (!mesh) {
  22764. return true;
  22765. }
  22766. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22767. return false;
  22768. }
  22769. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22770. return false;
  22771. }
  22772. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22773. return false;
  22774. }
  22775. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22776. return false;
  22777. }
  22778. return true;
  22779. };
  22780. /**
  22781. * Sort function to order lights for rendering.
  22782. * @param a First Light object to compare to second.
  22783. * @param b Second Light object to compare first.
  22784. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22785. */
  22786. Light.CompareLightsPriority = function (a, b) {
  22787. //shadow-casting lights have priority over non-shadow-casting lights
  22788. //the renderPrioirty is a secondary sort criterion
  22789. if (a.shadowEnabled !== b.shadowEnabled) {
  22790. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22791. }
  22792. return b.renderPriority - a.renderPriority;
  22793. };
  22794. /**
  22795. * Releases resources associated with this node.
  22796. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22797. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22798. */
  22799. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22800. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22801. if (this._shadowGenerator) {
  22802. this._shadowGenerator.dispose();
  22803. this._shadowGenerator = null;
  22804. }
  22805. // Animations
  22806. this.getScene().stopAnimation(this);
  22807. // Remove from meshes
  22808. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22809. var mesh = _a[_i];
  22810. mesh._removeLightSource(this);
  22811. }
  22812. this._uniformBuffer.dispose();
  22813. // Remove from scene
  22814. this.getScene().removeLight(this);
  22815. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22816. };
  22817. /**
  22818. * Returns the light type ID (integer).
  22819. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22820. */
  22821. Light.prototype.getTypeID = function () {
  22822. return 0;
  22823. };
  22824. /**
  22825. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22826. * @returns the scaled intensity in intensity mode unit
  22827. */
  22828. Light.prototype.getScaledIntensity = function () {
  22829. return this._photometricScale * this.intensity;
  22830. };
  22831. /**
  22832. * Returns a new Light object, named "name", from the current one.
  22833. * @param name The name of the cloned light
  22834. * @returns the new created light
  22835. */
  22836. Light.prototype.clone = function (name) {
  22837. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22838. if (!constructor) {
  22839. return null;
  22840. }
  22841. return BABYLON.SerializationHelper.Clone(constructor, this);
  22842. };
  22843. /**
  22844. * Serializes the current light into a Serialization object.
  22845. * @returns the serialized object.
  22846. */
  22847. Light.prototype.serialize = function () {
  22848. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22849. // Type
  22850. serializationObject.type = this.getTypeID();
  22851. // Parent
  22852. if (this.parent) {
  22853. serializationObject.parentId = this.parent.id;
  22854. }
  22855. // Inclusion / exclusions
  22856. if (this.excludedMeshes.length > 0) {
  22857. serializationObject.excludedMeshesIds = [];
  22858. this.excludedMeshes.forEach(function (mesh) {
  22859. serializationObject.excludedMeshesIds.push(mesh.id);
  22860. });
  22861. }
  22862. if (this.includedOnlyMeshes.length > 0) {
  22863. serializationObject.includedOnlyMeshesIds = [];
  22864. this.includedOnlyMeshes.forEach(function (mesh) {
  22865. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22866. });
  22867. }
  22868. // Animations
  22869. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22870. serializationObject.ranges = this.serializeAnimationRanges();
  22871. return serializationObject;
  22872. };
  22873. /**
  22874. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22875. * This new light is named "name" and added to the passed scene.
  22876. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22877. * @param name The friendly name of the light
  22878. * @param scene The scene the new light will belong to
  22879. * @returns the constructor function
  22880. */
  22881. Light.GetConstructorFromName = function (type, name, scene) {
  22882. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22883. if (constructorFunc) {
  22884. return constructorFunc;
  22885. }
  22886. // Default to no light for none present once.
  22887. return null;
  22888. };
  22889. /**
  22890. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22891. * @param parsedLight The JSON representation of the light
  22892. * @param scene The scene to create the parsed light in
  22893. * @returns the created light after parsing
  22894. */
  22895. Light.Parse = function (parsedLight, scene) {
  22896. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22897. if (!constructor) {
  22898. return null;
  22899. }
  22900. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22901. // Inclusion / exclusions
  22902. if (parsedLight.excludedMeshesIds) {
  22903. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22904. }
  22905. if (parsedLight.includedOnlyMeshesIds) {
  22906. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22907. }
  22908. // Parent
  22909. if (parsedLight.parentId) {
  22910. light._waitingParentId = parsedLight.parentId;
  22911. }
  22912. // Animations
  22913. if (parsedLight.animations) {
  22914. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22915. var parsedAnimation = parsedLight.animations[animationIndex];
  22916. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22917. }
  22918. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22919. }
  22920. if (parsedLight.autoAnimate) {
  22921. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22922. }
  22923. return light;
  22924. };
  22925. Light.prototype._hookArrayForExcluded = function (array) {
  22926. var _this = this;
  22927. var oldPush = array.push;
  22928. array.push = function () {
  22929. var items = [];
  22930. for (var _i = 0; _i < arguments.length; _i++) {
  22931. items[_i] = arguments[_i];
  22932. }
  22933. var result = oldPush.apply(array, items);
  22934. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22935. var item = items_1[_a];
  22936. item._resyncLighSource(_this);
  22937. }
  22938. return result;
  22939. };
  22940. var oldSplice = array.splice;
  22941. array.splice = function (index, deleteCount) {
  22942. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22943. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22944. var item = deleted_1[_i];
  22945. item._resyncLighSource(_this);
  22946. }
  22947. return deleted;
  22948. };
  22949. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22950. var item = array_1[_i];
  22951. item._resyncLighSource(this);
  22952. }
  22953. };
  22954. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22955. var _this = this;
  22956. var oldPush = array.push;
  22957. array.push = function () {
  22958. var items = [];
  22959. for (var _i = 0; _i < arguments.length; _i++) {
  22960. items[_i] = arguments[_i];
  22961. }
  22962. var result = oldPush.apply(array, items);
  22963. _this._resyncMeshes();
  22964. return result;
  22965. };
  22966. var oldSplice = array.splice;
  22967. array.splice = function (index, deleteCount) {
  22968. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22969. _this._resyncMeshes();
  22970. return deleted;
  22971. };
  22972. this._resyncMeshes();
  22973. };
  22974. Light.prototype._resyncMeshes = function () {
  22975. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22976. var mesh = _a[_i];
  22977. mesh._resyncLighSource(this);
  22978. }
  22979. };
  22980. /**
  22981. * Forces the meshes to update their light related information in their rendering used effects
  22982. * @hidden Internal Use Only
  22983. */
  22984. Light.prototype._markMeshesAsLightDirty = function () {
  22985. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22986. var mesh = _a[_i];
  22987. if (mesh._lightSources.indexOf(this) !== -1) {
  22988. mesh._markSubMeshesAsLightDirty();
  22989. }
  22990. }
  22991. };
  22992. /**
  22993. * Recomputes the cached photometric scale if needed.
  22994. */
  22995. Light.prototype._computePhotometricScale = function () {
  22996. this._photometricScale = this._getPhotometricScale();
  22997. this.getScene().resetCachedMaterial();
  22998. };
  22999. /**
  23000. * Returns the Photometric Scale according to the light type and intensity mode.
  23001. */
  23002. Light.prototype._getPhotometricScale = function () {
  23003. var photometricScale = 0.0;
  23004. var lightTypeID = this.getTypeID();
  23005. //get photometric mode
  23006. var photometricMode = this.intensityMode;
  23007. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23008. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23009. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23010. }
  23011. else {
  23012. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23013. }
  23014. }
  23015. //compute photometric scale
  23016. switch (lightTypeID) {
  23017. case Light.LIGHTTYPEID_POINTLIGHT:
  23018. case Light.LIGHTTYPEID_SPOTLIGHT:
  23019. switch (photometricMode) {
  23020. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23021. photometricScale = 1.0 / (4.0 * Math.PI);
  23022. break;
  23023. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23024. photometricScale = 1.0;
  23025. break;
  23026. case Light.INTENSITYMODE_LUMINANCE:
  23027. photometricScale = this.radius * this.radius;
  23028. break;
  23029. }
  23030. break;
  23031. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23032. switch (photometricMode) {
  23033. case Light.INTENSITYMODE_ILLUMINANCE:
  23034. photometricScale = 1.0;
  23035. break;
  23036. case Light.INTENSITYMODE_LUMINANCE:
  23037. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23038. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23039. var apexAngleRadians = this.radius;
  23040. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23041. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23042. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23043. photometricScale = solidAngle;
  23044. break;
  23045. }
  23046. break;
  23047. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23048. // No fall off in hemisperic light.
  23049. photometricScale = 1.0;
  23050. break;
  23051. }
  23052. return photometricScale;
  23053. };
  23054. /**
  23055. * Reorder the light in the scene according to their defined priority.
  23056. * @hidden Internal Use Only
  23057. */
  23058. Light.prototype._reorderLightsInScene = function () {
  23059. var scene = this.getScene();
  23060. if (this._renderPriority != 0) {
  23061. scene.requireLightSorting = true;
  23062. }
  23063. this.getScene().sortLightsByPriority();
  23064. };
  23065. /**
  23066. * Falloff Default: light is falling off following the material specification:
  23067. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23068. */
  23069. Light.FALLOFF_DEFAULT = 0;
  23070. /**
  23071. * Falloff Physical: light is falling off following the inverse squared distance law.
  23072. */
  23073. Light.FALLOFF_PHYSICAL = 1;
  23074. /**
  23075. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23076. * to enhance interoperability with other engines.
  23077. */
  23078. Light.FALLOFF_GLTF = 2;
  23079. /**
  23080. * Falloff Standard: light is falling off like in the standard material
  23081. * to enhance interoperability with other materials.
  23082. */
  23083. Light.FALLOFF_STANDARD = 3;
  23084. //lightmapMode Consts
  23085. /**
  23086. * If every light affecting the material is in this lightmapMode,
  23087. * material.lightmapTexture adds or multiplies
  23088. * (depends on material.useLightmapAsShadowmap)
  23089. * after every other light calculations.
  23090. */
  23091. Light.LIGHTMAP_DEFAULT = 0;
  23092. /**
  23093. * material.lightmapTexture as only diffuse lighting from this light
  23094. * adds only specular lighting from this light
  23095. * adds dynamic shadows
  23096. */
  23097. Light.LIGHTMAP_SPECULAR = 1;
  23098. /**
  23099. * material.lightmapTexture as only lighting
  23100. * no light calculation from this light
  23101. * only adds dynamic shadows from this light
  23102. */
  23103. Light.LIGHTMAP_SHADOWSONLY = 2;
  23104. // Intensity Mode Consts
  23105. /**
  23106. * Each light type uses the default quantity according to its type:
  23107. * point/spot lights use luminous intensity
  23108. * directional lights use illuminance
  23109. */
  23110. Light.INTENSITYMODE_AUTOMATIC = 0;
  23111. /**
  23112. * lumen (lm)
  23113. */
  23114. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23115. /**
  23116. * candela (lm/sr)
  23117. */
  23118. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23119. /**
  23120. * lux (lm/m^2)
  23121. */
  23122. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23123. /**
  23124. * nit (cd/m^2)
  23125. */
  23126. Light.INTENSITYMODE_LUMINANCE = 4;
  23127. // Light types ids const.
  23128. /**
  23129. * Light type const id of the point light.
  23130. */
  23131. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23132. /**
  23133. * Light type const id of the directional light.
  23134. */
  23135. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23136. /**
  23137. * Light type const id of the spot light.
  23138. */
  23139. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23140. /**
  23141. * Light type const id of the hemispheric light.
  23142. */
  23143. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23144. __decorate([
  23145. BABYLON.serializeAsColor3()
  23146. ], Light.prototype, "diffuse", void 0);
  23147. __decorate([
  23148. BABYLON.serializeAsColor3()
  23149. ], Light.prototype, "specular", void 0);
  23150. __decorate([
  23151. BABYLON.serialize()
  23152. ], Light.prototype, "falloffType", void 0);
  23153. __decorate([
  23154. BABYLON.serialize()
  23155. ], Light.prototype, "intensity", void 0);
  23156. __decorate([
  23157. BABYLON.serialize()
  23158. ], Light.prototype, "range", null);
  23159. __decorate([
  23160. BABYLON.serialize()
  23161. ], Light.prototype, "intensityMode", null);
  23162. __decorate([
  23163. BABYLON.serialize()
  23164. ], Light.prototype, "radius", null);
  23165. __decorate([
  23166. BABYLON.serialize()
  23167. ], Light.prototype, "_renderPriority", void 0);
  23168. __decorate([
  23169. BABYLON.expandToProperty("_reorderLightsInScene")
  23170. ], Light.prototype, "renderPriority", void 0);
  23171. __decorate([
  23172. BABYLON.serialize("shadowEnabled")
  23173. ], Light.prototype, "_shadowEnabled", void 0);
  23174. __decorate([
  23175. BABYLON.serialize("excludeWithLayerMask")
  23176. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23177. __decorate([
  23178. BABYLON.serialize("includeOnlyWithLayerMask")
  23179. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23180. __decorate([
  23181. BABYLON.serialize("lightmapMode")
  23182. ], Light.prototype, "_lightmapMode", void 0);
  23183. return Light;
  23184. }(BABYLON.Node));
  23185. BABYLON.Light = Light;
  23186. })(BABYLON || (BABYLON = {}));
  23187. //# sourceMappingURL=babylon.light.js.map
  23188. var BABYLON;
  23189. (function (BABYLON) {
  23190. /**
  23191. * This is the base class of all the camera used in the application.
  23192. * @see http://doc.babylonjs.com/features/cameras
  23193. */
  23194. var Camera = /** @class */ (function (_super) {
  23195. __extends(Camera, _super);
  23196. /**
  23197. * Instantiates a new camera object.
  23198. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23199. * @see http://doc.babylonjs.com/features/cameras
  23200. * @param name Defines the name of the camera in the scene
  23201. * @param position Defines the position of the camera
  23202. * @param scene Defines the scene the camera belongs too
  23203. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23204. */
  23205. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23206. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23207. var _this = _super.call(this, name, scene) || this;
  23208. /**
  23209. * The vector the camera should consider as up.
  23210. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23211. */
  23212. _this.upVector = BABYLON.Vector3.Up();
  23213. /**
  23214. * Define the current limit on the left side for an orthographic camera
  23215. * In scene unit
  23216. */
  23217. _this.orthoLeft = null;
  23218. /**
  23219. * Define the current limit on the right side for an orthographic camera
  23220. * In scene unit
  23221. */
  23222. _this.orthoRight = null;
  23223. /**
  23224. * Define the current limit on the bottom side for an orthographic camera
  23225. * In scene unit
  23226. */
  23227. _this.orthoBottom = null;
  23228. /**
  23229. * Define the current limit on the top side for an orthographic camera
  23230. * In scene unit
  23231. */
  23232. _this.orthoTop = null;
  23233. /**
  23234. * Field Of View is set in Radians. (default is 0.8)
  23235. */
  23236. _this.fov = 0.8;
  23237. /**
  23238. * Define the minimum distance the camera can see from.
  23239. * This is important to note that the depth buffer are not infinite and the closer it starts
  23240. * the more your scene might encounter depth fighting issue.
  23241. */
  23242. _this.minZ = 1;
  23243. /**
  23244. * Define the maximum distance the camera can see to.
  23245. * This is important to note that the depth buffer are not infinite and the further it end
  23246. * the more your scene might encounter depth fighting issue.
  23247. */
  23248. _this.maxZ = 10000.0;
  23249. /**
  23250. * Define the default inertia of the camera.
  23251. * This helps giving a smooth feeling to the camera movement.
  23252. */
  23253. _this.inertia = 0.9;
  23254. /**
  23255. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23256. */
  23257. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23258. /**
  23259. * Define wether the camera is intermediate.
  23260. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23261. */
  23262. _this.isIntermediate = false;
  23263. /**
  23264. * Define the viewport of the camera.
  23265. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23266. */
  23267. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23268. /**
  23269. * Restricts the camera to viewing objects with the same layerMask.
  23270. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23271. */
  23272. _this.layerMask = 0x0FFFFFFF;
  23273. /**
  23274. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23275. */
  23276. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23277. /**
  23278. * Rig mode of the camera.
  23279. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23280. * This is normally controlled byt the camera themselves as internal use.
  23281. */
  23282. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23283. /**
  23284. * Defines the list of custom render target the camera should render to.
  23285. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23286. * else in the scene.
  23287. */
  23288. _this.customRenderTargets = new Array();
  23289. /**
  23290. * Observable triggered when the camera view matrix has changed.
  23291. */
  23292. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23293. /**
  23294. * Observable triggered when the camera Projection matrix has changed.
  23295. */
  23296. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23297. /**
  23298. * Observable triggered when the inputs have been processed.
  23299. */
  23300. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23301. /**
  23302. * Observable triggered when reset has been called and applied to the camera.
  23303. */
  23304. _this.onRestoreStateObservable = new BABYLON.Observable();
  23305. /** @hidden */
  23306. _this._rigCameras = new Array();
  23307. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23308. /** @hidden */
  23309. _this._skipRendering = false;
  23310. /** @hidden */
  23311. _this._projectionMatrix = new BABYLON.Matrix();
  23312. /** @hidden */
  23313. _this._postProcesses = new Array();
  23314. /** @hidden */
  23315. _this._activeMeshes = new BABYLON.SmartArray(256);
  23316. _this._globalPosition = BABYLON.Vector3.Zero();
  23317. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23318. _this._doNotComputeProjectionMatrix = false;
  23319. _this._transformMatrix = BABYLON.Matrix.Zero();
  23320. _this._refreshFrustumPlanes = true;
  23321. _this.getScene().addCamera(_this);
  23322. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23323. _this.getScene().activeCamera = _this;
  23324. }
  23325. _this.position = position;
  23326. return _this;
  23327. }
  23328. /**
  23329. * Store current camera state (fov, position, etc..)
  23330. * @returns the camera
  23331. */
  23332. Camera.prototype.storeState = function () {
  23333. this._stateStored = true;
  23334. this._storedFov = this.fov;
  23335. return this;
  23336. };
  23337. /**
  23338. * Restores the camera state values if it has been stored. You must call storeState() first
  23339. */
  23340. Camera.prototype._restoreStateValues = function () {
  23341. if (!this._stateStored) {
  23342. return false;
  23343. }
  23344. this.fov = this._storedFov;
  23345. return true;
  23346. };
  23347. /**
  23348. * Restored camera state. You must call storeState() first.
  23349. * @returns true if restored and false otherwise
  23350. */
  23351. Camera.prototype.restoreState = function () {
  23352. if (this._restoreStateValues()) {
  23353. this.onRestoreStateObservable.notifyObservers(this);
  23354. return true;
  23355. }
  23356. return false;
  23357. };
  23358. /**
  23359. * Gets the class name of the camera.
  23360. * @returns the class name
  23361. */
  23362. Camera.prototype.getClassName = function () {
  23363. return "Camera";
  23364. };
  23365. /**
  23366. * Gets a string representation of the camera usefull for debug purpose.
  23367. * @param fullDetails Defines that a more verboe level of logging is required
  23368. * @returns the string representation
  23369. */
  23370. Camera.prototype.toString = function (fullDetails) {
  23371. var ret = "Name: " + this.name;
  23372. ret += ", type: " + this.getClassName();
  23373. if (this.animations) {
  23374. for (var i = 0; i < this.animations.length; i++) {
  23375. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23376. }
  23377. }
  23378. if (fullDetails) {
  23379. }
  23380. return ret;
  23381. };
  23382. Object.defineProperty(Camera.prototype, "globalPosition", {
  23383. /**
  23384. * Gets the current world space position of the camera.
  23385. */
  23386. get: function () {
  23387. return this._globalPosition;
  23388. },
  23389. enumerable: true,
  23390. configurable: true
  23391. });
  23392. /**
  23393. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23394. * @returns the active meshe list
  23395. */
  23396. Camera.prototype.getActiveMeshes = function () {
  23397. return this._activeMeshes;
  23398. };
  23399. /**
  23400. * Check wether a mesh is part of the current active mesh list of the camera
  23401. * @param mesh Defines the mesh to check
  23402. * @returns true if active, false otherwise
  23403. */
  23404. Camera.prototype.isActiveMesh = function (mesh) {
  23405. return (this._activeMeshes.indexOf(mesh) !== -1);
  23406. };
  23407. /**
  23408. * Is this camera ready to be used/rendered
  23409. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23410. * @return true if the camera is ready
  23411. */
  23412. Camera.prototype.isReady = function (completeCheck) {
  23413. if (completeCheck === void 0) { completeCheck = false; }
  23414. if (completeCheck) {
  23415. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23416. var pp = _a[_i];
  23417. if (pp && !pp.isReady()) {
  23418. return false;
  23419. }
  23420. }
  23421. }
  23422. return _super.prototype.isReady.call(this, completeCheck);
  23423. };
  23424. /** @hidden */
  23425. Camera.prototype._initCache = function () {
  23426. _super.prototype._initCache.call(this);
  23427. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23428. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23429. this._cache.mode = undefined;
  23430. this._cache.minZ = undefined;
  23431. this._cache.maxZ = undefined;
  23432. this._cache.fov = undefined;
  23433. this._cache.fovMode = undefined;
  23434. this._cache.aspectRatio = undefined;
  23435. this._cache.orthoLeft = undefined;
  23436. this._cache.orthoRight = undefined;
  23437. this._cache.orthoBottom = undefined;
  23438. this._cache.orthoTop = undefined;
  23439. this._cache.renderWidth = undefined;
  23440. this._cache.renderHeight = undefined;
  23441. };
  23442. /** @hidden */
  23443. Camera.prototype._updateCache = function (ignoreParentClass) {
  23444. if (!ignoreParentClass) {
  23445. _super.prototype._updateCache.call(this);
  23446. }
  23447. this._cache.position.copyFrom(this.position);
  23448. this._cache.upVector.copyFrom(this.upVector);
  23449. };
  23450. /** @hidden */
  23451. Camera.prototype._isSynchronized = function () {
  23452. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23453. };
  23454. /** @hidden */
  23455. Camera.prototype._isSynchronizedViewMatrix = function () {
  23456. if (!_super.prototype._isSynchronized.call(this)) {
  23457. return false;
  23458. }
  23459. return this._cache.position.equals(this.position)
  23460. && this._cache.upVector.equals(this.upVector)
  23461. && this.isSynchronizedWithParent();
  23462. };
  23463. /** @hidden */
  23464. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23465. var check = this._cache.mode === this.mode
  23466. && this._cache.minZ === this.minZ
  23467. && this._cache.maxZ === this.maxZ;
  23468. if (!check) {
  23469. return false;
  23470. }
  23471. var engine = this.getEngine();
  23472. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23473. check = this._cache.fov === this.fov
  23474. && this._cache.fovMode === this.fovMode
  23475. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23476. }
  23477. else {
  23478. check = this._cache.orthoLeft === this.orthoLeft
  23479. && this._cache.orthoRight === this.orthoRight
  23480. && this._cache.orthoBottom === this.orthoBottom
  23481. && this._cache.orthoTop === this.orthoTop
  23482. && this._cache.renderWidth === engine.getRenderWidth()
  23483. && this._cache.renderHeight === engine.getRenderHeight();
  23484. }
  23485. return check;
  23486. };
  23487. /**
  23488. * Attach the input controls to a specific dom element to get the input from.
  23489. * @param element Defines the element the controls should be listened from
  23490. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23491. */
  23492. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23493. };
  23494. /**
  23495. * Detach the current controls from the specified dom element.
  23496. * @param element Defines the element to stop listening the inputs from
  23497. */
  23498. Camera.prototype.detachControl = function (element) {
  23499. };
  23500. /**
  23501. * Update the camera state according to the different inputs gathered during the frame.
  23502. */
  23503. Camera.prototype.update = function () {
  23504. this._checkInputs();
  23505. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23506. this._updateRigCameras();
  23507. }
  23508. };
  23509. /** @hidden */
  23510. Camera.prototype._checkInputs = function () {
  23511. this.onAfterCheckInputsObservable.notifyObservers(this);
  23512. };
  23513. Object.defineProperty(Camera.prototype, "rigCameras", {
  23514. /** @hidden */
  23515. get: function () {
  23516. return this._rigCameras;
  23517. },
  23518. enumerable: true,
  23519. configurable: true
  23520. });
  23521. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23522. /**
  23523. * Gets the post process used by the rig cameras
  23524. */
  23525. get: function () {
  23526. return this._rigPostProcess;
  23527. },
  23528. enumerable: true,
  23529. configurable: true
  23530. });
  23531. /**
  23532. * Internal, gets the first post proces.
  23533. * @returns the first post process to be run on this camera.
  23534. */
  23535. Camera.prototype._getFirstPostProcess = function () {
  23536. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23537. if (this._postProcesses[ppIndex] !== null) {
  23538. return this._postProcesses[ppIndex];
  23539. }
  23540. }
  23541. return null;
  23542. };
  23543. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23544. // invalidate framebuffer
  23545. var firstPostProcess = this._getFirstPostProcess();
  23546. if (firstPostProcess) {
  23547. firstPostProcess.markTextureDirty();
  23548. }
  23549. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23550. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23551. var cam = this._rigCameras[i];
  23552. var rigPostProcess = cam._rigPostProcess;
  23553. // for VR rig, there does not have to be a post process
  23554. if (rigPostProcess) {
  23555. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23556. if (isPass) {
  23557. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23558. cam.isIntermediate = this._postProcesses.length === 0;
  23559. }
  23560. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23561. rigPostProcess.markTextureDirty();
  23562. }
  23563. else {
  23564. cam._postProcesses = this._postProcesses.slice(0);
  23565. }
  23566. }
  23567. };
  23568. /**
  23569. * Attach a post process to the camera.
  23570. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23571. * @param postProcess The post process to attach to the camera
  23572. * @param insertAt The position of the post process in case several of them are in use in the scene
  23573. * @returns the position the post process has been inserted at
  23574. */
  23575. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23576. if (insertAt === void 0) { insertAt = null; }
  23577. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23578. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23579. return 0;
  23580. }
  23581. if (insertAt == null || insertAt < 0) {
  23582. this._postProcesses.push(postProcess);
  23583. }
  23584. else if (this._postProcesses[insertAt] === null) {
  23585. this._postProcesses[insertAt] = postProcess;
  23586. }
  23587. else {
  23588. this._postProcesses.splice(insertAt, 0, postProcess);
  23589. }
  23590. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23591. return this._postProcesses.indexOf(postProcess);
  23592. };
  23593. /**
  23594. * Detach a post process to the camera.
  23595. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23596. * @param postProcess The post process to detach from the camera
  23597. */
  23598. Camera.prototype.detachPostProcess = function (postProcess) {
  23599. var idx = this._postProcesses.indexOf(postProcess);
  23600. if (idx !== -1) {
  23601. this._postProcesses[idx] = null;
  23602. }
  23603. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23604. };
  23605. /**
  23606. * Gets the current world matrix of the camera
  23607. */
  23608. Camera.prototype.getWorldMatrix = function () {
  23609. if (this._isSynchronizedViewMatrix()) {
  23610. return this._worldMatrix;
  23611. }
  23612. // Getting the the view matrix will also compute the world matrix.
  23613. this.getViewMatrix();
  23614. return this._worldMatrix;
  23615. };
  23616. /** @hidden */
  23617. Camera.prototype._getViewMatrix = function () {
  23618. return BABYLON.Matrix.Identity();
  23619. };
  23620. /**
  23621. * Gets the current view matrix of the camera.
  23622. * @param force forces the camera to recompute the matrix without looking at the cached state
  23623. * @returns the view matrix
  23624. */
  23625. Camera.prototype.getViewMatrix = function (force) {
  23626. if (!force && this._isSynchronizedViewMatrix()) {
  23627. return this._computedViewMatrix;
  23628. }
  23629. this.updateCache();
  23630. this._computedViewMatrix = this._getViewMatrix();
  23631. this._currentRenderId = this.getScene().getRenderId();
  23632. this._childRenderId = this._currentRenderId;
  23633. this._refreshFrustumPlanes = true;
  23634. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23635. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23636. }
  23637. this.onViewMatrixChangedObservable.notifyObservers(this);
  23638. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23639. return this._computedViewMatrix;
  23640. };
  23641. /**
  23642. * Freeze the projection matrix.
  23643. * It will prevent the cache check of the camera projection compute and can speed up perf
  23644. * if no parameter of the camera are meant to change
  23645. * @param projection Defines manually a projection if necessary
  23646. */
  23647. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23648. this._doNotComputeProjectionMatrix = true;
  23649. if (projection !== undefined) {
  23650. this._projectionMatrix = projection;
  23651. }
  23652. };
  23653. /**
  23654. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23655. */
  23656. Camera.prototype.unfreezeProjectionMatrix = function () {
  23657. this._doNotComputeProjectionMatrix = false;
  23658. };
  23659. /**
  23660. * Gets the current projection matrix of the camera.
  23661. * @param force forces the camera to recompute the matrix without looking at the cached state
  23662. * @returns the projection matrix
  23663. */
  23664. Camera.prototype.getProjectionMatrix = function (force) {
  23665. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23666. return this._projectionMatrix;
  23667. }
  23668. // Cache
  23669. this._cache.mode = this.mode;
  23670. this._cache.minZ = this.minZ;
  23671. this._cache.maxZ = this.maxZ;
  23672. // Matrix
  23673. this._refreshFrustumPlanes = true;
  23674. var engine = this.getEngine();
  23675. var scene = this.getScene();
  23676. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23677. this._cache.fov = this.fov;
  23678. this._cache.fovMode = this.fovMode;
  23679. this._cache.aspectRatio = engine.getAspectRatio(this);
  23680. if (this.minZ <= 0) {
  23681. this.minZ = 0.1;
  23682. }
  23683. if (scene.useRightHandedSystem) {
  23684. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23685. }
  23686. else {
  23687. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23688. }
  23689. }
  23690. else {
  23691. var halfWidth = engine.getRenderWidth() / 2.0;
  23692. var halfHeight = engine.getRenderHeight() / 2.0;
  23693. if (scene.useRightHandedSystem) {
  23694. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23695. }
  23696. else {
  23697. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23698. }
  23699. this._cache.orthoLeft = this.orthoLeft;
  23700. this._cache.orthoRight = this.orthoRight;
  23701. this._cache.orthoBottom = this.orthoBottom;
  23702. this._cache.orthoTop = this.orthoTop;
  23703. this._cache.renderWidth = engine.getRenderWidth();
  23704. this._cache.renderHeight = engine.getRenderHeight();
  23705. }
  23706. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23707. return this._projectionMatrix;
  23708. };
  23709. /**
  23710. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23711. * @returns a Matrix
  23712. */
  23713. Camera.prototype.getTransformationMatrix = function () {
  23714. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23715. return this._transformMatrix;
  23716. };
  23717. Camera.prototype._updateFrustumPlanes = function () {
  23718. if (!this._refreshFrustumPlanes) {
  23719. return;
  23720. }
  23721. this.getTransformationMatrix();
  23722. if (!this._frustumPlanes) {
  23723. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23724. }
  23725. else {
  23726. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23727. }
  23728. this._refreshFrustumPlanes = false;
  23729. };
  23730. /**
  23731. * Checks if a cullable object (mesh...) is in the camera frustum
  23732. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23733. * @param target The object to check
  23734. * @returns true if the object is in frustum otherwise false
  23735. */
  23736. Camera.prototype.isInFrustum = function (target) {
  23737. this._updateFrustumPlanes();
  23738. return target.isInFrustum(this._frustumPlanes);
  23739. };
  23740. /**
  23741. * Checks if a cullable object (mesh...) is in the camera frustum
  23742. * Unlike isInFrustum this cheks the full bounding box
  23743. * @param target The object to check
  23744. * @returns true if the object is in frustum otherwise false
  23745. */
  23746. Camera.prototype.isCompletelyInFrustum = function (target) {
  23747. this._updateFrustumPlanes();
  23748. return target.isCompletelyInFrustum(this._frustumPlanes);
  23749. };
  23750. /**
  23751. * Gets a ray in the forward direction from the camera.
  23752. * @param length Defines the length of the ray to create
  23753. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23754. * @param origin Defines the start point of the ray which defaults to the camera position
  23755. * @returns the forward ray
  23756. */
  23757. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23758. if (length === void 0) { length = 100; }
  23759. if (!transform) {
  23760. transform = this.getWorldMatrix();
  23761. }
  23762. if (!origin) {
  23763. origin = this.position;
  23764. }
  23765. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23766. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23767. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23768. return new BABYLON.Ray(origin, direction, length);
  23769. };
  23770. /**
  23771. * Releases resources associated with this node.
  23772. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23773. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23774. */
  23775. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23776. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23777. // Observables
  23778. this.onViewMatrixChangedObservable.clear();
  23779. this.onProjectionMatrixChangedObservable.clear();
  23780. this.onAfterCheckInputsObservable.clear();
  23781. this.onRestoreStateObservable.clear();
  23782. // Inputs
  23783. if (this.inputs) {
  23784. this.inputs.clear();
  23785. }
  23786. // Animations
  23787. this.getScene().stopAnimation(this);
  23788. // Remove from scene
  23789. this.getScene().removeCamera(this);
  23790. while (this._rigCameras.length > 0) {
  23791. var camera = this._rigCameras.pop();
  23792. if (camera) {
  23793. camera.dispose();
  23794. }
  23795. }
  23796. // Postprocesses
  23797. if (this._rigPostProcess) {
  23798. this._rigPostProcess.dispose(this);
  23799. this._rigPostProcess = null;
  23800. this._postProcesses = [];
  23801. }
  23802. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23803. this._rigPostProcess = null;
  23804. this._postProcesses = [];
  23805. }
  23806. else {
  23807. var i = this._postProcesses.length;
  23808. while (--i >= 0) {
  23809. var postProcess = this._postProcesses[i];
  23810. if (postProcess) {
  23811. postProcess.dispose(this);
  23812. }
  23813. }
  23814. }
  23815. // Render targets
  23816. var i = this.customRenderTargets.length;
  23817. while (--i >= 0) {
  23818. this.customRenderTargets[i].dispose();
  23819. }
  23820. this.customRenderTargets = [];
  23821. // Active Meshes
  23822. this._activeMeshes.dispose();
  23823. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23824. };
  23825. Object.defineProperty(Camera.prototype, "leftCamera", {
  23826. /**
  23827. * Gets the left camera of a rig setup in case of Rigged Camera
  23828. */
  23829. get: function () {
  23830. if (this._rigCameras.length < 1) {
  23831. return null;
  23832. }
  23833. return this._rigCameras[0];
  23834. },
  23835. enumerable: true,
  23836. configurable: true
  23837. });
  23838. Object.defineProperty(Camera.prototype, "rightCamera", {
  23839. /**
  23840. * Gets the right camera of a rig setup in case of Rigged Camera
  23841. */
  23842. get: function () {
  23843. if (this._rigCameras.length < 2) {
  23844. return null;
  23845. }
  23846. return this._rigCameras[1];
  23847. },
  23848. enumerable: true,
  23849. configurable: true
  23850. });
  23851. /**
  23852. * Gets the left camera target of a rig setup in case of Rigged Camera
  23853. * @returns the target position
  23854. */
  23855. Camera.prototype.getLeftTarget = function () {
  23856. if (this._rigCameras.length < 1) {
  23857. return null;
  23858. }
  23859. return this._rigCameras[0].getTarget();
  23860. };
  23861. /**
  23862. * Gets the right camera target of a rig setup in case of Rigged Camera
  23863. * @returns the target position
  23864. */
  23865. Camera.prototype.getRightTarget = function () {
  23866. if (this._rigCameras.length < 2) {
  23867. return null;
  23868. }
  23869. return this._rigCameras[1].getTarget();
  23870. };
  23871. /**
  23872. * @hidden
  23873. */
  23874. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23875. if (this.cameraRigMode === mode) {
  23876. return;
  23877. }
  23878. while (this._rigCameras.length > 0) {
  23879. var camera = this._rigCameras.pop();
  23880. if (camera) {
  23881. camera.dispose();
  23882. }
  23883. }
  23884. this.cameraRigMode = mode;
  23885. this._cameraRigParams = {};
  23886. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23887. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23888. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23889. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23890. // create the rig cameras, unless none
  23891. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23892. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23893. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23894. if (leftCamera && rightCamera) {
  23895. this._rigCameras.push(leftCamera);
  23896. this._rigCameras.push(rightCamera);
  23897. }
  23898. }
  23899. switch (this.cameraRigMode) {
  23900. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23901. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23902. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23903. break;
  23904. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23905. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23906. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23907. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23908. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23909. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23910. break;
  23911. case Camera.RIG_MODE_VR:
  23912. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23913. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23914. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23915. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23916. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23917. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23918. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23919. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23920. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23921. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23922. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23923. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23924. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23925. if (metrics.compensateDistortion) {
  23926. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23927. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23928. }
  23929. break;
  23930. case Camera.RIG_MODE_WEBVR:
  23931. if (rigParams.vrDisplay) {
  23932. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23933. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23934. //Left eye
  23935. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23936. this._rigCameras[0].setCameraRigParameter("left", true);
  23937. //leaving this for future reference
  23938. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23939. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23940. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23941. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23942. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23943. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23944. this._rigCameras[0].parent = this;
  23945. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23946. //Right eye
  23947. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23948. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23949. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23950. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23951. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23952. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23953. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23954. this._rigCameras[1].parent = this;
  23955. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23956. if (Camera.UseAlternateWebVRRendering) {
  23957. this._rigCameras[1]._skipRendering = true;
  23958. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23959. }
  23960. }
  23961. break;
  23962. }
  23963. this._cascadePostProcessesToRigCams();
  23964. this.update();
  23965. };
  23966. Camera.prototype._getVRProjectionMatrix = function () {
  23967. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23968. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23969. return this._projectionMatrix;
  23970. };
  23971. Camera.prototype._updateCameraRotationMatrix = function () {
  23972. //Here for WebVR
  23973. };
  23974. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23975. //Here for WebVR
  23976. };
  23977. /**
  23978. * This function MUST be overwritten by the different WebVR cameras available.
  23979. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23980. */
  23981. Camera.prototype._getWebVRProjectionMatrix = function () {
  23982. return BABYLON.Matrix.Identity();
  23983. };
  23984. /**
  23985. * This function MUST be overwritten by the different WebVR cameras available.
  23986. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23987. */
  23988. Camera.prototype._getWebVRViewMatrix = function () {
  23989. return BABYLON.Matrix.Identity();
  23990. };
  23991. /** @hidden */
  23992. Camera.prototype.setCameraRigParameter = function (name, value) {
  23993. if (!this._cameraRigParams) {
  23994. this._cameraRigParams = {};
  23995. }
  23996. this._cameraRigParams[name] = value;
  23997. //provisionnally:
  23998. if (name === "interaxialDistance") {
  23999. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24000. }
  24001. };
  24002. /**
  24003. * needs to be overridden by children so sub has required properties to be copied
  24004. * @hidden
  24005. */
  24006. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24007. return null;
  24008. };
  24009. /**
  24010. * May need to be overridden by children
  24011. * @hidden
  24012. */
  24013. Camera.prototype._updateRigCameras = function () {
  24014. for (var i = 0; i < this._rigCameras.length; i++) {
  24015. this._rigCameras[i].minZ = this.minZ;
  24016. this._rigCameras[i].maxZ = this.maxZ;
  24017. this._rigCameras[i].fov = this.fov;
  24018. }
  24019. // only update viewport when ANAGLYPH
  24020. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24021. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24022. }
  24023. };
  24024. /** @hidden */
  24025. Camera.prototype._setupInputs = function () {
  24026. };
  24027. /**
  24028. * Serialiaze the camera setup to a json represention
  24029. * @returns the JSON representation
  24030. */
  24031. Camera.prototype.serialize = function () {
  24032. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24033. // Type
  24034. serializationObject.type = this.getClassName();
  24035. // Parent
  24036. if (this.parent) {
  24037. serializationObject.parentId = this.parent.id;
  24038. }
  24039. if (this.inputs) {
  24040. this.inputs.serialize(serializationObject);
  24041. }
  24042. // Animations
  24043. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24044. serializationObject.ranges = this.serializeAnimationRanges();
  24045. return serializationObject;
  24046. };
  24047. /**
  24048. * Clones the current camera.
  24049. * @param name The cloned camera name
  24050. * @returns the cloned camera
  24051. */
  24052. Camera.prototype.clone = function (name) {
  24053. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24054. };
  24055. /**
  24056. * Gets the direction of the camera relative to a given local axis.
  24057. * @param localAxis Defines the reference axis to provide a relative direction.
  24058. * @return the direction
  24059. */
  24060. Camera.prototype.getDirection = function (localAxis) {
  24061. var result = BABYLON.Vector3.Zero();
  24062. this.getDirectionToRef(localAxis, result);
  24063. return result;
  24064. };
  24065. /**
  24066. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24067. * @param localAxis Defines the reference axis to provide a relative direction.
  24068. * @param result Defines the vector to store the result in
  24069. */
  24070. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24071. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24072. };
  24073. /**
  24074. * Gets a camera constructor for a given camera type
  24075. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24076. * @param name The name of the camera the result will be able to instantiate
  24077. * @param scene The scene the result will construct the camera in
  24078. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24079. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24080. * @returns a factory method to construc the camera
  24081. */
  24082. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24083. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24084. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24085. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24086. interaxial_distance: interaxial_distance,
  24087. isStereoscopicSideBySide: isStereoscopicSideBySide
  24088. });
  24089. if (constructorFunc) {
  24090. return constructorFunc;
  24091. }
  24092. // Default to universal camera
  24093. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24094. };
  24095. /**
  24096. * Compute the world matrix of the camera.
  24097. * @returns the camera workd matrix
  24098. */
  24099. Camera.prototype.computeWorldMatrix = function () {
  24100. return this.getWorldMatrix();
  24101. };
  24102. /**
  24103. * Parse a JSON and creates the camera from the parsed information
  24104. * @param parsedCamera The JSON to parse
  24105. * @param scene The scene to instantiate the camera in
  24106. * @returns the newly constructed camera
  24107. */
  24108. Camera.Parse = function (parsedCamera, scene) {
  24109. var type = parsedCamera.type;
  24110. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24111. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24112. // Parent
  24113. if (parsedCamera.parentId) {
  24114. camera._waitingParentId = parsedCamera.parentId;
  24115. }
  24116. //If camera has an input manager, let it parse inputs settings
  24117. if (camera.inputs) {
  24118. camera.inputs.parse(parsedCamera);
  24119. camera._setupInputs();
  24120. }
  24121. if (camera.setPosition) { // need to force position
  24122. camera.position.copyFromFloats(0, 0, 0);
  24123. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24124. }
  24125. // Target
  24126. if (parsedCamera.target) {
  24127. if (camera.setTarget) {
  24128. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24129. }
  24130. }
  24131. // Apply 3d rig, when found
  24132. if (parsedCamera.cameraRigMode) {
  24133. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24134. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24135. }
  24136. // Animations
  24137. if (parsedCamera.animations) {
  24138. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24139. var parsedAnimation = parsedCamera.animations[animationIndex];
  24140. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24141. }
  24142. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24143. }
  24144. if (parsedCamera.autoAnimate) {
  24145. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24146. }
  24147. return camera;
  24148. };
  24149. /**
  24150. * This is the default projection mode used by the cameras.
  24151. * It helps recreating a feeling of perspective and better appreciate depth.
  24152. * This is the best way to simulate real life cameras.
  24153. */
  24154. Camera.PERSPECTIVE_CAMERA = 0;
  24155. /**
  24156. * This helps creating camera with an orthographic mode.
  24157. * 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.
  24158. */
  24159. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24160. /**
  24161. * This is the default FOV mode for perspective cameras.
  24162. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24163. */
  24164. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24165. /**
  24166. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24167. */
  24168. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24169. /**
  24170. * This specifies ther is no need for a camera rig.
  24171. * Basically only one eye is rendered corresponding to the camera.
  24172. */
  24173. Camera.RIG_MODE_NONE = 0;
  24174. /**
  24175. * Simulates a camera Rig with one blue eye and one red eye.
  24176. * This can be use with 3d blue and red glasses.
  24177. */
  24178. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24179. /**
  24180. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24181. */
  24182. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24183. /**
  24184. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24185. */
  24186. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24187. /**
  24188. * Defines that both eyes of the camera will be rendered over under each other.
  24189. */
  24190. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24191. /**
  24192. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24193. */
  24194. Camera.RIG_MODE_VR = 20;
  24195. /**
  24196. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24197. */
  24198. Camera.RIG_MODE_WEBVR = 21;
  24199. /**
  24200. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24201. */
  24202. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24203. /**
  24204. * @hidden
  24205. * Might be removed once multiview will be a thing
  24206. */
  24207. Camera.UseAlternateWebVRRendering = false;
  24208. __decorate([
  24209. BABYLON.serializeAsVector3()
  24210. ], Camera.prototype, "position", void 0);
  24211. __decorate([
  24212. BABYLON.serializeAsVector3()
  24213. ], Camera.prototype, "upVector", void 0);
  24214. __decorate([
  24215. BABYLON.serialize()
  24216. ], Camera.prototype, "orthoLeft", void 0);
  24217. __decorate([
  24218. BABYLON.serialize()
  24219. ], Camera.prototype, "orthoRight", void 0);
  24220. __decorate([
  24221. BABYLON.serialize()
  24222. ], Camera.prototype, "orthoBottom", void 0);
  24223. __decorate([
  24224. BABYLON.serialize()
  24225. ], Camera.prototype, "orthoTop", void 0);
  24226. __decorate([
  24227. BABYLON.serialize()
  24228. ], Camera.prototype, "fov", void 0);
  24229. __decorate([
  24230. BABYLON.serialize()
  24231. ], Camera.prototype, "minZ", void 0);
  24232. __decorate([
  24233. BABYLON.serialize()
  24234. ], Camera.prototype, "maxZ", void 0);
  24235. __decorate([
  24236. BABYLON.serialize()
  24237. ], Camera.prototype, "inertia", void 0);
  24238. __decorate([
  24239. BABYLON.serialize()
  24240. ], Camera.prototype, "mode", void 0);
  24241. __decorate([
  24242. BABYLON.serialize()
  24243. ], Camera.prototype, "layerMask", void 0);
  24244. __decorate([
  24245. BABYLON.serialize()
  24246. ], Camera.prototype, "fovMode", void 0);
  24247. __decorate([
  24248. BABYLON.serialize()
  24249. ], Camera.prototype, "cameraRigMode", void 0);
  24250. __decorate([
  24251. BABYLON.serialize()
  24252. ], Camera.prototype, "interaxialDistance", void 0);
  24253. __decorate([
  24254. BABYLON.serialize()
  24255. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24256. return Camera;
  24257. }(BABYLON.Node));
  24258. BABYLON.Camera = Camera;
  24259. })(BABYLON || (BABYLON = {}));
  24260. //# sourceMappingURL=babylon.camera.js.map
  24261. var BABYLON;
  24262. (function (BABYLON) {
  24263. /**
  24264. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24265. * It is enable to manage the different groups as well as the different necessary sort functions.
  24266. * This should not be used directly aside of the few static configurations
  24267. */
  24268. var RenderingManager = /** @class */ (function () {
  24269. /**
  24270. * Instantiates a new rendering group for a particular scene
  24271. * @param scene Defines the scene the groups belongs to
  24272. */
  24273. function RenderingManager(scene) {
  24274. /**
  24275. * @hidden
  24276. */
  24277. this._useSceneAutoClearSetup = false;
  24278. this._renderingGroups = new Array();
  24279. this._autoClearDepthStencil = {};
  24280. this._customOpaqueSortCompareFn = {};
  24281. this._customAlphaTestSortCompareFn = {};
  24282. this._customTransparentSortCompareFn = {};
  24283. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24284. this._scene = scene;
  24285. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24286. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24287. }
  24288. }
  24289. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24290. if (depth === void 0) { depth = true; }
  24291. if (stencil === void 0) { stencil = true; }
  24292. if (this._depthStencilBufferAlreadyCleaned) {
  24293. return;
  24294. }
  24295. this._scene.getEngine().clear(null, false, depth, stencil);
  24296. this._depthStencilBufferAlreadyCleaned = true;
  24297. };
  24298. /**
  24299. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24300. * @hidden
  24301. */
  24302. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24303. // Update the observable context (not null as it only goes away on dispose)
  24304. var info = this._renderingGroupInfo;
  24305. info.scene = this._scene;
  24306. info.camera = this._scene.activeCamera;
  24307. // Dispatch sprites
  24308. if (this._scene.spriteManagers && renderSprites) {
  24309. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24310. var manager = this._scene.spriteManagers[index];
  24311. this.dispatchSprites(manager);
  24312. }
  24313. }
  24314. // Render
  24315. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24316. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24317. var renderingGroup = this._renderingGroups[index];
  24318. if (!renderingGroup) {
  24319. continue;
  24320. }
  24321. var renderingGroupMask = Math.pow(2, index);
  24322. info.renderingGroupId = index;
  24323. // Before Observable
  24324. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24325. // Clear depth/stencil if needed
  24326. if (RenderingManager.AUTOCLEAR) {
  24327. var autoClear = this._useSceneAutoClearSetup ?
  24328. this._scene.getAutoClearDepthStencilSetup(index) :
  24329. this._autoClearDepthStencil[index];
  24330. if (autoClear && autoClear.autoClear) {
  24331. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24332. }
  24333. }
  24334. // Render
  24335. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24336. var step = _a[_i];
  24337. step.action(index);
  24338. }
  24339. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24340. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24341. var step = _c[_b];
  24342. step.action(index);
  24343. }
  24344. // After Observable
  24345. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24346. }
  24347. };
  24348. /**
  24349. * Resets the different information of the group to prepare a new frame
  24350. * @hidden
  24351. */
  24352. RenderingManager.prototype.reset = function () {
  24353. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24354. var renderingGroup = this._renderingGroups[index];
  24355. if (renderingGroup) {
  24356. renderingGroup.prepare();
  24357. }
  24358. }
  24359. };
  24360. /**
  24361. * Dispose and release the group and its associated resources.
  24362. * @hidden
  24363. */
  24364. RenderingManager.prototype.dispose = function () {
  24365. this.freeRenderingGroups();
  24366. this._renderingGroups.length = 0;
  24367. this._renderingGroupInfo = null;
  24368. };
  24369. /**
  24370. * Clear the info related to rendering groups preventing retention points during dispose.
  24371. */
  24372. RenderingManager.prototype.freeRenderingGroups = function () {
  24373. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24374. var renderingGroup = this._renderingGroups[index];
  24375. if (renderingGroup) {
  24376. renderingGroup.dispose();
  24377. }
  24378. }
  24379. };
  24380. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24381. if (this._renderingGroups[renderingGroupId] === undefined) {
  24382. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24383. }
  24384. };
  24385. /**
  24386. * Add a sprite manager to the rendering manager in order to render it this frame.
  24387. * @param spriteManager Define the sprite manager to render
  24388. */
  24389. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24390. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24391. this._prepareRenderingGroup(renderingGroupId);
  24392. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24393. };
  24394. /**
  24395. * Add a particle system to the rendering manager in order to render it this frame.
  24396. * @param particleSystem Define the particle system to render
  24397. */
  24398. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24399. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24400. this._prepareRenderingGroup(renderingGroupId);
  24401. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24402. };
  24403. /**
  24404. * Add a submesh to the manager in order to render it this frame
  24405. * @param subMesh The submesh to dispatch
  24406. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24407. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24408. */
  24409. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24410. if (mesh === undefined) {
  24411. mesh = subMesh.getMesh();
  24412. }
  24413. var renderingGroupId = mesh.renderingGroupId || 0;
  24414. this._prepareRenderingGroup(renderingGroupId);
  24415. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24416. };
  24417. /**
  24418. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24419. * This allowed control for front to back rendering or reversly depending of the special needs.
  24420. *
  24421. * @param renderingGroupId The rendering group id corresponding to its index
  24422. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24423. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24424. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24425. */
  24426. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24427. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24428. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24429. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24430. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24431. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24432. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24433. if (this._renderingGroups[renderingGroupId]) {
  24434. var group = this._renderingGroups[renderingGroupId];
  24435. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24436. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24437. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24438. }
  24439. };
  24440. /**
  24441. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24442. *
  24443. * @param renderingGroupId The rendering group id corresponding to its index
  24444. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24445. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24446. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24447. */
  24448. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24449. if (depth === void 0) { depth = true; }
  24450. if (stencil === void 0) { stencil = true; }
  24451. this._autoClearDepthStencil[renderingGroupId] = {
  24452. autoClear: autoClearDepthStencil,
  24453. depth: depth,
  24454. stencil: stencil
  24455. };
  24456. };
  24457. /**
  24458. * Gets the current auto clear configuration for one rendering group of the rendering
  24459. * manager.
  24460. * @param index the rendering group index to get the information for
  24461. * @returns The auto clear setup for the requested rendering group
  24462. */
  24463. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24464. return this._autoClearDepthStencil[index];
  24465. };
  24466. /**
  24467. * The max id used for rendering groups (not included)
  24468. */
  24469. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24470. /**
  24471. * The min id used for rendering groups (included)
  24472. */
  24473. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24474. /**
  24475. * Used to globally prevent autoclearing scenes.
  24476. */
  24477. RenderingManager.AUTOCLEAR = true;
  24478. return RenderingManager;
  24479. }());
  24480. BABYLON.RenderingManager = RenderingManager;
  24481. })(BABYLON || (BABYLON = {}));
  24482. //# sourceMappingURL=babylon.renderingManager.js.map
  24483. var BABYLON;
  24484. (function (BABYLON) {
  24485. /**
  24486. * This represents the object necessary to create a rendering group.
  24487. * This is exclusively used and created by the rendering manager.
  24488. * To modify the behavior, you use the available helpers in your scene or meshes.
  24489. * @hidden
  24490. */
  24491. var RenderingGroup = /** @class */ (function () {
  24492. /**
  24493. * Creates a new rendering group.
  24494. * @param index The rendering group index
  24495. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24496. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24497. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24498. */
  24499. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24500. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24501. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24502. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24503. this.index = index;
  24504. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24505. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24506. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24507. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24508. this._particleSystems = new BABYLON.SmartArray(256);
  24509. this._spriteManagers = new BABYLON.SmartArray(256);
  24510. this._edgesRenderers = new BABYLON.SmartArray(16);
  24511. this._scene = scene;
  24512. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24513. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24514. this.transparentSortCompareFn = transparentSortCompareFn;
  24515. }
  24516. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24517. /**
  24518. * Set the opaque sort comparison function.
  24519. * If null the sub meshes will be render in the order they were created
  24520. */
  24521. set: function (value) {
  24522. this._opaqueSortCompareFn = value;
  24523. if (value) {
  24524. this._renderOpaque = this.renderOpaqueSorted;
  24525. }
  24526. else {
  24527. this._renderOpaque = RenderingGroup.renderUnsorted;
  24528. }
  24529. },
  24530. enumerable: true,
  24531. configurable: true
  24532. });
  24533. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24534. /**
  24535. * Set the alpha test sort comparison function.
  24536. * If null the sub meshes will be render in the order they were created
  24537. */
  24538. set: function (value) {
  24539. this._alphaTestSortCompareFn = value;
  24540. if (value) {
  24541. this._renderAlphaTest = this.renderAlphaTestSorted;
  24542. }
  24543. else {
  24544. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24545. }
  24546. },
  24547. enumerable: true,
  24548. configurable: true
  24549. });
  24550. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24551. /**
  24552. * Set the transparent sort comparison function.
  24553. * If null the sub meshes will be render in the order they were created
  24554. */
  24555. set: function (value) {
  24556. if (value) {
  24557. this._transparentSortCompareFn = value;
  24558. }
  24559. else {
  24560. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24561. }
  24562. this._renderTransparent = this.renderTransparentSorted;
  24563. },
  24564. enumerable: true,
  24565. configurable: true
  24566. });
  24567. /**
  24568. * Render all the sub meshes contained in the group.
  24569. * @param customRenderFunction Used to override the default render behaviour of the group.
  24570. * @returns true if rendered some submeshes.
  24571. */
  24572. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24573. if (customRenderFunction) {
  24574. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24575. return;
  24576. }
  24577. var engine = this._scene.getEngine();
  24578. // Depth only
  24579. if (this._depthOnlySubMeshes.length !== 0) {
  24580. engine.setColorWrite(false);
  24581. this._renderAlphaTest(this._depthOnlySubMeshes);
  24582. engine.setColorWrite(true);
  24583. }
  24584. // Opaque
  24585. if (this._opaqueSubMeshes.length !== 0) {
  24586. this._renderOpaque(this._opaqueSubMeshes);
  24587. }
  24588. // Alpha test
  24589. if (this._alphaTestSubMeshes.length !== 0) {
  24590. this._renderAlphaTest(this._alphaTestSubMeshes);
  24591. }
  24592. var stencilState = engine.getStencilBuffer();
  24593. engine.setStencilBuffer(false);
  24594. // Sprites
  24595. if (renderSprites) {
  24596. this._renderSprites();
  24597. }
  24598. // Particles
  24599. if (renderParticles) {
  24600. this._renderParticles(activeMeshes);
  24601. }
  24602. if (this.onBeforeTransparentRendering) {
  24603. this.onBeforeTransparentRendering();
  24604. }
  24605. // Transparent
  24606. if (this._transparentSubMeshes.length !== 0) {
  24607. this._renderTransparent(this._transparentSubMeshes);
  24608. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24609. }
  24610. // Set back stencil to false in case it changes before the edge renderer.
  24611. engine.setStencilBuffer(false);
  24612. // Edges
  24613. if (this._edgesRenderers.length) {
  24614. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24615. this._edgesRenderers.data[edgesRendererIndex].render();
  24616. }
  24617. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24618. }
  24619. // Restore Stencil state.
  24620. engine.setStencilBuffer(stencilState);
  24621. };
  24622. /**
  24623. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24624. * @param subMeshes The submeshes to render
  24625. */
  24626. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24627. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24628. };
  24629. /**
  24630. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24631. * @param subMeshes The submeshes to render
  24632. */
  24633. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24634. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24635. };
  24636. /**
  24637. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24638. * @param subMeshes The submeshes to render
  24639. */
  24640. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24641. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24642. };
  24643. /**
  24644. * Renders the submeshes in a specified order.
  24645. * @param subMeshes The submeshes to sort before render
  24646. * @param sortCompareFn The comparison function use to sort
  24647. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24648. * @param transparent Specifies to activate blending if true
  24649. */
  24650. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24651. var subIndex = 0;
  24652. var subMesh;
  24653. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24654. for (; subIndex < subMeshes.length; subIndex++) {
  24655. subMesh = subMeshes.data[subIndex];
  24656. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24657. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24658. }
  24659. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24660. if (sortCompareFn) {
  24661. sortedArray.sort(sortCompareFn);
  24662. }
  24663. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24664. subMesh = sortedArray[subIndex];
  24665. if (transparent) {
  24666. var material = subMesh.getMaterial();
  24667. if (material && material.needDepthPrePass) {
  24668. var engine = material.getScene().getEngine();
  24669. engine.setColorWrite(false);
  24670. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24671. subMesh.render(false);
  24672. engine.setColorWrite(true);
  24673. }
  24674. }
  24675. subMesh.render(transparent);
  24676. }
  24677. };
  24678. /**
  24679. * Renders the submeshes in the order they were dispatched (no sort applied).
  24680. * @param subMeshes The submeshes to render
  24681. */
  24682. RenderingGroup.renderUnsorted = function (subMeshes) {
  24683. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24684. var submesh = subMeshes.data[subIndex];
  24685. submesh.render(false);
  24686. }
  24687. };
  24688. /**
  24689. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24690. * are rendered back to front if in the same alpha index.
  24691. *
  24692. * @param a The first submesh
  24693. * @param b The second submesh
  24694. * @returns The result of the comparison
  24695. */
  24696. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24697. // Alpha index first
  24698. if (a._alphaIndex > b._alphaIndex) {
  24699. return 1;
  24700. }
  24701. if (a._alphaIndex < b._alphaIndex) {
  24702. return -1;
  24703. }
  24704. // Then distance to camera
  24705. return RenderingGroup.backToFrontSortCompare(a, b);
  24706. };
  24707. /**
  24708. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24709. * are rendered back to front.
  24710. *
  24711. * @param a The first submesh
  24712. * @param b The second submesh
  24713. * @returns The result of the comparison
  24714. */
  24715. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24716. // Then distance to camera
  24717. if (a._distanceToCamera < b._distanceToCamera) {
  24718. return 1;
  24719. }
  24720. if (a._distanceToCamera > b._distanceToCamera) {
  24721. return -1;
  24722. }
  24723. return 0;
  24724. };
  24725. /**
  24726. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24727. * are rendered front to back (prevent overdraw).
  24728. *
  24729. * @param a The first submesh
  24730. * @param b The second submesh
  24731. * @returns The result of the comparison
  24732. */
  24733. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24734. // Then distance to camera
  24735. if (a._distanceToCamera < b._distanceToCamera) {
  24736. return -1;
  24737. }
  24738. if (a._distanceToCamera > b._distanceToCamera) {
  24739. return 1;
  24740. }
  24741. return 0;
  24742. };
  24743. /**
  24744. * Resets the different lists of submeshes to prepare a new frame.
  24745. */
  24746. RenderingGroup.prototype.prepare = function () {
  24747. this._opaqueSubMeshes.reset();
  24748. this._transparentSubMeshes.reset();
  24749. this._alphaTestSubMeshes.reset();
  24750. this._depthOnlySubMeshes.reset();
  24751. this._particleSystems.reset();
  24752. this._spriteManagers.reset();
  24753. this._edgesRenderers.reset();
  24754. };
  24755. RenderingGroup.prototype.dispose = function () {
  24756. this._opaqueSubMeshes.dispose();
  24757. this._transparentSubMeshes.dispose();
  24758. this._alphaTestSubMeshes.dispose();
  24759. this._depthOnlySubMeshes.dispose();
  24760. this._particleSystems.dispose();
  24761. this._spriteManagers.dispose();
  24762. this._edgesRenderers.dispose();
  24763. };
  24764. /**
  24765. * Inserts the submesh in its correct queue depending on its material.
  24766. * @param subMesh The submesh to dispatch
  24767. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24768. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24769. */
  24770. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24771. // Get mesh and materials if not provided
  24772. if (mesh === undefined) {
  24773. mesh = subMesh.getMesh();
  24774. }
  24775. if (material === undefined) {
  24776. material = subMesh.getMaterial();
  24777. }
  24778. if (material === null || material === undefined) {
  24779. return;
  24780. }
  24781. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24782. this._transparentSubMeshes.push(subMesh);
  24783. }
  24784. else if (material.needAlphaTesting()) { // Alpha test
  24785. if (material.needDepthPrePass) {
  24786. this._depthOnlySubMeshes.push(subMesh);
  24787. }
  24788. this._alphaTestSubMeshes.push(subMesh);
  24789. }
  24790. else {
  24791. if (material.needDepthPrePass) {
  24792. this._depthOnlySubMeshes.push(subMesh);
  24793. }
  24794. this._opaqueSubMeshes.push(subMesh); // Opaque
  24795. }
  24796. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24797. this._edgesRenderers.push(mesh._edgesRenderer);
  24798. }
  24799. };
  24800. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24801. this._spriteManagers.push(spriteManager);
  24802. };
  24803. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24804. this._particleSystems.push(particleSystem);
  24805. };
  24806. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24807. if (this._particleSystems.length === 0) {
  24808. return;
  24809. }
  24810. // Particles
  24811. var activeCamera = this._scene.activeCamera;
  24812. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24813. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24814. var particleSystem = this._particleSystems.data[particleIndex];
  24815. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24816. continue;
  24817. }
  24818. var emitter = particleSystem.emitter;
  24819. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24820. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24821. }
  24822. }
  24823. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24824. };
  24825. RenderingGroup.prototype._renderSprites = function () {
  24826. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24827. return;
  24828. }
  24829. // Sprites
  24830. var activeCamera = this._scene.activeCamera;
  24831. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24832. for (var id = 0; id < this._spriteManagers.length; id++) {
  24833. var spriteManager = this._spriteManagers.data[id];
  24834. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24835. spriteManager.render();
  24836. }
  24837. }
  24838. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24839. };
  24840. return RenderingGroup;
  24841. }());
  24842. BABYLON.RenderingGroup = RenderingGroup;
  24843. })(BABYLON || (BABYLON = {}));
  24844. //# sourceMappingURL=babylon.renderingGroup.js.map
  24845. var BABYLON;
  24846. (function (BABYLON) {
  24847. /**
  24848. * Groups all the scene component constants in one place to ease maintenance.
  24849. * @hidden
  24850. */
  24851. var SceneComponentConstants = /** @class */ (function () {
  24852. function SceneComponentConstants() {
  24853. }
  24854. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24855. SceneComponentConstants.NAME_LAYER = "Layer";
  24856. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24857. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24858. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24859. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24860. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24861. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24862. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24863. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24864. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24865. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24866. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24867. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24868. SceneComponentConstants.NAME_OCTREE = "Octree";
  24869. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24870. SceneComponentConstants.NAME_AUDIO = "Audio";
  24871. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24872. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24873. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24874. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24875. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24876. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24877. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24878. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24879. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24880. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24881. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24882. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24883. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24884. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24885. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24886. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24887. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24888. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24889. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24890. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24891. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24892. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24893. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24894. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24895. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24896. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24897. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24898. return SceneComponentConstants;
  24899. }());
  24900. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24901. /**
  24902. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24903. * @hidden
  24904. */
  24905. var Stage = /** @class */ (function (_super) {
  24906. __extends(Stage, _super);
  24907. /**
  24908. * Hide ctor from the rest of the world.
  24909. * @param items The items to add.
  24910. */
  24911. function Stage(items) {
  24912. return _super.apply(this, items) || this;
  24913. }
  24914. /**
  24915. * Creates a new Stage.
  24916. * @returns A new instance of a Stage
  24917. */
  24918. Stage.Create = function () {
  24919. return Object.create(Stage.prototype);
  24920. };
  24921. /**
  24922. * Registers a step in an ordered way in the targeted stage.
  24923. * @param index Defines the position to register the step in
  24924. * @param component Defines the component attached to the step
  24925. * @param action Defines the action to launch during the step
  24926. */
  24927. Stage.prototype.registerStep = function (index, component, action) {
  24928. var i = 0;
  24929. var maxIndex = Number.MAX_VALUE;
  24930. for (; i < this.length; i++) {
  24931. var step = this[i];
  24932. maxIndex = step.index;
  24933. if (index < maxIndex) {
  24934. break;
  24935. }
  24936. }
  24937. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24938. };
  24939. /**
  24940. * Clears all the steps from the stage.
  24941. */
  24942. Stage.prototype.clear = function () {
  24943. this.length = 0;
  24944. };
  24945. return Stage;
  24946. }(Array));
  24947. BABYLON.Stage = Stage;
  24948. })(BABYLON || (BABYLON = {}));
  24949. //# sourceMappingURL=babylon.sceneComponent.js.map
  24950. var BABYLON;
  24951. (function (BABYLON) {
  24952. /**
  24953. * Base class of the scene acting as a container for the different elements composing a scene.
  24954. * This class is dynamically extended by the different components of the scene increasing
  24955. * flexibility and reducing coupling
  24956. */
  24957. var AbstractScene = /** @class */ (function () {
  24958. function AbstractScene() {
  24959. /**
  24960. * Gets the list of root nodes (ie. nodes with no parent)
  24961. */
  24962. this.rootNodes = new Array();
  24963. /** All of the cameras added to this scene
  24964. * @see http://doc.babylonjs.com/babylon101/cameras
  24965. */
  24966. this.cameras = new Array();
  24967. /**
  24968. * All of the lights added to this scene
  24969. * @see http://doc.babylonjs.com/babylon101/lights
  24970. */
  24971. this.lights = new Array();
  24972. /**
  24973. * All of the (abstract) meshes added to this scene
  24974. */
  24975. this.meshes = new Array();
  24976. /**
  24977. * The list of skeletons added to the scene
  24978. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24979. */
  24980. this.skeletons = new Array();
  24981. /**
  24982. * All of the particle systems added to this scene
  24983. * @see http://doc.babylonjs.com/babylon101/particles
  24984. */
  24985. this.particleSystems = new Array();
  24986. /**
  24987. * Gets a list of Animations associated with the scene
  24988. */
  24989. this.animations = [];
  24990. /**
  24991. * All of the animation groups added to this scene
  24992. * @see http://doc.babylonjs.com/how_to/group
  24993. */
  24994. this.animationGroups = new Array();
  24995. /**
  24996. * All of the multi-materials added to this scene
  24997. * @see http://doc.babylonjs.com/how_to/multi_materials
  24998. */
  24999. this.multiMaterials = new Array();
  25000. /**
  25001. * All of the materials added to this scene
  25002. * @see http://doc.babylonjs.com/babylon101/materials
  25003. */
  25004. this.materials = new Array();
  25005. /**
  25006. * The list of morph target managers added to the scene
  25007. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25008. */
  25009. this.morphTargetManagers = new Array();
  25010. /**
  25011. * The list of geometries used in the scene.
  25012. */
  25013. this.geometries = new Array();
  25014. /**
  25015. * All of the tranform nodes added to this scene
  25016. * @see http://doc.babylonjs.com/how_to/transformnode
  25017. */
  25018. this.transformNodes = new Array();
  25019. /**
  25020. * ActionManagers available on the scene.
  25021. */
  25022. this.actionManagers = new Array();
  25023. /**
  25024. * Textures to keep.
  25025. */
  25026. this.textures = new Array();
  25027. }
  25028. /**
  25029. * Adds a parser in the list of available ones
  25030. * @param name Defines the name of the parser
  25031. * @param parser Defines the parser to add
  25032. */
  25033. AbstractScene.AddParser = function (name, parser) {
  25034. this._BabylonFileParsers[name] = parser;
  25035. };
  25036. /**
  25037. * Gets a general parser from the list of avaialble ones
  25038. * @param name Defines the name of the parser
  25039. * @returns the requested parser or null
  25040. */
  25041. AbstractScene.GetParser = function (name) {
  25042. if (this._BabylonFileParsers[name]) {
  25043. return this._BabylonFileParsers[name];
  25044. }
  25045. return null;
  25046. };
  25047. /**
  25048. * Adds n individual parser in the list of available ones
  25049. * @param name Defines the name of the parser
  25050. * @param parser Defines the parser to add
  25051. */
  25052. AbstractScene.AddIndividualParser = function (name, parser) {
  25053. this._IndividualBabylonFileParsers[name] = parser;
  25054. };
  25055. /**
  25056. * Gets an individual parser from the list of avaialble ones
  25057. * @param name Defines the name of the parser
  25058. * @returns the requested parser or null
  25059. */
  25060. AbstractScene.GetIndividualParser = function (name) {
  25061. if (this._IndividualBabylonFileParsers[name]) {
  25062. return this._IndividualBabylonFileParsers[name];
  25063. }
  25064. return null;
  25065. };
  25066. /**
  25067. * Parser json data and populate both a scene and its associated container object
  25068. * @param jsonData Defines the data to parse
  25069. * @param scene Defines the scene to parse the data for
  25070. * @param container Defines the container attached to the parsing sequence
  25071. * @param rootUrl Defines the root url of the data
  25072. */
  25073. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25074. for (var parserName in this._BabylonFileParsers) {
  25075. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25076. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25077. }
  25078. }
  25079. };
  25080. /**
  25081. * Stores the list of available parsers in the application.
  25082. */
  25083. AbstractScene._BabylonFileParsers = {};
  25084. /**
  25085. * Stores the list of available individual parsers in the application.
  25086. */
  25087. AbstractScene._IndividualBabylonFileParsers = {};
  25088. return AbstractScene;
  25089. }());
  25090. BABYLON.AbstractScene = AbstractScene;
  25091. })(BABYLON || (BABYLON = {}));
  25092. //# sourceMappingURL=babylon.abstractScene.js.map
  25093. var BABYLON;
  25094. (function (BABYLON) {
  25095. /** @hidden */
  25096. var ClickInfo = /** @class */ (function () {
  25097. function ClickInfo() {
  25098. this._singleClick = false;
  25099. this._doubleClick = false;
  25100. this._hasSwiped = false;
  25101. this._ignore = false;
  25102. }
  25103. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25104. get: function () {
  25105. return this._singleClick;
  25106. },
  25107. set: function (b) {
  25108. this._singleClick = b;
  25109. },
  25110. enumerable: true,
  25111. configurable: true
  25112. });
  25113. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25114. get: function () {
  25115. return this._doubleClick;
  25116. },
  25117. set: function (b) {
  25118. this._doubleClick = b;
  25119. },
  25120. enumerable: true,
  25121. configurable: true
  25122. });
  25123. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25124. get: function () {
  25125. return this._hasSwiped;
  25126. },
  25127. set: function (b) {
  25128. this._hasSwiped = b;
  25129. },
  25130. enumerable: true,
  25131. configurable: true
  25132. });
  25133. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25134. get: function () {
  25135. return this._ignore;
  25136. },
  25137. set: function (b) {
  25138. this._ignore = b;
  25139. },
  25140. enumerable: true,
  25141. configurable: true
  25142. });
  25143. return ClickInfo;
  25144. }());
  25145. /**
  25146. * This class is used by the onRenderingGroupObservable
  25147. */
  25148. var RenderingGroupInfo = /** @class */ (function () {
  25149. function RenderingGroupInfo() {
  25150. }
  25151. return RenderingGroupInfo;
  25152. }());
  25153. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25154. /**
  25155. * Represents a scene to be rendered by the engine.
  25156. * @see http://doc.babylonjs.com/features/scene
  25157. */
  25158. var Scene = /** @class */ (function (_super) {
  25159. __extends(Scene, _super);
  25160. /**
  25161. * Creates a new Scene
  25162. * @param engine defines the engine to use to render this scene
  25163. */
  25164. function Scene(engine) {
  25165. var _this = _super.call(this) || this;
  25166. // Members
  25167. /**
  25168. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25169. */
  25170. _this.autoClear = true;
  25171. /**
  25172. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25173. */
  25174. _this.autoClearDepthAndStencil = true;
  25175. /**
  25176. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25177. */
  25178. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25179. /**
  25180. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25181. */
  25182. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25183. _this._forceWireframe = false;
  25184. _this._forcePointsCloud = false;
  25185. /**
  25186. * Gets or sets a boolean indicating if animations are enabled
  25187. */
  25188. _this.animationsEnabled = true;
  25189. _this._animationPropertiesOverride = null;
  25190. /**
  25191. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25192. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25193. */
  25194. _this.useConstantAnimationDeltaTime = false;
  25195. /**
  25196. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25197. * Please note that it requires to run a ray cast through the scene on every frame
  25198. */
  25199. _this.constantlyUpdateMeshUnderPointer = false;
  25200. /**
  25201. * Defines the HTML cursor to use when hovering over interactive elements
  25202. */
  25203. _this.hoverCursor = "pointer";
  25204. /**
  25205. * Defines the HTML default cursor to use (empty by default)
  25206. */
  25207. _this.defaultCursor = "";
  25208. /**
  25209. * This is used to call preventDefault() on pointer down
  25210. * in order to block unwanted artifacts like system double clicks
  25211. */
  25212. _this.preventDefaultOnPointerDown = true;
  25213. // Metadata
  25214. /**
  25215. * Gets or sets user defined metadata
  25216. */
  25217. _this.metadata = null;
  25218. /**
  25219. * Use this array to add regular expressions used to disable offline support for specific urls
  25220. */
  25221. _this.disableOfflineSupportExceptionRules = new Array();
  25222. /**
  25223. * An event triggered when the scene is disposed.
  25224. */
  25225. _this.onDisposeObservable = new BABYLON.Observable();
  25226. _this._onDisposeObserver = null;
  25227. /**
  25228. * An event triggered before rendering the scene (right after animations and physics)
  25229. */
  25230. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25231. _this._onBeforeRenderObserver = null;
  25232. /**
  25233. * An event triggered after rendering the scene
  25234. */
  25235. _this.onAfterRenderObservable = new BABYLON.Observable();
  25236. _this._onAfterRenderObserver = null;
  25237. /**
  25238. * An event triggered before animating the scene
  25239. */
  25240. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25241. /**
  25242. * An event triggered after animations processing
  25243. */
  25244. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25245. /**
  25246. * An event triggered before draw calls are ready to be sent
  25247. */
  25248. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25249. /**
  25250. * An event triggered after draw calls have been sent
  25251. */
  25252. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25253. /**
  25254. * An event triggered when the scene is ready
  25255. */
  25256. _this.onReadyObservable = new BABYLON.Observable();
  25257. /**
  25258. * An event triggered before rendering a camera
  25259. */
  25260. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25261. _this._onBeforeCameraRenderObserver = null;
  25262. /**
  25263. * An event triggered after rendering a camera
  25264. */
  25265. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25266. _this._onAfterCameraRenderObserver = null;
  25267. /**
  25268. * An event triggered when active meshes evaluation is about to start
  25269. */
  25270. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25271. /**
  25272. * An event triggered when active meshes evaluation is done
  25273. */
  25274. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25275. /**
  25276. * An event triggered when particles rendering is about to start
  25277. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25278. */
  25279. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25280. /**
  25281. * An event triggered when particles rendering is done
  25282. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25283. */
  25284. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25285. /**
  25286. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25287. */
  25288. _this.onDataLoadedObservable = new BABYLON.Observable();
  25289. /**
  25290. * An event triggered when a camera is created
  25291. */
  25292. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25293. /**
  25294. * An event triggered when a camera is removed
  25295. */
  25296. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25297. /**
  25298. * An event triggered when a light is created
  25299. */
  25300. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25301. /**
  25302. * An event triggered when a light is removed
  25303. */
  25304. _this.onLightRemovedObservable = new BABYLON.Observable();
  25305. /**
  25306. * An event triggered when a geometry is created
  25307. */
  25308. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25309. /**
  25310. * An event triggered when a geometry is removed
  25311. */
  25312. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25313. /**
  25314. * An event triggered when a transform node is created
  25315. */
  25316. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25317. /**
  25318. * An event triggered when a transform node is removed
  25319. */
  25320. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25321. /**
  25322. * An event triggered when a mesh is created
  25323. */
  25324. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25325. /**
  25326. * An event triggered when a mesh is removed
  25327. */
  25328. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25329. /**
  25330. * An event triggered when a material is created
  25331. */
  25332. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25333. /**
  25334. * An event triggered when a material is removed
  25335. */
  25336. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25337. /**
  25338. * An event triggered when a texture is created
  25339. */
  25340. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25341. /**
  25342. * An event triggered when a texture is removed
  25343. */
  25344. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25345. /**
  25346. * An event triggered when render targets are about to be rendered
  25347. * Can happen multiple times per frame.
  25348. */
  25349. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25350. /**
  25351. * An event triggered when render targets were rendered.
  25352. * Can happen multiple times per frame.
  25353. */
  25354. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25355. /**
  25356. * An event triggered before calculating deterministic simulation step
  25357. */
  25358. _this.onBeforeStepObservable = new BABYLON.Observable();
  25359. /**
  25360. * An event triggered after calculating deterministic simulation step
  25361. */
  25362. _this.onAfterStepObservable = new BABYLON.Observable();
  25363. /**
  25364. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25365. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25366. * 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)
  25367. */
  25368. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25369. /**
  25370. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25371. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25372. * 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)
  25373. */
  25374. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25375. /**
  25376. * This Observable will when a mesh has been imported into the scene.
  25377. */
  25378. _this.onMeshImportedObservable = new BABYLON.Observable();
  25379. // Animations
  25380. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25381. /**
  25382. * 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).
  25383. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25384. */
  25385. _this.onPrePointerObservable = new BABYLON.Observable();
  25386. /**
  25387. * Observable event triggered each time an input event is received from the rendering canvas
  25388. */
  25389. _this.onPointerObservable = new BABYLON.Observable();
  25390. _this._meshPickProceed = false;
  25391. _this._currentPickResult = null;
  25392. _this._previousPickResult = null;
  25393. _this._totalPointersPressed = 0;
  25394. _this._doubleClickOccured = false;
  25395. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25396. _this.cameraToUseForPointers = null;
  25397. _this._pointerX = 0;
  25398. _this._pointerY = 0;
  25399. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25400. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25401. _this._startingPointerTime = 0;
  25402. _this._previousStartingPointerTime = 0;
  25403. _this._pointerCaptures = {};
  25404. // Deterministic lockstep
  25405. _this._timeAccumulator = 0;
  25406. _this._currentStepId = 0;
  25407. _this._currentInternalStep = 0;
  25408. // Keyboard
  25409. /**
  25410. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25411. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25412. */
  25413. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25414. /**
  25415. * Observable event triggered each time an keyboard event is received from the hosting window
  25416. */
  25417. _this.onKeyboardObservable = new BABYLON.Observable();
  25418. // Coordinates system
  25419. _this._useRightHandedSystem = false;
  25420. // Fog
  25421. _this._fogEnabled = true;
  25422. _this._fogMode = Scene.FOGMODE_NONE;
  25423. /**
  25424. * Gets or sets the fog color to use
  25425. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25426. * (Default is Color3(0.2, 0.2, 0.3))
  25427. */
  25428. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25429. /**
  25430. * Gets or sets the fog density to use
  25431. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25432. * (Default is 0.1)
  25433. */
  25434. _this.fogDensity = 0.1;
  25435. /**
  25436. * Gets or sets the fog start distance to use
  25437. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25438. * (Default is 0)
  25439. */
  25440. _this.fogStart = 0;
  25441. /**
  25442. * Gets or sets the fog end distance to use
  25443. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25444. * (Default is 1000)
  25445. */
  25446. _this.fogEnd = 1000.0;
  25447. // Lights
  25448. _this._shadowsEnabled = true;
  25449. _this._lightsEnabled = true;
  25450. /** All of the active cameras added to this scene. */
  25451. _this.activeCameras = new Array();
  25452. // Textures
  25453. _this._texturesEnabled = true;
  25454. // Particles
  25455. /**
  25456. * Gets or sets a boolean indicating if particles are enabled on this scene
  25457. */
  25458. _this.particlesEnabled = true;
  25459. // Sprites
  25460. /**
  25461. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25462. */
  25463. _this.spritesEnabled = true;
  25464. // Skeletons
  25465. _this._skeletonsEnabled = true;
  25466. // Lens flares
  25467. /**
  25468. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25469. */
  25470. _this.lensFlaresEnabled = true;
  25471. // Collisions
  25472. /**
  25473. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25474. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25475. */
  25476. _this.collisionsEnabled = true;
  25477. /**
  25478. * Defines the gravity applied to this scene (used only for collisions)
  25479. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25480. */
  25481. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25482. // Postprocesses
  25483. /**
  25484. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25485. */
  25486. _this.postProcessesEnabled = true;
  25487. /**
  25488. * The list of postprocesses added to the scene
  25489. */
  25490. _this.postProcesses = new Array();
  25491. // Customs render targets
  25492. /**
  25493. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25494. */
  25495. _this.renderTargetsEnabled = true;
  25496. /**
  25497. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25498. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25499. */
  25500. _this.dumpNextRenderTargets = false;
  25501. /**
  25502. * The list of user defined render targets added to the scene
  25503. */
  25504. _this.customRenderTargets = new Array();
  25505. /**
  25506. * Gets the list of meshes imported to the scene through SceneLoader
  25507. */
  25508. _this.importedMeshesFiles = new Array();
  25509. // Probes
  25510. /**
  25511. * Gets or sets a boolean indicating if probes are enabled on this scene
  25512. */
  25513. _this.probesEnabled = true;
  25514. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25515. // Procedural textures
  25516. /**
  25517. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25518. */
  25519. _this.proceduralTexturesEnabled = true;
  25520. // Performance counters
  25521. _this._totalVertices = new BABYLON.PerfCounter();
  25522. /** @hidden */
  25523. _this._activeIndices = new BABYLON.PerfCounter();
  25524. /** @hidden */
  25525. _this._activeParticles = new BABYLON.PerfCounter();
  25526. /** @hidden */
  25527. _this._activeBones = new BABYLON.PerfCounter();
  25528. _this._animationTime = 0;
  25529. /**
  25530. * Gets or sets a general scale for animation speed
  25531. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25532. */
  25533. _this.animationTimeScale = 1;
  25534. _this._renderId = 0;
  25535. _this._frameId = 0;
  25536. _this._executeWhenReadyTimeoutId = -1;
  25537. _this._intermediateRendering = false;
  25538. _this._viewUpdateFlag = -1;
  25539. _this._projectionUpdateFlag = -1;
  25540. _this._alternateViewUpdateFlag = -1;
  25541. _this._alternateProjectionUpdateFlag = -1;
  25542. /** @hidden */
  25543. _this._toBeDisposed = new Array(256);
  25544. _this._activeRequests = new Array();
  25545. _this._pendingData = new Array();
  25546. _this._isDisposed = false;
  25547. /**
  25548. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25549. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25550. */
  25551. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25552. _this._activeMeshes = new BABYLON.SmartArray(256);
  25553. _this._processedMaterials = new BABYLON.SmartArray(256);
  25554. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25555. /** @hidden */
  25556. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25557. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25558. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25559. /** @hidden */
  25560. _this._activeAnimatables = new Array();
  25561. _this._transformMatrix = BABYLON.Matrix.Zero();
  25562. _this._useAlternateCameraConfiguration = false;
  25563. _this._alternateRendering = false;
  25564. /**
  25565. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25566. * This is useful if there are more lights that the maximum simulteanous authorized
  25567. */
  25568. _this.requireLightSorting = false;
  25569. /**
  25570. * @hidden
  25571. * Backing store of defined scene components.
  25572. */
  25573. _this._components = [];
  25574. /**
  25575. * @hidden
  25576. * Backing store of defined scene components.
  25577. */
  25578. _this._serializableComponents = [];
  25579. /**
  25580. * List of components to register on the next registration step.
  25581. */
  25582. _this._transientComponents = [];
  25583. /**
  25584. * @hidden
  25585. * Defines the actions happening before camera updates.
  25586. */
  25587. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25588. /**
  25589. * @hidden
  25590. * Defines the actions happening before clear the canvas.
  25591. */
  25592. _this._beforeClearStage = BABYLON.Stage.Create();
  25593. /**
  25594. * @hidden
  25595. * Defines the actions when collecting render targets for the frame.
  25596. */
  25597. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25598. /**
  25599. * @hidden
  25600. * Defines the actions happening for one camera in the frame.
  25601. */
  25602. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25603. /**
  25604. * @hidden
  25605. * Defines the actions happening during the per mesh ready checks.
  25606. */
  25607. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25608. /**
  25609. * @hidden
  25610. * Defines the actions happening before evaluate active mesh checks.
  25611. */
  25612. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25613. /**
  25614. * @hidden
  25615. * Defines the actions happening during the evaluate sub mesh checks.
  25616. */
  25617. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25618. /**
  25619. * @hidden
  25620. * Defines the actions happening during the active mesh stage.
  25621. */
  25622. _this._activeMeshStage = BABYLON.Stage.Create();
  25623. /**
  25624. * @hidden
  25625. * Defines the actions happening during the per camera render target step.
  25626. */
  25627. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25628. /**
  25629. * @hidden
  25630. * Defines the actions happening just before the active camera is drawing.
  25631. */
  25632. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25633. /**
  25634. * @hidden
  25635. * Defines the actions happening just before a rendering group is drawing.
  25636. */
  25637. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25638. /**
  25639. * @hidden
  25640. * Defines the actions happening just before a mesh is drawing.
  25641. */
  25642. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25643. /**
  25644. * @hidden
  25645. * Defines the actions happening just after a mesh has been drawn.
  25646. */
  25647. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25648. /**
  25649. * @hidden
  25650. * Defines the actions happening just after a rendering group has been drawn.
  25651. */
  25652. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25653. /**
  25654. * @hidden
  25655. * Defines the actions happening just after the active camera has been drawn.
  25656. */
  25657. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25658. /**
  25659. * @hidden
  25660. * Defines the actions happening just after rendering all cameras and computing intersections.
  25661. */
  25662. _this._afterRenderStage = BABYLON.Stage.Create();
  25663. /**
  25664. * @hidden
  25665. * Defines the actions happening when a pointer move event happens.
  25666. */
  25667. _this._pointerMoveStage = BABYLON.Stage.Create();
  25668. /**
  25669. * @hidden
  25670. * Defines the actions happening when a pointer down event happens.
  25671. */
  25672. _this._pointerDownStage = BABYLON.Stage.Create();
  25673. /**
  25674. * @hidden
  25675. * Defines the actions happening when a pointer up event happens.
  25676. */
  25677. _this._pointerUpStage = BABYLON.Stage.Create();
  25678. _this._defaultMeshCandidates = {
  25679. data: [],
  25680. length: 0
  25681. };
  25682. _this._defaultSubMeshCandidates = {
  25683. data: [],
  25684. length: 0
  25685. };
  25686. _this._activeMeshesFrozen = false;
  25687. /** @hidden */
  25688. _this._allowPostProcessClearColor = true;
  25689. /**
  25690. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25691. */
  25692. _this.getDeterministicFrameTime = function () {
  25693. return 1000.0 / 60.0; // frame time in ms
  25694. };
  25695. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25696. _this._blockMaterialDirtyMechanism = false;
  25697. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25698. _this._engine.scenes.push(_this);
  25699. _this._uid = null;
  25700. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25701. if (BABYLON.PostProcessManager) {
  25702. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25703. }
  25704. if (BABYLON.Tools.IsWindowObjectExist()) {
  25705. _this.attachControl();
  25706. }
  25707. //collision coordinator initialization. For now legacy per default.
  25708. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25709. // Uniform Buffer
  25710. _this._createUbo();
  25711. // Default Image processing definition
  25712. if (BABYLON.ImageProcessingConfiguration) {
  25713. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25714. }
  25715. _this.setDefaultCandidateProviders();
  25716. return _this;
  25717. }
  25718. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25719. /**
  25720. * Texture used in all pbr material as the reflection texture.
  25721. * As in the majority of the scene they are the same (exception for multi room and so on),
  25722. * this is easier to reference from here than from all the materials.
  25723. */
  25724. get: function () {
  25725. return this._environmentTexture;
  25726. },
  25727. /**
  25728. * Texture used in all pbr material as the reflection texture.
  25729. * As in the majority of the scene they are the same (exception for multi room and so on),
  25730. * this is easier to set here than in all the materials.
  25731. */
  25732. set: function (value) {
  25733. if (this._environmentTexture === value) {
  25734. return;
  25735. }
  25736. this._environmentTexture = value;
  25737. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25738. },
  25739. enumerable: true,
  25740. configurable: true
  25741. });
  25742. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25743. /**
  25744. * Default image processing configuration used either in the rendering
  25745. * Forward main pass or through the imageProcessingPostProcess if present.
  25746. * As in the majority of the scene they are the same (exception for multi camera),
  25747. * this is easier to reference from here than from all the materials and post process.
  25748. *
  25749. * No setter as we it is a shared configuration, you can set the values instead.
  25750. */
  25751. get: function () {
  25752. return this._imageProcessingConfiguration;
  25753. },
  25754. enumerable: true,
  25755. configurable: true
  25756. });
  25757. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25758. get: function () {
  25759. return this._forceWireframe;
  25760. },
  25761. /**
  25762. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25763. */
  25764. set: function (value) {
  25765. if (this._forceWireframe === value) {
  25766. return;
  25767. }
  25768. this._forceWireframe = value;
  25769. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25770. },
  25771. enumerable: true,
  25772. configurable: true
  25773. });
  25774. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25775. get: function () {
  25776. return this._forcePointsCloud;
  25777. },
  25778. /**
  25779. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25780. */
  25781. set: function (value) {
  25782. if (this._forcePointsCloud === value) {
  25783. return;
  25784. }
  25785. this._forcePointsCloud = value;
  25786. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25787. },
  25788. enumerable: true,
  25789. configurable: true
  25790. });
  25791. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25792. /**
  25793. * Gets or sets the animation properties override
  25794. */
  25795. get: function () {
  25796. return this._animationPropertiesOverride;
  25797. },
  25798. set: function (value) {
  25799. this._animationPropertiesOverride = value;
  25800. },
  25801. enumerable: true,
  25802. configurable: true
  25803. });
  25804. Object.defineProperty(Scene.prototype, "onDispose", {
  25805. /** Sets a function to be executed when this scene is disposed. */
  25806. set: function (callback) {
  25807. if (this._onDisposeObserver) {
  25808. this.onDisposeObservable.remove(this._onDisposeObserver);
  25809. }
  25810. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25811. },
  25812. enumerable: true,
  25813. configurable: true
  25814. });
  25815. Object.defineProperty(Scene.prototype, "beforeRender", {
  25816. /** Sets a function to be executed before rendering this scene */
  25817. set: function (callback) {
  25818. if (this._onBeforeRenderObserver) {
  25819. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25820. }
  25821. if (callback) {
  25822. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25823. }
  25824. },
  25825. enumerable: true,
  25826. configurable: true
  25827. });
  25828. Object.defineProperty(Scene.prototype, "afterRender", {
  25829. /** Sets a function to be executed after rendering this scene */
  25830. set: function (callback) {
  25831. if (this._onAfterRenderObserver) {
  25832. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25833. }
  25834. if (callback) {
  25835. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25836. }
  25837. },
  25838. enumerable: true,
  25839. configurable: true
  25840. });
  25841. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25842. /** Sets a function to be executed before rendering a camera*/
  25843. set: function (callback) {
  25844. if (this._onBeforeCameraRenderObserver) {
  25845. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25846. }
  25847. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25848. },
  25849. enumerable: true,
  25850. configurable: true
  25851. });
  25852. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25853. /** Sets a function to be executed after rendering a camera*/
  25854. set: function (callback) {
  25855. if (this._onAfterCameraRenderObserver) {
  25856. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25857. }
  25858. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25859. },
  25860. enumerable: true,
  25861. configurable: true
  25862. });
  25863. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25864. /**
  25865. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25866. */
  25867. get: function () {
  25868. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25869. },
  25870. enumerable: true,
  25871. configurable: true
  25872. });
  25873. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25874. get: function () {
  25875. return this._useRightHandedSystem;
  25876. },
  25877. /**
  25878. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25879. */
  25880. set: function (value) {
  25881. if (this._useRightHandedSystem === value) {
  25882. return;
  25883. }
  25884. this._useRightHandedSystem = value;
  25885. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. /**
  25891. * Sets the step Id used by deterministic lock step
  25892. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25893. * @param newStepId defines the step Id
  25894. */
  25895. Scene.prototype.setStepId = function (newStepId) {
  25896. this._currentStepId = newStepId;
  25897. };
  25898. /**
  25899. * Gets the step Id used by deterministic lock step
  25900. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25901. * @returns the step Id
  25902. */
  25903. Scene.prototype.getStepId = function () {
  25904. return this._currentStepId;
  25905. };
  25906. /**
  25907. * Gets the internal step used by deterministic lock step
  25908. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25909. * @returns the internal step
  25910. */
  25911. Scene.prototype.getInternalStep = function () {
  25912. return this._currentInternalStep;
  25913. };
  25914. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25915. get: function () {
  25916. return this._fogEnabled;
  25917. },
  25918. /**
  25919. * Gets or sets a boolean indicating if fog is enabled on this scene
  25920. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25921. * (Default is true)
  25922. */
  25923. set: function (value) {
  25924. if (this._fogEnabled === value) {
  25925. return;
  25926. }
  25927. this._fogEnabled = value;
  25928. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25929. },
  25930. enumerable: true,
  25931. configurable: true
  25932. });
  25933. Object.defineProperty(Scene.prototype, "fogMode", {
  25934. get: function () {
  25935. return this._fogMode;
  25936. },
  25937. /**
  25938. * Gets or sets the fog mode to use
  25939. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25940. * | mode | value |
  25941. * | --- | --- |
  25942. * | FOGMODE_NONE | 0 |
  25943. * | FOGMODE_EXP | 1 |
  25944. * | FOGMODE_EXP2 | 2 |
  25945. * | FOGMODE_LINEAR | 3 |
  25946. */
  25947. set: function (value) {
  25948. if (this._fogMode === value) {
  25949. return;
  25950. }
  25951. this._fogMode = value;
  25952. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25953. },
  25954. enumerable: true,
  25955. configurable: true
  25956. });
  25957. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25958. get: function () {
  25959. return this._shadowsEnabled;
  25960. },
  25961. /**
  25962. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25963. */
  25964. set: function (value) {
  25965. if (this._shadowsEnabled === value) {
  25966. return;
  25967. }
  25968. this._shadowsEnabled = value;
  25969. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25970. },
  25971. enumerable: true,
  25972. configurable: true
  25973. });
  25974. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25975. get: function () {
  25976. return this._lightsEnabled;
  25977. },
  25978. /**
  25979. * Gets or sets a boolean indicating if lights are enabled on this scene
  25980. */
  25981. set: function (value) {
  25982. if (this._lightsEnabled === value) {
  25983. return;
  25984. }
  25985. this._lightsEnabled = value;
  25986. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25987. },
  25988. enumerable: true,
  25989. configurable: true
  25990. });
  25991. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25992. /** The default material used on meshes when no material is affected */
  25993. get: function () {
  25994. if (!this._defaultMaterial) {
  25995. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25996. }
  25997. return this._defaultMaterial;
  25998. },
  25999. /** The default material used on meshes when no material is affected */
  26000. set: function (value) {
  26001. this._defaultMaterial = value;
  26002. },
  26003. enumerable: true,
  26004. configurable: true
  26005. });
  26006. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26007. get: function () {
  26008. return this._texturesEnabled;
  26009. },
  26010. /**
  26011. * Gets or sets a boolean indicating if textures are enabled on this scene
  26012. */
  26013. set: function (value) {
  26014. if (this._texturesEnabled === value) {
  26015. return;
  26016. }
  26017. this._texturesEnabled = value;
  26018. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26019. },
  26020. enumerable: true,
  26021. configurable: true
  26022. });
  26023. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26024. get: function () {
  26025. return this._skeletonsEnabled;
  26026. },
  26027. /**
  26028. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26029. */
  26030. set: function (value) {
  26031. if (this._skeletonsEnabled === value) {
  26032. return;
  26033. }
  26034. this._skeletonsEnabled = value;
  26035. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26036. },
  26037. enumerable: true,
  26038. configurable: true
  26039. });
  26040. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26041. /** @hidden */
  26042. get: function () {
  26043. return this._alternateRendering;
  26044. },
  26045. enumerable: true,
  26046. configurable: true
  26047. });
  26048. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26049. /**
  26050. * Gets the list of frustum planes (built from the active camera)
  26051. */
  26052. get: function () {
  26053. return this._frustumPlanes;
  26054. },
  26055. enumerable: true,
  26056. configurable: true
  26057. });
  26058. /**
  26059. * Registers the transient components if needed.
  26060. */
  26061. Scene.prototype._registerTransientComponents = function () {
  26062. // Register components that have been associated lately to the scene.
  26063. if (this._transientComponents.length > 0) {
  26064. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26065. var component = _a[_i];
  26066. component.register();
  26067. }
  26068. this._transientComponents = [];
  26069. }
  26070. };
  26071. /**
  26072. * @hidden
  26073. * Add a component to the scene.
  26074. * Note that the ccomponent could be registered on th next frame if this is called after
  26075. * the register component stage.
  26076. * @param component Defines the component to add to the scene
  26077. */
  26078. Scene.prototype._addComponent = function (component) {
  26079. this._components.push(component);
  26080. this._transientComponents.push(component);
  26081. var serializableComponent = component;
  26082. if (serializableComponent.addFromContainer) {
  26083. this._serializableComponents.push(serializableComponent);
  26084. }
  26085. };
  26086. /**
  26087. * @hidden
  26088. * Gets a component from the scene.
  26089. * @param name defines the name of the component to retrieve
  26090. * @returns the component or null if not present
  26091. */
  26092. Scene.prototype._getComponent = function (name) {
  26093. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26094. var component = _a[_i];
  26095. if (component.name === name) {
  26096. return component;
  26097. }
  26098. }
  26099. return null;
  26100. };
  26101. /**
  26102. * @hidden
  26103. */
  26104. Scene.prototype._getDefaultMeshCandidates = function () {
  26105. this._defaultMeshCandidates.data = this.meshes;
  26106. this._defaultMeshCandidates.length = this.meshes.length;
  26107. return this._defaultMeshCandidates;
  26108. };
  26109. /**
  26110. * @hidden
  26111. */
  26112. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26113. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26114. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26115. return this._defaultSubMeshCandidates;
  26116. };
  26117. /**
  26118. * Sets the default candidate providers for the scene.
  26119. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26120. * and getCollidingSubMeshCandidates to their default function
  26121. */
  26122. Scene.prototype.setDefaultCandidateProviders = function () {
  26123. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26124. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26125. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26126. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26127. };
  26128. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26129. /**
  26130. * Gets a boolean indicating if collisions are processed on a web worker
  26131. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26132. */
  26133. get: function () {
  26134. return this._workerCollisions;
  26135. },
  26136. set: function (enabled) {
  26137. if (!BABYLON.CollisionCoordinatorLegacy) {
  26138. return;
  26139. }
  26140. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26141. this._workerCollisions = enabled;
  26142. if (this.collisionCoordinator) {
  26143. this.collisionCoordinator.destroy();
  26144. }
  26145. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26146. this.collisionCoordinator.init(this);
  26147. },
  26148. enumerable: true,
  26149. configurable: true
  26150. });
  26151. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26152. /**
  26153. * Gets the mesh that is currently under the pointer
  26154. */
  26155. get: function () {
  26156. return this._pointerOverMesh;
  26157. },
  26158. enumerable: true,
  26159. configurable: true
  26160. });
  26161. Object.defineProperty(Scene.prototype, "pointerX", {
  26162. /**
  26163. * Gets the current on-screen X position of the pointer
  26164. */
  26165. get: function () {
  26166. return this._pointerX;
  26167. },
  26168. enumerable: true,
  26169. configurable: true
  26170. });
  26171. Object.defineProperty(Scene.prototype, "pointerY", {
  26172. /**
  26173. * Gets the current on-screen Y position of the pointer
  26174. */
  26175. get: function () {
  26176. return this._pointerY;
  26177. },
  26178. enumerable: true,
  26179. configurable: true
  26180. });
  26181. /**
  26182. * Gets the cached material (ie. the latest rendered one)
  26183. * @returns the cached material
  26184. */
  26185. Scene.prototype.getCachedMaterial = function () {
  26186. return this._cachedMaterial;
  26187. };
  26188. /**
  26189. * Gets the cached effect (ie. the latest rendered one)
  26190. * @returns the cached effect
  26191. */
  26192. Scene.prototype.getCachedEffect = function () {
  26193. return this._cachedEffect;
  26194. };
  26195. /**
  26196. * Gets the cached visibility state (ie. the latest rendered one)
  26197. * @returns the cached visibility state
  26198. */
  26199. Scene.prototype.getCachedVisibility = function () {
  26200. return this._cachedVisibility;
  26201. };
  26202. /**
  26203. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26204. * @param material defines the current material
  26205. * @param effect defines the current effect
  26206. * @param visibility defines the current visibility state
  26207. * @returns true if one parameter is not cached
  26208. */
  26209. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26210. if (visibility === void 0) { visibility = 1; }
  26211. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26212. };
  26213. /**
  26214. * Gets the engine associated with the scene
  26215. * @returns an Engine
  26216. */
  26217. Scene.prototype.getEngine = function () {
  26218. return this._engine;
  26219. };
  26220. /**
  26221. * Gets the total number of vertices rendered per frame
  26222. * @returns the total number of vertices rendered per frame
  26223. */
  26224. Scene.prototype.getTotalVertices = function () {
  26225. return this._totalVertices.current;
  26226. };
  26227. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26228. /**
  26229. * Gets the performance counter for total vertices
  26230. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26231. */
  26232. get: function () {
  26233. return this._totalVertices;
  26234. },
  26235. enumerable: true,
  26236. configurable: true
  26237. });
  26238. /**
  26239. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26240. * @returns the total number of active indices rendered per frame
  26241. */
  26242. Scene.prototype.getActiveIndices = function () {
  26243. return this._activeIndices.current;
  26244. };
  26245. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26246. /**
  26247. * Gets the performance counter for active indices
  26248. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26249. */
  26250. get: function () {
  26251. return this._activeIndices;
  26252. },
  26253. enumerable: true,
  26254. configurable: true
  26255. });
  26256. /**
  26257. * Gets the total number of active particles rendered per frame
  26258. * @returns the total number of active particles rendered per frame
  26259. */
  26260. Scene.prototype.getActiveParticles = function () {
  26261. return this._activeParticles.current;
  26262. };
  26263. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26264. /**
  26265. * Gets the performance counter for active particles
  26266. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26267. */
  26268. get: function () {
  26269. return this._activeParticles;
  26270. },
  26271. enumerable: true,
  26272. configurable: true
  26273. });
  26274. /**
  26275. * Gets the total number of active bones rendered per frame
  26276. * @returns the total number of active bones rendered per frame
  26277. */
  26278. Scene.prototype.getActiveBones = function () {
  26279. return this._activeBones.current;
  26280. };
  26281. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26282. /**
  26283. * Gets the performance counter for active bones
  26284. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26285. */
  26286. get: function () {
  26287. return this._activeBones;
  26288. },
  26289. enumerable: true,
  26290. configurable: true
  26291. });
  26292. /** @hidden */
  26293. Scene.prototype.getInterFramePerfCounter = function () {
  26294. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26295. return 0;
  26296. };
  26297. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26298. /** @hidden */
  26299. get: function () {
  26300. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26301. return null;
  26302. },
  26303. enumerable: true,
  26304. configurable: true
  26305. });
  26306. /** @hidden */
  26307. Scene.prototype.getLastFrameDuration = function () {
  26308. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26309. return 0;
  26310. };
  26311. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26312. /** @hidden */
  26313. get: function () {
  26314. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26315. return null;
  26316. },
  26317. enumerable: true,
  26318. configurable: true
  26319. });
  26320. /** @hidden */
  26321. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26322. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26323. return 0;
  26324. };
  26325. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26326. /** @hidden */
  26327. get: function () {
  26328. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26329. return null;
  26330. },
  26331. enumerable: true,
  26332. configurable: true
  26333. });
  26334. /**
  26335. * Gets the array of active meshes
  26336. * @returns an array of AbstractMesh
  26337. */
  26338. Scene.prototype.getActiveMeshes = function () {
  26339. return this._activeMeshes;
  26340. };
  26341. /** @hidden */
  26342. Scene.prototype.getRenderTargetsDuration = function () {
  26343. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26344. return 0;
  26345. };
  26346. /** @hidden */
  26347. Scene.prototype.getRenderDuration = function () {
  26348. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26349. return 0;
  26350. };
  26351. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26352. /** @hidden */
  26353. get: function () {
  26354. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26355. return null;
  26356. },
  26357. enumerable: true,
  26358. configurable: true
  26359. });
  26360. /** @hidden */
  26361. Scene.prototype.getParticlesDuration = function () {
  26362. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26363. return 0;
  26364. };
  26365. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26366. /** @hidden */
  26367. get: function () {
  26368. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26369. return null;
  26370. },
  26371. enumerable: true,
  26372. configurable: true
  26373. });
  26374. /** @hidden */
  26375. Scene.prototype.getSpritesDuration = function () {
  26376. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26377. return 0;
  26378. };
  26379. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26380. /** @hidden */
  26381. get: function () {
  26382. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26383. return null;
  26384. },
  26385. enumerable: true,
  26386. configurable: true
  26387. });
  26388. /**
  26389. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26390. * @returns a number
  26391. */
  26392. Scene.prototype.getAnimationRatio = function () {
  26393. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26394. };
  26395. /**
  26396. * Gets an unique Id for the current render phase
  26397. * @returns a number
  26398. */
  26399. Scene.prototype.getRenderId = function () {
  26400. return this._renderId;
  26401. };
  26402. /**
  26403. * Gets an unique Id for the current frame
  26404. * @returns a number
  26405. */
  26406. Scene.prototype.getFrameId = function () {
  26407. return this._frameId;
  26408. };
  26409. /** Call this function if you want to manually increment the render Id*/
  26410. Scene.prototype.incrementRenderId = function () {
  26411. this._renderId++;
  26412. };
  26413. Scene.prototype._updatePointerPosition = function (evt) {
  26414. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26415. if (!canvasRect) {
  26416. return;
  26417. }
  26418. this._pointerX = evt.clientX - canvasRect.left;
  26419. this._pointerY = evt.clientY - canvasRect.top;
  26420. this._unTranslatedPointerX = this._pointerX;
  26421. this._unTranslatedPointerY = this._pointerY;
  26422. };
  26423. Scene.prototype._createUbo = function () {
  26424. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26425. this._sceneUbo.addUniform("viewProjection", 16);
  26426. this._sceneUbo.addUniform("view", 16);
  26427. };
  26428. Scene.prototype._createAlternateUbo = function () {
  26429. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26430. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26431. this._alternateSceneUbo.addUniform("view", 16);
  26432. };
  26433. // Pointers handling
  26434. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26435. if (pointerInfo.pickInfo) {
  26436. if (!pointerInfo.pickInfo.ray) {
  26437. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26438. }
  26439. }
  26440. };
  26441. /**
  26442. * Use this method to simulate a pointer move on a mesh
  26443. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26444. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26445. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26446. * @returns the current scene
  26447. */
  26448. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26449. var evt = new PointerEvent("pointermove", pointerEventInit);
  26450. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26451. return this;
  26452. }
  26453. return this._processPointerMove(pickResult, evt);
  26454. };
  26455. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26456. var canvas = this._engine.getRenderingCanvas();
  26457. if (!canvas) {
  26458. return this;
  26459. }
  26460. // Restore pointer
  26461. canvas.style.cursor = this.defaultCursor;
  26462. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26463. if (isMeshPicked) {
  26464. this.setPointerOverMesh(pickResult.pickedMesh);
  26465. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26466. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26467. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26468. }
  26469. else {
  26470. canvas.style.cursor = this.hoverCursor;
  26471. }
  26472. }
  26473. }
  26474. else {
  26475. this.setPointerOverMesh(null);
  26476. }
  26477. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26478. var step = _a[_i];
  26479. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26480. }
  26481. if (pickResult) {
  26482. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26483. if (this.onPointerMove) {
  26484. this.onPointerMove(evt, pickResult, type);
  26485. }
  26486. if (this.onPointerObservable.hasObservers()) {
  26487. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26488. this._setRayOnPointerInfo(pi);
  26489. this.onPointerObservable.notifyObservers(pi, type);
  26490. }
  26491. }
  26492. return this;
  26493. };
  26494. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26495. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26496. if (pickResult) {
  26497. pi.ray = pickResult.ray;
  26498. }
  26499. this.onPrePointerObservable.notifyObservers(pi, type);
  26500. if (pi.skipOnPointerObservable) {
  26501. return true;
  26502. }
  26503. else {
  26504. return false;
  26505. }
  26506. };
  26507. /**
  26508. * Use this method to simulate a pointer down on a mesh
  26509. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26510. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26511. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26512. * @returns the current scene
  26513. */
  26514. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26515. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26516. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26517. return this;
  26518. }
  26519. return this._processPointerDown(pickResult, evt);
  26520. };
  26521. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26522. var _this = this;
  26523. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26524. this._pickedDownMesh = pickResult.pickedMesh;
  26525. var actionManager = pickResult.pickedMesh.actionManager;
  26526. if (actionManager) {
  26527. if (actionManager.hasPickTriggers) {
  26528. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26529. switch (evt.button) {
  26530. case 0:
  26531. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26532. break;
  26533. case 1:
  26534. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26535. break;
  26536. case 2:
  26537. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26538. break;
  26539. }
  26540. }
  26541. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26542. window.setTimeout(function () {
  26543. 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);
  26544. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26545. if (_this._totalPointersPressed !== 0 &&
  26546. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26547. !_this._isPointerSwiping()) {
  26548. _this._startingPointerTime = 0;
  26549. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26550. }
  26551. }
  26552. }, Scene.LongPressDelay);
  26553. }
  26554. }
  26555. }
  26556. else {
  26557. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26558. var step = _a[_i];
  26559. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26560. }
  26561. }
  26562. if (pickResult) {
  26563. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26564. if (this.onPointerDown) {
  26565. this.onPointerDown(evt, pickResult, type);
  26566. }
  26567. if (this.onPointerObservable.hasObservers()) {
  26568. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26569. this._setRayOnPointerInfo(pi);
  26570. this.onPointerObservable.notifyObservers(pi, type);
  26571. }
  26572. }
  26573. return this;
  26574. };
  26575. /**
  26576. * Use this method to simulate a pointer up on a mesh
  26577. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26578. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26579. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26580. * @returns the current scene
  26581. */
  26582. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26583. var evt = new PointerEvent("pointerup", pointerEventInit);
  26584. var clickInfo = new ClickInfo();
  26585. clickInfo.singleClick = true;
  26586. clickInfo.ignore = true;
  26587. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26588. return this;
  26589. }
  26590. return this._processPointerUp(pickResult, evt, clickInfo);
  26591. };
  26592. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26593. if (pickResult && pickResult && pickResult.pickedMesh) {
  26594. this._pickedUpMesh = pickResult.pickedMesh;
  26595. if (this._pickedDownMesh === this._pickedUpMesh) {
  26596. if (this.onPointerPick) {
  26597. this.onPointerPick(evt, pickResult);
  26598. }
  26599. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26600. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26601. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26602. this._setRayOnPointerInfo(pi);
  26603. this.onPointerObservable.notifyObservers(pi, type_1);
  26604. }
  26605. }
  26606. if (pickResult.pickedMesh.actionManager) {
  26607. if (clickInfo.ignore) {
  26608. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26609. }
  26610. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26611. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26612. }
  26613. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26614. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26615. }
  26616. }
  26617. }
  26618. else {
  26619. if (!clickInfo.ignore) {
  26620. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26621. var step = _a[_i];
  26622. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26623. }
  26624. }
  26625. }
  26626. if (this._pickedDownMesh &&
  26627. this._pickedDownMesh.actionManager &&
  26628. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26629. this._pickedDownMesh !== this._pickedUpMesh) {
  26630. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26631. }
  26632. var type = BABYLON.PointerEventTypes.POINTERUP;
  26633. if (this.onPointerObservable.hasObservers()) {
  26634. if (!clickInfo.ignore) {
  26635. if (!clickInfo.hasSwiped) {
  26636. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26637. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26638. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26639. this._setRayOnPointerInfo(pi);
  26640. this.onPointerObservable.notifyObservers(pi, type_2);
  26641. }
  26642. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26643. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26644. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26645. this._setRayOnPointerInfo(pi);
  26646. this.onPointerObservable.notifyObservers(pi, type_3);
  26647. }
  26648. }
  26649. }
  26650. else {
  26651. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26652. this._setRayOnPointerInfo(pi);
  26653. this.onPointerObservable.notifyObservers(pi, type);
  26654. }
  26655. }
  26656. if (this.onPointerUp) {
  26657. this.onPointerUp(evt, pickResult, type);
  26658. }
  26659. return this;
  26660. };
  26661. /**
  26662. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26663. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26664. * @returns true if the pointer was captured
  26665. */
  26666. Scene.prototype.isPointerCaptured = function (pointerId) {
  26667. if (pointerId === void 0) { pointerId = 0; }
  26668. return this._pointerCaptures[pointerId];
  26669. };
  26670. /** @hidden */
  26671. Scene.prototype._isPointerSwiping = function () {
  26672. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26673. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26674. };
  26675. /**
  26676. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26677. * @param attachUp defines if you want to attach events to pointerup
  26678. * @param attachDown defines if you want to attach events to pointerdown
  26679. * @param attachMove defines if you want to attach events to pointermove
  26680. */
  26681. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26682. var _this = this;
  26683. if (attachUp === void 0) { attachUp = true; }
  26684. if (attachDown === void 0) { attachDown = true; }
  26685. if (attachMove === void 0) { attachMove = true; }
  26686. this._initActionManager = function (act, clickInfo) {
  26687. if (!_this._meshPickProceed) {
  26688. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26689. _this._currentPickResult = pickResult;
  26690. if (pickResult) {
  26691. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26692. }
  26693. _this._meshPickProceed = true;
  26694. }
  26695. return act;
  26696. };
  26697. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26698. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26699. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26700. btn !== _this._previousButtonPressed) {
  26701. _this._doubleClickOccured = false;
  26702. clickInfo.singleClick = true;
  26703. clickInfo.ignore = false;
  26704. cb(clickInfo, _this._currentPickResult);
  26705. }
  26706. };
  26707. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26708. var clickInfo = new ClickInfo();
  26709. _this._currentPickResult = null;
  26710. var act = null;
  26711. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26712. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26713. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26714. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26715. act = _this._initActionManager(act, clickInfo);
  26716. if (act) {
  26717. checkPicking = act.hasPickTriggers;
  26718. }
  26719. }
  26720. if (checkPicking) {
  26721. var btn = evt.button;
  26722. clickInfo.hasSwiped = _this._isPointerSwiping();
  26723. if (!clickInfo.hasSwiped) {
  26724. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26725. if (!checkSingleClickImmediately) {
  26726. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26727. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26728. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26729. act = _this._initActionManager(act, clickInfo);
  26730. if (act) {
  26731. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26732. }
  26733. }
  26734. }
  26735. if (checkSingleClickImmediately) {
  26736. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26737. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26738. btn !== _this._previousButtonPressed) {
  26739. clickInfo.singleClick = true;
  26740. cb(clickInfo, _this._currentPickResult);
  26741. }
  26742. }
  26743. // at least one double click is required to be check and exclusive double click is enabled
  26744. else {
  26745. // wait that no double click has been raised during the double click delay
  26746. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26747. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26748. }
  26749. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26750. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26751. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26752. act = _this._initActionManager(act, clickInfo);
  26753. if (act) {
  26754. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26755. }
  26756. }
  26757. if (checkDoubleClick) {
  26758. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26759. if (btn === _this._previousButtonPressed &&
  26760. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26761. !_this._doubleClickOccured) {
  26762. // pointer has not moved for 2 clicks, it's a double click
  26763. if (!clickInfo.hasSwiped &&
  26764. !_this._isPointerSwiping()) {
  26765. _this._previousStartingPointerTime = 0;
  26766. _this._doubleClickOccured = true;
  26767. clickInfo.doubleClick = true;
  26768. clickInfo.ignore = false;
  26769. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26770. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26771. }
  26772. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26773. cb(clickInfo, _this._currentPickResult);
  26774. }
  26775. // if the two successive clicks are too far, it's just two simple clicks
  26776. else {
  26777. _this._doubleClickOccured = false;
  26778. _this._previousStartingPointerTime = _this._startingPointerTime;
  26779. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26780. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26781. _this._previousButtonPressed = btn;
  26782. if (Scene.ExclusiveDoubleClickMode) {
  26783. if (_this._previousDelayedSimpleClickTimeout) {
  26784. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26785. }
  26786. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26787. cb(clickInfo, _this._previousPickResult);
  26788. }
  26789. else {
  26790. cb(clickInfo, _this._currentPickResult);
  26791. }
  26792. }
  26793. }
  26794. // just the first click of the double has been raised
  26795. else {
  26796. _this._doubleClickOccured = false;
  26797. _this._previousStartingPointerTime = _this._startingPointerTime;
  26798. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26799. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26800. _this._previousButtonPressed = btn;
  26801. }
  26802. }
  26803. }
  26804. }
  26805. clickInfo.ignore = true;
  26806. cb(clickInfo, _this._currentPickResult);
  26807. };
  26808. this._onPointerMove = function (evt) {
  26809. _this._updatePointerPosition(evt);
  26810. // PreObservable support
  26811. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26812. return;
  26813. }
  26814. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26815. return;
  26816. }
  26817. if (!_this.pointerMovePredicate) {
  26818. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26819. }
  26820. // Meshes
  26821. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26822. _this._processPointerMove(pickResult, evt);
  26823. };
  26824. this._onPointerDown = function (evt) {
  26825. _this._totalPointersPressed++;
  26826. _this._pickedDownMesh = null;
  26827. _this._meshPickProceed = false;
  26828. _this._updatePointerPosition(evt);
  26829. if (_this.preventDefaultOnPointerDown && canvas) {
  26830. evt.preventDefault();
  26831. canvas.focus();
  26832. }
  26833. // PreObservable support
  26834. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26835. return;
  26836. }
  26837. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26838. return;
  26839. }
  26840. _this._pointerCaptures[evt.pointerId] = true;
  26841. _this._startingPointerPosition.x = _this._pointerX;
  26842. _this._startingPointerPosition.y = _this._pointerY;
  26843. _this._startingPointerTime = Date.now();
  26844. if (!_this.pointerDownPredicate) {
  26845. _this.pointerDownPredicate = function (mesh) {
  26846. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26847. };
  26848. }
  26849. // Meshes
  26850. _this._pickedDownMesh = null;
  26851. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26852. _this._processPointerDown(pickResult, evt);
  26853. };
  26854. this._onPointerUp = function (evt) {
  26855. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26856. return; // So we need to test it the pointer down was pressed before.
  26857. }
  26858. _this._totalPointersPressed--;
  26859. _this._pickedUpMesh = null;
  26860. _this._meshPickProceed = false;
  26861. _this._updatePointerPosition(evt);
  26862. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26863. // PreObservable support
  26864. if (_this.onPrePointerObservable.hasObservers()) {
  26865. if (!clickInfo.ignore) {
  26866. if (!clickInfo.hasSwiped) {
  26867. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26868. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26869. return;
  26870. }
  26871. }
  26872. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26873. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26874. return;
  26875. }
  26876. }
  26877. }
  26878. }
  26879. else {
  26880. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26881. return;
  26882. }
  26883. }
  26884. }
  26885. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26886. return;
  26887. }
  26888. _this._pointerCaptures[evt.pointerId] = false;
  26889. if (!_this.pointerUpPredicate) {
  26890. _this.pointerUpPredicate = function (mesh) {
  26891. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26892. };
  26893. }
  26894. // Meshes
  26895. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26896. _this._initActionManager(null, clickInfo);
  26897. }
  26898. if (!pickResult) {
  26899. pickResult = _this._currentPickResult;
  26900. }
  26901. _this._processPointerUp(pickResult, evt, clickInfo);
  26902. _this._previousPickResult = _this._currentPickResult;
  26903. });
  26904. };
  26905. this._onKeyDown = function (evt) {
  26906. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26907. if (_this.onPreKeyboardObservable.hasObservers()) {
  26908. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26909. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26910. if (pi.skipOnPointerObservable) {
  26911. return;
  26912. }
  26913. }
  26914. if (_this.onKeyboardObservable.hasObservers()) {
  26915. var pi = new BABYLON.KeyboardInfo(type, evt);
  26916. _this.onKeyboardObservable.notifyObservers(pi, type);
  26917. }
  26918. if (_this.actionManager) {
  26919. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26920. }
  26921. };
  26922. this._onKeyUp = function (evt) {
  26923. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26924. if (_this.onPreKeyboardObservable.hasObservers()) {
  26925. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26926. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26927. if (pi.skipOnPointerObservable) {
  26928. return;
  26929. }
  26930. }
  26931. if (_this.onKeyboardObservable.hasObservers()) {
  26932. var pi = new BABYLON.KeyboardInfo(type, evt);
  26933. _this.onKeyboardObservable.notifyObservers(pi, type);
  26934. }
  26935. if (_this.actionManager) {
  26936. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26937. }
  26938. };
  26939. var engine = this.getEngine();
  26940. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26941. if (!canvas) {
  26942. return;
  26943. }
  26944. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26945. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26946. });
  26947. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26948. if (!canvas) {
  26949. return;
  26950. }
  26951. canvas.removeEventListener("keydown", _this._onKeyDown);
  26952. canvas.removeEventListener("keyup", _this._onKeyUp);
  26953. });
  26954. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26955. var canvas = this._engine.getRenderingCanvas();
  26956. if (!canvas) {
  26957. return;
  26958. }
  26959. if (attachMove) {
  26960. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26961. // Wheel
  26962. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26963. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26964. }
  26965. if (attachDown) {
  26966. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26967. }
  26968. if (attachUp) {
  26969. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26970. }
  26971. canvas.tabIndex = 1;
  26972. };
  26973. /** Detaches all event handlers*/
  26974. Scene.prototype.detachControl = function () {
  26975. var engine = this.getEngine();
  26976. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26977. var canvas = engine.getRenderingCanvas();
  26978. if (!canvas) {
  26979. return;
  26980. }
  26981. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26982. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26983. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26984. if (this._onCanvasBlurObserver) {
  26985. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26986. }
  26987. if (this._onCanvasFocusObserver) {
  26988. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26989. }
  26990. // Wheel
  26991. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26992. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26993. // Keyboard
  26994. canvas.removeEventListener("keydown", this._onKeyDown);
  26995. canvas.removeEventListener("keyup", this._onKeyUp);
  26996. // Observables
  26997. this.onKeyboardObservable.clear();
  26998. this.onPreKeyboardObservable.clear();
  26999. this.onPointerObservable.clear();
  27000. this.onPrePointerObservable.clear();
  27001. };
  27002. /**
  27003. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27004. * Delay loaded resources are not taking in account
  27005. * @return true if all required resources are ready
  27006. */
  27007. Scene.prototype.isReady = function () {
  27008. if (this._isDisposed) {
  27009. return false;
  27010. }
  27011. if (this._pendingData.length > 0) {
  27012. return false;
  27013. }
  27014. var index;
  27015. var engine = this.getEngine();
  27016. // Geometries
  27017. for (index = 0; index < this.geometries.length; index++) {
  27018. var geometry = this.geometries[index];
  27019. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27020. return false;
  27021. }
  27022. }
  27023. // Meshes
  27024. for (index = 0; index < this.meshes.length; index++) {
  27025. var mesh = this.meshes[index];
  27026. if (!mesh.isEnabled()) {
  27027. continue;
  27028. }
  27029. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27030. continue;
  27031. }
  27032. if (!mesh.isReady(true)) {
  27033. return false;
  27034. }
  27035. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27036. // Is Ready For Mesh
  27037. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27038. var step = _a[_i];
  27039. if (!step.action(mesh, hardwareInstancedRendering)) {
  27040. return false;
  27041. }
  27042. }
  27043. }
  27044. // Post-processes
  27045. if (this.activeCameras && this.activeCameras.length > 0) {
  27046. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27047. var camera = _c[_b];
  27048. if (!camera.isReady(true)) {
  27049. return false;
  27050. }
  27051. }
  27052. }
  27053. else if (this.activeCamera) {
  27054. if (!this.activeCamera.isReady(true)) {
  27055. return false;
  27056. }
  27057. }
  27058. // Particles
  27059. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27060. var particleSystem = _e[_d];
  27061. if (!particleSystem.isReady()) {
  27062. return false;
  27063. }
  27064. }
  27065. return true;
  27066. };
  27067. /** Resets all cached information relative to material (including effect and visibility) */
  27068. Scene.prototype.resetCachedMaterial = function () {
  27069. this._cachedMaterial = null;
  27070. this._cachedEffect = null;
  27071. this._cachedVisibility = null;
  27072. };
  27073. /**
  27074. * Registers a function to be called before every frame render
  27075. * @param func defines the function to register
  27076. */
  27077. Scene.prototype.registerBeforeRender = function (func) {
  27078. this.onBeforeRenderObservable.add(func);
  27079. };
  27080. /**
  27081. * Unregisters a function called before every frame render
  27082. * @param func defines the function to unregister
  27083. */
  27084. Scene.prototype.unregisterBeforeRender = function (func) {
  27085. this.onBeforeRenderObservable.removeCallback(func);
  27086. };
  27087. /**
  27088. * Registers a function to be called after every frame render
  27089. * @param func defines the function to register
  27090. */
  27091. Scene.prototype.registerAfterRender = function (func) {
  27092. this.onAfterRenderObservable.add(func);
  27093. };
  27094. /**
  27095. * Unregisters a function called after every frame render
  27096. * @param func defines the function to unregister
  27097. */
  27098. Scene.prototype.unregisterAfterRender = function (func) {
  27099. this.onAfterRenderObservable.removeCallback(func);
  27100. };
  27101. Scene.prototype._executeOnceBeforeRender = function (func) {
  27102. var _this = this;
  27103. var execFunc = function () {
  27104. func();
  27105. setTimeout(function () {
  27106. _this.unregisterBeforeRender(execFunc);
  27107. });
  27108. };
  27109. this.registerBeforeRender(execFunc);
  27110. };
  27111. /**
  27112. * The provided function will run before render once and will be disposed afterwards.
  27113. * A timeout delay can be provided so that the function will be executed in N ms.
  27114. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27115. * @param func The function to be executed.
  27116. * @param timeout optional delay in ms
  27117. */
  27118. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27119. var _this = this;
  27120. if (timeout !== undefined) {
  27121. setTimeout(function () {
  27122. _this._executeOnceBeforeRender(func);
  27123. }, timeout);
  27124. }
  27125. else {
  27126. this._executeOnceBeforeRender(func);
  27127. }
  27128. };
  27129. /** @hidden */
  27130. Scene.prototype._addPendingData = function (data) {
  27131. this._pendingData.push(data);
  27132. };
  27133. /** @hidden */
  27134. Scene.prototype._removePendingData = function (data) {
  27135. var wasLoading = this.isLoading;
  27136. var index = this._pendingData.indexOf(data);
  27137. if (index !== -1) {
  27138. this._pendingData.splice(index, 1);
  27139. }
  27140. if (wasLoading && !this.isLoading) {
  27141. this.onDataLoadedObservable.notifyObservers(this);
  27142. }
  27143. };
  27144. /**
  27145. * Returns the number of items waiting to be loaded
  27146. * @returns the number of items waiting to be loaded
  27147. */
  27148. Scene.prototype.getWaitingItemsCount = function () {
  27149. return this._pendingData.length;
  27150. };
  27151. Object.defineProperty(Scene.prototype, "isLoading", {
  27152. /**
  27153. * Returns a boolean indicating if the scene is still loading data
  27154. */
  27155. get: function () {
  27156. return this._pendingData.length > 0;
  27157. },
  27158. enumerable: true,
  27159. configurable: true
  27160. });
  27161. /**
  27162. * Registers a function to be executed when the scene is ready
  27163. * @param {Function} func - the function to be executed
  27164. */
  27165. Scene.prototype.executeWhenReady = function (func) {
  27166. var _this = this;
  27167. this.onReadyObservable.add(func);
  27168. if (this._executeWhenReadyTimeoutId !== -1) {
  27169. return;
  27170. }
  27171. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27172. _this._checkIsReady();
  27173. }, 150);
  27174. };
  27175. /**
  27176. * Returns a promise that resolves when the scene is ready
  27177. * @returns A promise that resolves when the scene is ready
  27178. */
  27179. Scene.prototype.whenReadyAsync = function () {
  27180. var _this = this;
  27181. return new Promise(function (resolve) {
  27182. _this.executeWhenReady(function () {
  27183. resolve();
  27184. });
  27185. });
  27186. };
  27187. /** @hidden */
  27188. Scene.prototype._checkIsReady = function () {
  27189. var _this = this;
  27190. this._registerTransientComponents();
  27191. if (this.isReady()) {
  27192. this.onReadyObservable.notifyObservers(this);
  27193. this.onReadyObservable.clear();
  27194. this._executeWhenReadyTimeoutId = -1;
  27195. return;
  27196. }
  27197. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27198. _this._checkIsReady();
  27199. }, 150);
  27200. };
  27201. // Animations
  27202. /**
  27203. * Will start the animation sequence of a given target
  27204. * @param target defines the target
  27205. * @param from defines from which frame should animation start
  27206. * @param to defines until which frame should animation run.
  27207. * @param weight defines the weight to apply to the animation (1.0 by default)
  27208. * @param loop defines if the animation loops
  27209. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27210. * @param onAnimationEnd defines the function to be executed when the animation ends
  27211. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27212. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27213. * @returns the animatable object created for this animation
  27214. */
  27215. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27216. if (weight === void 0) { weight = 1.0; }
  27217. if (speedRatio === void 0) { speedRatio = 1.0; }
  27218. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27219. returnedAnimatable.weight = weight;
  27220. return returnedAnimatable;
  27221. };
  27222. /**
  27223. * Will start the animation sequence of a given target
  27224. * @param target defines the target
  27225. * @param from defines from which frame should animation start
  27226. * @param to defines until which frame should animation run.
  27227. * @param loop defines if the animation loops
  27228. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27229. * @param onAnimationEnd defines the function to be executed when the animation ends
  27230. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27231. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27232. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27233. * @returns the animatable object created for this animation
  27234. */
  27235. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27236. if (speedRatio === void 0) { speedRatio = 1.0; }
  27237. if (stopCurrent === void 0) { stopCurrent = true; }
  27238. if (from > to && speedRatio > 0) {
  27239. speedRatio *= -1;
  27240. }
  27241. if (stopCurrent) {
  27242. this.stopAnimation(target, undefined, targetMask);
  27243. }
  27244. if (!animatable) {
  27245. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27246. }
  27247. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27248. // Local animations
  27249. if (target.animations && shouldRunTargetAnimations) {
  27250. animatable.appendAnimations(target, target.animations);
  27251. }
  27252. // Children animations
  27253. if (target.getAnimatables) {
  27254. var animatables = target.getAnimatables();
  27255. for (var index = 0; index < animatables.length; index++) {
  27256. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27257. }
  27258. }
  27259. animatable.reset();
  27260. return animatable;
  27261. };
  27262. /**
  27263. * Begin a new animation on a given node
  27264. * @param target defines the target where the animation will take place
  27265. * @param animations defines the list of animations to start
  27266. * @param from defines the initial value
  27267. * @param to defines the final value
  27268. * @param loop defines if you want animation to loop (off by default)
  27269. * @param speedRatio defines the speed ratio to apply to all animations
  27270. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27271. * @returns the list of created animatables
  27272. */
  27273. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27274. if (speedRatio === undefined) {
  27275. speedRatio = 1.0;
  27276. }
  27277. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27278. return animatable;
  27279. };
  27280. /**
  27281. * Begin a new animation on a given node and its hierarchy
  27282. * @param target defines the root node where the animation will take place
  27283. * @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.
  27284. * @param animations defines the list of animations to start
  27285. * @param from defines the initial value
  27286. * @param to defines the final value
  27287. * @param loop defines if you want animation to loop (off by default)
  27288. * @param speedRatio defines the speed ratio to apply to all animations
  27289. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27290. * @returns the list of animatables created for all nodes
  27291. */
  27292. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27293. var children = target.getDescendants(directDescendantsOnly);
  27294. var result = [];
  27295. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27296. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27297. var child = children_1[_i];
  27298. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27299. }
  27300. return result;
  27301. };
  27302. /**
  27303. * Gets the animatable associated with a specific target
  27304. * @param target defines the target of the animatable
  27305. * @returns the required animatable if found
  27306. */
  27307. Scene.prototype.getAnimatableByTarget = function (target) {
  27308. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27309. if (this._activeAnimatables[index].target === target) {
  27310. return this._activeAnimatables[index];
  27311. }
  27312. }
  27313. return null;
  27314. };
  27315. /**
  27316. * Gets all animatables associated with a given target
  27317. * @param target defines the target to look animatables for
  27318. * @returns an array of Animatables
  27319. */
  27320. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27321. var result = [];
  27322. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27323. if (this._activeAnimatables[index].target === target) {
  27324. result.push(this._activeAnimatables[index]);
  27325. }
  27326. }
  27327. return result;
  27328. };
  27329. Object.defineProperty(Scene.prototype, "animatables", {
  27330. /**
  27331. * Gets all animatable attached to the scene
  27332. */
  27333. get: function () {
  27334. return this._activeAnimatables;
  27335. },
  27336. enumerable: true,
  27337. configurable: true
  27338. });
  27339. /**
  27340. * Will stop the animation of the given target
  27341. * @param target - the target
  27342. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27343. * @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)
  27344. */
  27345. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27346. var animatables = this.getAllAnimatablesByTarget(target);
  27347. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27348. var animatable = animatables_1[_i];
  27349. animatable.stop(animationName, targetMask);
  27350. }
  27351. };
  27352. /**
  27353. * Stops and removes all animations that have been applied to the scene
  27354. */
  27355. Scene.prototype.stopAllAnimations = function () {
  27356. if (this._activeAnimatables) {
  27357. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27358. this._activeAnimatables[i].stop();
  27359. }
  27360. this._activeAnimatables = [];
  27361. }
  27362. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27363. var group = _a[_i];
  27364. group.stop();
  27365. }
  27366. };
  27367. Scene.prototype._animate = function () {
  27368. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27369. return;
  27370. }
  27371. // Getting time
  27372. var now = BABYLON.Tools.Now;
  27373. if (!this._animationTimeLast) {
  27374. if (this._pendingData.length > 0) {
  27375. return;
  27376. }
  27377. this._animationTimeLast = now;
  27378. }
  27379. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27380. this._animationTime += deltaTime;
  27381. this._animationTimeLast = now;
  27382. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27383. this._activeAnimatables[index]._animate(this._animationTime);
  27384. }
  27385. // Late animation bindings
  27386. this._processLateAnimationBindings();
  27387. };
  27388. /** @hidden */
  27389. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27390. var target = runtimeAnimation.target;
  27391. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27392. if (!target._lateAnimationHolders) {
  27393. target._lateAnimationHolders = {};
  27394. }
  27395. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27396. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27397. totalWeight: 0,
  27398. animations: [],
  27399. originalValue: originalValue
  27400. };
  27401. }
  27402. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27403. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27404. };
  27405. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27406. var normalizer = 1.0;
  27407. var finalPosition = BABYLON.Tmp.Vector3[0];
  27408. var finalScaling = BABYLON.Tmp.Vector3[1];
  27409. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27410. var startIndex = 0;
  27411. var originalAnimation = holder.animations[0];
  27412. var originalValue = holder.originalValue;
  27413. var scale = 1;
  27414. if (holder.totalWeight < 1.0) {
  27415. // We need to mix the original value in
  27416. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27417. scale = 1.0 - holder.totalWeight;
  27418. }
  27419. else {
  27420. startIndex = 1;
  27421. // We need to normalize the weights
  27422. normalizer = holder.totalWeight;
  27423. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27424. scale = originalAnimation.weight / normalizer;
  27425. if (scale == 1) {
  27426. return originalAnimation.currentValue;
  27427. }
  27428. }
  27429. finalScaling.scaleInPlace(scale);
  27430. finalPosition.scaleInPlace(scale);
  27431. finalQuaternion.scaleInPlace(scale);
  27432. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27433. var runtimeAnimation = holder.animations[animIndex];
  27434. var scale = runtimeAnimation.weight / normalizer;
  27435. var currentPosition = BABYLON.Tmp.Vector3[2];
  27436. var currentScaling = BABYLON.Tmp.Vector3[3];
  27437. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27438. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27439. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27440. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27441. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27442. }
  27443. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27444. return originalAnimation._workValue;
  27445. };
  27446. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27447. var originalAnimation = holder.animations[0];
  27448. var originalValue = holder.originalValue;
  27449. if (holder.animations.length === 1) {
  27450. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27451. return refQuaternion;
  27452. }
  27453. var normalizer = 1.0;
  27454. var quaternions;
  27455. var weights;
  27456. if (holder.totalWeight < 1.0) {
  27457. var scale = 1.0 - holder.totalWeight;
  27458. quaternions = [];
  27459. weights = [];
  27460. quaternions.push(originalValue);
  27461. weights.push(scale);
  27462. }
  27463. else {
  27464. if (holder.animations.length === 2) { // Slerp as soon as we can
  27465. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27466. return refQuaternion;
  27467. }
  27468. quaternions = [];
  27469. weights = [];
  27470. normalizer = holder.totalWeight;
  27471. }
  27472. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27473. var runtimeAnimation = holder.animations[animIndex];
  27474. quaternions.push(runtimeAnimation.currentValue);
  27475. weights.push(runtimeAnimation.weight / normalizer);
  27476. }
  27477. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27478. var cumulativeAmount = 0;
  27479. var cumulativeQuaternion = null;
  27480. for (var index = 0; index < quaternions.length;) {
  27481. if (!cumulativeQuaternion) {
  27482. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27483. cumulativeQuaternion = refQuaternion;
  27484. cumulativeAmount = weights[index] + weights[index + 1];
  27485. index += 2;
  27486. continue;
  27487. }
  27488. cumulativeAmount += weights[index];
  27489. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27490. index++;
  27491. }
  27492. return cumulativeQuaternion;
  27493. };
  27494. Scene.prototype._processLateAnimationBindings = function () {
  27495. if (!this._registeredForLateAnimationBindings.length) {
  27496. return;
  27497. }
  27498. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27499. var target = this._registeredForLateAnimationBindings.data[index];
  27500. for (var path in target._lateAnimationHolders) {
  27501. var holder = target._lateAnimationHolders[path];
  27502. var originalAnimation = holder.animations[0];
  27503. var originalValue = holder.originalValue;
  27504. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27505. var finalValue = target[path];
  27506. if (matrixDecomposeMode) {
  27507. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27508. }
  27509. else {
  27510. var quaternionMode = originalValue.w !== undefined;
  27511. if (quaternionMode) {
  27512. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27513. }
  27514. else {
  27515. var startIndex = 0;
  27516. var normalizer = 1.0;
  27517. if (holder.totalWeight < 1.0) {
  27518. // We need to mix the original value in
  27519. if (originalValue.scale) {
  27520. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27521. }
  27522. else {
  27523. finalValue = originalValue * (1.0 - holder.totalWeight);
  27524. }
  27525. }
  27526. else {
  27527. // We need to normalize the weights
  27528. normalizer = holder.totalWeight;
  27529. var scale_1 = originalAnimation.weight / normalizer;
  27530. if (scale_1 !== 1) {
  27531. if (originalAnimation.currentValue.scale) {
  27532. finalValue = originalAnimation.currentValue.scale(scale_1);
  27533. }
  27534. else {
  27535. finalValue = originalAnimation.currentValue * scale_1;
  27536. }
  27537. }
  27538. else {
  27539. finalValue = originalAnimation.currentValue;
  27540. }
  27541. startIndex = 1;
  27542. }
  27543. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27544. var runtimeAnimation = holder.animations[animIndex];
  27545. var scale = runtimeAnimation.weight / normalizer;
  27546. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27547. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27548. }
  27549. else {
  27550. finalValue += runtimeAnimation.currentValue * scale;
  27551. }
  27552. }
  27553. }
  27554. }
  27555. target[path] = finalValue;
  27556. }
  27557. target._lateAnimationHolders = {};
  27558. }
  27559. this._registeredForLateAnimationBindings.reset();
  27560. };
  27561. // Matrix
  27562. /** @hidden */
  27563. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27564. this._useAlternateCameraConfiguration = active;
  27565. };
  27566. /**
  27567. * Gets the current view matrix
  27568. * @returns a Matrix
  27569. */
  27570. Scene.prototype.getViewMatrix = function () {
  27571. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27572. };
  27573. /**
  27574. * Gets the current projection matrix
  27575. * @returns a Matrix
  27576. */
  27577. Scene.prototype.getProjectionMatrix = function () {
  27578. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27579. };
  27580. /**
  27581. * Gets the current transform matrix
  27582. * @returns a Matrix made of View * Projection
  27583. */
  27584. Scene.prototype.getTransformMatrix = function () {
  27585. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27586. };
  27587. /**
  27588. * Sets the current transform matrix
  27589. * @param view defines the View matrix to use
  27590. * @param projection defines the Projection matrix to use
  27591. */
  27592. Scene.prototype.setTransformMatrix = function (view, projection) {
  27593. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27594. return;
  27595. }
  27596. this._viewUpdateFlag = view.updateFlag;
  27597. this._projectionUpdateFlag = projection.updateFlag;
  27598. this._viewMatrix = view;
  27599. this._projectionMatrix = projection;
  27600. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27601. // Update frustum
  27602. if (!this._frustumPlanes) {
  27603. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27604. }
  27605. else {
  27606. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27607. }
  27608. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27609. var otherCamera = this.activeCamera._alternateCamera;
  27610. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27611. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27612. }
  27613. if (this._sceneUbo.useUbo) {
  27614. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27615. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27616. this._sceneUbo.update();
  27617. }
  27618. };
  27619. /** @hidden */
  27620. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27621. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27622. return;
  27623. }
  27624. this._alternateViewUpdateFlag = view.updateFlag;
  27625. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27626. this._alternateViewMatrix = view;
  27627. this._alternateProjectionMatrix = projection;
  27628. if (!this._alternateTransformMatrix) {
  27629. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27630. }
  27631. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27632. if (!this._alternateSceneUbo) {
  27633. this._createAlternateUbo();
  27634. }
  27635. if (this._alternateSceneUbo.useUbo) {
  27636. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27637. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27638. this._alternateSceneUbo.update();
  27639. }
  27640. };
  27641. /**
  27642. * Gets the uniform buffer used to store scene data
  27643. * @returns a UniformBuffer
  27644. */
  27645. Scene.prototype.getSceneUniformBuffer = function () {
  27646. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27647. };
  27648. /**
  27649. * Gets an unique (relatively to the current scene) Id
  27650. * @returns an unique number for the scene
  27651. */
  27652. Scene.prototype.getUniqueId = function () {
  27653. var result = Scene._uniqueIdCounter;
  27654. Scene._uniqueIdCounter++;
  27655. return result;
  27656. };
  27657. /**
  27658. * Add a mesh to the list of scene's meshes
  27659. * @param newMesh defines the mesh to add
  27660. * @param recursive if all child meshes should also be added to the scene
  27661. */
  27662. Scene.prototype.addMesh = function (newMesh, recursive) {
  27663. var _this = this;
  27664. if (recursive === void 0) { recursive = false; }
  27665. this.meshes.push(newMesh);
  27666. //notify the collision coordinator
  27667. if (this.collisionCoordinator) {
  27668. this.collisionCoordinator.onMeshAdded(newMesh);
  27669. }
  27670. newMesh._resyncLightSources();
  27671. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27672. if (recursive) {
  27673. newMesh.getChildMeshes().forEach(function (m) {
  27674. _this.addMesh(m);
  27675. });
  27676. }
  27677. };
  27678. /**
  27679. * Remove a mesh for the list of scene's meshes
  27680. * @param toRemove defines the mesh to remove
  27681. * @param recursive if all child meshes should also be removed from the scene
  27682. * @returns the index where the mesh was in the mesh list
  27683. */
  27684. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27685. var _this = this;
  27686. if (recursive === void 0) { recursive = false; }
  27687. var index = this.meshes.indexOf(toRemove);
  27688. if (index !== -1) {
  27689. // Remove from the scene if mesh found
  27690. this.meshes.splice(index, 1);
  27691. }
  27692. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27693. if (recursive) {
  27694. toRemove.getChildMeshes().forEach(function (m) {
  27695. _this.removeMesh(m);
  27696. });
  27697. }
  27698. return index;
  27699. };
  27700. /**
  27701. * Add a transform node to the list of scene's transform nodes
  27702. * @param newTransformNode defines the transform node to add
  27703. */
  27704. Scene.prototype.addTransformNode = function (newTransformNode) {
  27705. this.transformNodes.push(newTransformNode);
  27706. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27707. };
  27708. /**
  27709. * Remove a transform node for the list of scene's transform nodes
  27710. * @param toRemove defines the transform node to remove
  27711. * @returns the index where the transform node was in the transform node list
  27712. */
  27713. Scene.prototype.removeTransformNode = function (toRemove) {
  27714. var index = this.transformNodes.indexOf(toRemove);
  27715. if (index !== -1) {
  27716. // Remove from the scene if found
  27717. this.transformNodes.splice(index, 1);
  27718. }
  27719. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27720. return index;
  27721. };
  27722. /**
  27723. * Remove a skeleton for the list of scene's skeletons
  27724. * @param toRemove defines the skeleton to remove
  27725. * @returns the index where the skeleton was in the skeleton list
  27726. */
  27727. Scene.prototype.removeSkeleton = function (toRemove) {
  27728. var index = this.skeletons.indexOf(toRemove);
  27729. if (index !== -1) {
  27730. // Remove from the scene if found
  27731. this.skeletons.splice(index, 1);
  27732. }
  27733. return index;
  27734. };
  27735. /**
  27736. * Remove a morph target for the list of scene's morph targets
  27737. * @param toRemove defines the morph target to remove
  27738. * @returns the index where the morph target was in the morph target list
  27739. */
  27740. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27741. var index = this.morphTargetManagers.indexOf(toRemove);
  27742. if (index !== -1) {
  27743. // Remove from the scene if found
  27744. this.morphTargetManagers.splice(index, 1);
  27745. }
  27746. return index;
  27747. };
  27748. /**
  27749. * Remove a light for the list of scene's lights
  27750. * @param toRemove defines the light to remove
  27751. * @returns the index where the light was in the light list
  27752. */
  27753. Scene.prototype.removeLight = function (toRemove) {
  27754. var index = this.lights.indexOf(toRemove);
  27755. if (index !== -1) {
  27756. // Remove from meshes
  27757. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27758. var mesh = _a[_i];
  27759. mesh._removeLightSource(toRemove);
  27760. }
  27761. // Remove from the scene if mesh found
  27762. this.lights.splice(index, 1);
  27763. this.sortLightsByPriority();
  27764. }
  27765. this.onLightRemovedObservable.notifyObservers(toRemove);
  27766. return index;
  27767. };
  27768. /**
  27769. * Remove a camera for the list of scene's cameras
  27770. * @param toRemove defines the camera to remove
  27771. * @returns the index where the camera was in the camera list
  27772. */
  27773. Scene.prototype.removeCamera = function (toRemove) {
  27774. var index = this.cameras.indexOf(toRemove);
  27775. if (index !== -1) {
  27776. // Remove from the scene if mesh found
  27777. this.cameras.splice(index, 1);
  27778. }
  27779. // Remove from activeCameras
  27780. var index2 = this.activeCameras.indexOf(toRemove);
  27781. if (index2 !== -1) {
  27782. // Remove from the scene if mesh found
  27783. this.activeCameras.splice(index2, 1);
  27784. }
  27785. // Reset the activeCamera
  27786. if (this.activeCamera === toRemove) {
  27787. if (this.cameras.length > 0) {
  27788. this.activeCamera = this.cameras[0];
  27789. }
  27790. else {
  27791. this.activeCamera = null;
  27792. }
  27793. }
  27794. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27795. return index;
  27796. };
  27797. /**
  27798. * Remove a particle system for the list of scene's particle systems
  27799. * @param toRemove defines the particle system to remove
  27800. * @returns the index where the particle system was in the particle system list
  27801. */
  27802. Scene.prototype.removeParticleSystem = function (toRemove) {
  27803. var index = this.particleSystems.indexOf(toRemove);
  27804. if (index !== -1) {
  27805. this.particleSystems.splice(index, 1);
  27806. }
  27807. return index;
  27808. };
  27809. /**
  27810. * Remove a animation for the list of scene's animations
  27811. * @param toRemove defines the animation to remove
  27812. * @returns the index where the animation was in the animation list
  27813. */
  27814. Scene.prototype.removeAnimation = function (toRemove) {
  27815. var index = this.animations.indexOf(toRemove);
  27816. if (index !== -1) {
  27817. this.animations.splice(index, 1);
  27818. }
  27819. return index;
  27820. };
  27821. /**
  27822. * Removes the given animation group from this scene.
  27823. * @param toRemove The animation group to remove
  27824. * @returns The index of the removed animation group
  27825. */
  27826. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27827. var index = this.animationGroups.indexOf(toRemove);
  27828. if (index !== -1) {
  27829. this.animationGroups.splice(index, 1);
  27830. }
  27831. return index;
  27832. };
  27833. /**
  27834. * Removes the given multi-material from this scene.
  27835. * @param toRemove The multi-material to remove
  27836. * @returns The index of the removed multi-material
  27837. */
  27838. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27839. var index = this.multiMaterials.indexOf(toRemove);
  27840. if (index !== -1) {
  27841. this.multiMaterials.splice(index, 1);
  27842. }
  27843. return index;
  27844. };
  27845. /**
  27846. * Removes the given material from this scene.
  27847. * @param toRemove The material to remove
  27848. * @returns The index of the removed material
  27849. */
  27850. Scene.prototype.removeMaterial = function (toRemove) {
  27851. var index = this.materials.indexOf(toRemove);
  27852. if (index !== -1) {
  27853. this.materials.splice(index, 1);
  27854. }
  27855. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27856. return index;
  27857. };
  27858. /**
  27859. * Removes the given action manager from this scene.
  27860. * @param toRemove The action manager to remove
  27861. * @returns The index of the removed action manager
  27862. */
  27863. Scene.prototype.removeActionManager = function (toRemove) {
  27864. var index = this.actionManagers.indexOf(toRemove);
  27865. if (index !== -1) {
  27866. this.actionManagers.splice(index, 1);
  27867. }
  27868. return index;
  27869. };
  27870. /**
  27871. * Removes the given texture from this scene.
  27872. * @param toRemove The texture to remove
  27873. * @returns The index of the removed texture
  27874. */
  27875. Scene.prototype.removeTexture = function (toRemove) {
  27876. var index = this.textures.indexOf(toRemove);
  27877. if (index !== -1) {
  27878. this.textures.splice(index, 1);
  27879. }
  27880. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27881. return index;
  27882. };
  27883. /**
  27884. * Adds the given light to this scene
  27885. * @param newLight The light to add
  27886. */
  27887. Scene.prototype.addLight = function (newLight) {
  27888. this.lights.push(newLight);
  27889. this.sortLightsByPriority();
  27890. // Add light to all meshes (To support if the light is removed and then readded)
  27891. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27892. var mesh = _a[_i];
  27893. if (mesh._lightSources.indexOf(newLight) === -1) {
  27894. mesh._lightSources.push(newLight);
  27895. mesh._resyncLightSources();
  27896. }
  27897. }
  27898. this.onNewLightAddedObservable.notifyObservers(newLight);
  27899. };
  27900. /**
  27901. * Sorts the list list based on light priorities
  27902. */
  27903. Scene.prototype.sortLightsByPriority = function () {
  27904. if (this.requireLightSorting) {
  27905. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27906. }
  27907. };
  27908. /**
  27909. * Adds the given camera to this scene
  27910. * @param newCamera The camera to add
  27911. */
  27912. Scene.prototype.addCamera = function (newCamera) {
  27913. this.cameras.push(newCamera);
  27914. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27915. };
  27916. /**
  27917. * Adds the given skeleton to this scene
  27918. * @param newSkeleton The skeleton to add
  27919. */
  27920. Scene.prototype.addSkeleton = function (newSkeleton) {
  27921. this.skeletons.push(newSkeleton);
  27922. };
  27923. /**
  27924. * Adds the given particle system to this scene
  27925. * @param newParticleSystem The particle system to add
  27926. */
  27927. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27928. this.particleSystems.push(newParticleSystem);
  27929. };
  27930. /**
  27931. * Adds the given animation to this scene
  27932. * @param newAnimation The animation to add
  27933. */
  27934. Scene.prototype.addAnimation = function (newAnimation) {
  27935. this.animations.push(newAnimation);
  27936. };
  27937. /**
  27938. * Adds the given animation group to this scene.
  27939. * @param newAnimationGroup The animation group to add
  27940. */
  27941. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27942. this.animationGroups.push(newAnimationGroup);
  27943. };
  27944. /**
  27945. * Adds the given multi-material to this scene
  27946. * @param newMultiMaterial The multi-material to add
  27947. */
  27948. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27949. this.multiMaterials.push(newMultiMaterial);
  27950. };
  27951. /**
  27952. * Adds the given material to this scene
  27953. * @param newMaterial The material to add
  27954. */
  27955. Scene.prototype.addMaterial = function (newMaterial) {
  27956. this.materials.push(newMaterial);
  27957. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27958. };
  27959. /**
  27960. * Adds the given morph target to this scene
  27961. * @param newMorphTargetManager The morph target to add
  27962. */
  27963. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27964. this.morphTargetManagers.push(newMorphTargetManager);
  27965. };
  27966. /**
  27967. * Adds the given geometry to this scene
  27968. * @param newGeometry The geometry to add
  27969. */
  27970. Scene.prototype.addGeometry = function (newGeometry) {
  27971. this.geometries.push(newGeometry);
  27972. };
  27973. /**
  27974. * Adds the given action manager to this scene
  27975. * @param newActionManager The action manager to add
  27976. */
  27977. Scene.prototype.addActionManager = function (newActionManager) {
  27978. this.actionManagers.push(newActionManager);
  27979. };
  27980. /**
  27981. * Adds the given texture to this scene.
  27982. * @param newTexture The texture to add
  27983. */
  27984. Scene.prototype.addTexture = function (newTexture) {
  27985. this.textures.push(newTexture);
  27986. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27987. };
  27988. /**
  27989. * Switch active camera
  27990. * @param newCamera defines the new active camera
  27991. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27992. */
  27993. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27994. if (attachControl === void 0) { attachControl = true; }
  27995. var canvas = this._engine.getRenderingCanvas();
  27996. if (!canvas) {
  27997. return;
  27998. }
  27999. if (this.activeCamera) {
  28000. this.activeCamera.detachControl(canvas);
  28001. }
  28002. this.activeCamera = newCamera;
  28003. if (attachControl) {
  28004. newCamera.attachControl(canvas);
  28005. }
  28006. };
  28007. /**
  28008. * sets the active camera of the scene using its ID
  28009. * @param id defines the camera's ID
  28010. * @return the new active camera or null if none found.
  28011. */
  28012. Scene.prototype.setActiveCameraByID = function (id) {
  28013. var camera = this.getCameraByID(id);
  28014. if (camera) {
  28015. this.activeCamera = camera;
  28016. return camera;
  28017. }
  28018. return null;
  28019. };
  28020. /**
  28021. * sets the active camera of the scene using its name
  28022. * @param name defines the camera's name
  28023. * @returns the new active camera or null if none found.
  28024. */
  28025. Scene.prototype.setActiveCameraByName = function (name) {
  28026. var camera = this.getCameraByName(name);
  28027. if (camera) {
  28028. this.activeCamera = camera;
  28029. return camera;
  28030. }
  28031. return null;
  28032. };
  28033. /**
  28034. * get an animation group using its name
  28035. * @param name defines the material's name
  28036. * @return the animation group or null if none found.
  28037. */
  28038. Scene.prototype.getAnimationGroupByName = function (name) {
  28039. for (var index = 0; index < this.animationGroups.length; index++) {
  28040. if (this.animationGroups[index].name === name) {
  28041. return this.animationGroups[index];
  28042. }
  28043. }
  28044. return null;
  28045. };
  28046. /**
  28047. * get a material using its id
  28048. * @param id defines the material's ID
  28049. * @return the material or null if none found.
  28050. */
  28051. Scene.prototype.getMaterialByID = function (id) {
  28052. for (var index = 0; index < this.materials.length; index++) {
  28053. if (this.materials[index].id === id) {
  28054. return this.materials[index];
  28055. }
  28056. }
  28057. return null;
  28058. };
  28059. /**
  28060. * Gets a material using its name
  28061. * @param name defines the material's name
  28062. * @return the material or null if none found.
  28063. */
  28064. Scene.prototype.getMaterialByName = function (name) {
  28065. for (var index = 0; index < this.materials.length; index++) {
  28066. if (this.materials[index].name === name) {
  28067. return this.materials[index];
  28068. }
  28069. }
  28070. return null;
  28071. };
  28072. /**
  28073. * Gets a camera using its id
  28074. * @param id defines the id to look for
  28075. * @returns the camera or null if not found
  28076. */
  28077. Scene.prototype.getCameraByID = function (id) {
  28078. for (var index = 0; index < this.cameras.length; index++) {
  28079. if (this.cameras[index].id === id) {
  28080. return this.cameras[index];
  28081. }
  28082. }
  28083. return null;
  28084. };
  28085. /**
  28086. * Gets a camera using its unique id
  28087. * @param uniqueId defines the unique id to look for
  28088. * @returns the camera or null if not found
  28089. */
  28090. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28091. for (var index = 0; index < this.cameras.length; index++) {
  28092. if (this.cameras[index].uniqueId === uniqueId) {
  28093. return this.cameras[index];
  28094. }
  28095. }
  28096. return null;
  28097. };
  28098. /**
  28099. * Gets a camera using its name
  28100. * @param name defines the camera's name
  28101. * @return the camera or null if none found.
  28102. */
  28103. Scene.prototype.getCameraByName = function (name) {
  28104. for (var index = 0; index < this.cameras.length; index++) {
  28105. if (this.cameras[index].name === name) {
  28106. return this.cameras[index];
  28107. }
  28108. }
  28109. return null;
  28110. };
  28111. /**
  28112. * Gets a bone using its id
  28113. * @param id defines the bone's id
  28114. * @return the bone or null if not found
  28115. */
  28116. Scene.prototype.getBoneByID = function (id) {
  28117. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28118. var skeleton = this.skeletons[skeletonIndex];
  28119. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28120. if (skeleton.bones[boneIndex].id === id) {
  28121. return skeleton.bones[boneIndex];
  28122. }
  28123. }
  28124. }
  28125. return null;
  28126. };
  28127. /**
  28128. * Gets a bone using its id
  28129. * @param name defines the bone's name
  28130. * @return the bone or null if not found
  28131. */
  28132. Scene.prototype.getBoneByName = function (name) {
  28133. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28134. var skeleton = this.skeletons[skeletonIndex];
  28135. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28136. if (skeleton.bones[boneIndex].name === name) {
  28137. return skeleton.bones[boneIndex];
  28138. }
  28139. }
  28140. }
  28141. return null;
  28142. };
  28143. /**
  28144. * Gets a light node using its name
  28145. * @param name defines the the light's name
  28146. * @return the light or null if none found.
  28147. */
  28148. Scene.prototype.getLightByName = function (name) {
  28149. for (var index = 0; index < this.lights.length; index++) {
  28150. if (this.lights[index].name === name) {
  28151. return this.lights[index];
  28152. }
  28153. }
  28154. return null;
  28155. };
  28156. /**
  28157. * Gets a light node using its id
  28158. * @param id defines the light's id
  28159. * @return the light or null if none found.
  28160. */
  28161. Scene.prototype.getLightByID = function (id) {
  28162. for (var index = 0; index < this.lights.length; index++) {
  28163. if (this.lights[index].id === id) {
  28164. return this.lights[index];
  28165. }
  28166. }
  28167. return null;
  28168. };
  28169. /**
  28170. * Gets a light node using its scene-generated unique ID
  28171. * @param uniqueId defines the light's unique id
  28172. * @return the light or null if none found.
  28173. */
  28174. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28175. for (var index = 0; index < this.lights.length; index++) {
  28176. if (this.lights[index].uniqueId === uniqueId) {
  28177. return this.lights[index];
  28178. }
  28179. }
  28180. return null;
  28181. };
  28182. /**
  28183. * Gets a particle system by id
  28184. * @param id defines the particle system id
  28185. * @return the corresponding system or null if none found
  28186. */
  28187. Scene.prototype.getParticleSystemByID = function (id) {
  28188. for (var index = 0; index < this.particleSystems.length; index++) {
  28189. if (this.particleSystems[index].id === id) {
  28190. return this.particleSystems[index];
  28191. }
  28192. }
  28193. return null;
  28194. };
  28195. /**
  28196. * Gets a geometry using its ID
  28197. * @param id defines the geometry's id
  28198. * @return the geometry or null if none found.
  28199. */
  28200. Scene.prototype.getGeometryByID = function (id) {
  28201. for (var index = 0; index < this.geometries.length; index++) {
  28202. if (this.geometries[index].id === id) {
  28203. return this.geometries[index];
  28204. }
  28205. }
  28206. return null;
  28207. };
  28208. /**
  28209. * Add a new geometry to this scene
  28210. * @param geometry defines the geometry to be added to the scene.
  28211. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28212. * @return a boolean defining if the geometry was added or not
  28213. */
  28214. Scene.prototype.pushGeometry = function (geometry, force) {
  28215. if (!force && this.getGeometryByID(geometry.id)) {
  28216. return false;
  28217. }
  28218. this.geometries.push(geometry);
  28219. //notify the collision coordinator
  28220. if (this.collisionCoordinator) {
  28221. this.collisionCoordinator.onGeometryAdded(geometry);
  28222. }
  28223. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28224. return true;
  28225. };
  28226. /**
  28227. * Removes an existing geometry
  28228. * @param geometry defines the geometry to be removed from the scene
  28229. * @return a boolean defining if the geometry was removed or not
  28230. */
  28231. Scene.prototype.removeGeometry = function (geometry) {
  28232. var index = this.geometries.indexOf(geometry);
  28233. if (index > -1) {
  28234. this.geometries.splice(index, 1);
  28235. //notify the collision coordinator
  28236. if (this.collisionCoordinator) {
  28237. this.collisionCoordinator.onGeometryDeleted(geometry);
  28238. }
  28239. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28240. return true;
  28241. }
  28242. return false;
  28243. };
  28244. /**
  28245. * Gets the list of geometries attached to the scene
  28246. * @returns an array of Geometry
  28247. */
  28248. Scene.prototype.getGeometries = function () {
  28249. return this.geometries;
  28250. };
  28251. /**
  28252. * Gets the first added mesh found of a given ID
  28253. * @param id defines the id to search for
  28254. * @return the mesh found or null if not found at all
  28255. */
  28256. Scene.prototype.getMeshByID = function (id) {
  28257. for (var index = 0; index < this.meshes.length; index++) {
  28258. if (this.meshes[index].id === id) {
  28259. return this.meshes[index];
  28260. }
  28261. }
  28262. return null;
  28263. };
  28264. /**
  28265. * Gets a list of meshes using their id
  28266. * @param id defines the id to search for
  28267. * @returns a list of meshes
  28268. */
  28269. Scene.prototype.getMeshesByID = function (id) {
  28270. return this.meshes.filter(function (m) {
  28271. return m.id === id;
  28272. });
  28273. };
  28274. /**
  28275. * Gets the first added transform node found of a given ID
  28276. * @param id defines the id to search for
  28277. * @return the found transform node or null if not found at all.
  28278. */
  28279. Scene.prototype.getTransformNodeByID = function (id) {
  28280. for (var index = 0; index < this.transformNodes.length; index++) {
  28281. if (this.transformNodes[index].id === id) {
  28282. return this.transformNodes[index];
  28283. }
  28284. }
  28285. return null;
  28286. };
  28287. /**
  28288. * Gets a list of transform nodes using their id
  28289. * @param id defines the id to search for
  28290. * @returns a list of transform nodes
  28291. */
  28292. Scene.prototype.getTransformNodesByID = function (id) {
  28293. return this.transformNodes.filter(function (m) {
  28294. return m.id === id;
  28295. });
  28296. };
  28297. /**
  28298. * Gets a mesh with its auto-generated unique id
  28299. * @param uniqueId defines the unique id to search for
  28300. * @return the found mesh or null if not found at all.
  28301. */
  28302. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28303. for (var index = 0; index < this.meshes.length; index++) {
  28304. if (this.meshes[index].uniqueId === uniqueId) {
  28305. return this.meshes[index];
  28306. }
  28307. }
  28308. return null;
  28309. };
  28310. /**
  28311. * Gets a the last added mesh using a given id
  28312. * @param id defines the id to search for
  28313. * @return the found mesh or null if not found at all.
  28314. */
  28315. Scene.prototype.getLastMeshByID = function (id) {
  28316. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28317. if (this.meshes[index].id === id) {
  28318. return this.meshes[index];
  28319. }
  28320. }
  28321. return null;
  28322. };
  28323. /**
  28324. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28325. * @param id defines the id to search for
  28326. * @return the found node or null if not found at all
  28327. */
  28328. Scene.prototype.getLastEntryByID = function (id) {
  28329. var index;
  28330. for (index = this.meshes.length - 1; index >= 0; index--) {
  28331. if (this.meshes[index].id === id) {
  28332. return this.meshes[index];
  28333. }
  28334. }
  28335. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28336. if (this.transformNodes[index].id === id) {
  28337. return this.transformNodes[index];
  28338. }
  28339. }
  28340. for (index = this.cameras.length - 1; index >= 0; index--) {
  28341. if (this.cameras[index].id === id) {
  28342. return this.cameras[index];
  28343. }
  28344. }
  28345. for (index = this.lights.length - 1; index >= 0; index--) {
  28346. if (this.lights[index].id === id) {
  28347. return this.lights[index];
  28348. }
  28349. }
  28350. return null;
  28351. };
  28352. /**
  28353. * Gets a node (Mesh, Camera, Light) using a given id
  28354. * @param id defines the id to search for
  28355. * @return the found node or null if not found at all
  28356. */
  28357. Scene.prototype.getNodeByID = function (id) {
  28358. var mesh = this.getMeshByID(id);
  28359. if (mesh) {
  28360. return mesh;
  28361. }
  28362. var light = this.getLightByID(id);
  28363. if (light) {
  28364. return light;
  28365. }
  28366. var camera = this.getCameraByID(id);
  28367. if (camera) {
  28368. return camera;
  28369. }
  28370. var bone = this.getBoneByID(id);
  28371. return bone;
  28372. };
  28373. /**
  28374. * Gets a node (Mesh, Camera, Light) using a given name
  28375. * @param name defines the name to search for
  28376. * @return the found node or null if not found at all.
  28377. */
  28378. Scene.prototype.getNodeByName = function (name) {
  28379. var mesh = this.getMeshByName(name);
  28380. if (mesh) {
  28381. return mesh;
  28382. }
  28383. var light = this.getLightByName(name);
  28384. if (light) {
  28385. return light;
  28386. }
  28387. var camera = this.getCameraByName(name);
  28388. if (camera) {
  28389. return camera;
  28390. }
  28391. var bone = this.getBoneByName(name);
  28392. return bone;
  28393. };
  28394. /**
  28395. * Gets a mesh using a given name
  28396. * @param name defines the name to search for
  28397. * @return the found mesh or null if not found at all.
  28398. */
  28399. Scene.prototype.getMeshByName = function (name) {
  28400. for (var index = 0; index < this.meshes.length; index++) {
  28401. if (this.meshes[index].name === name) {
  28402. return this.meshes[index];
  28403. }
  28404. }
  28405. return null;
  28406. };
  28407. /**
  28408. * Gets a transform node using a given name
  28409. * @param name defines the name to search for
  28410. * @return the found transform node or null if not found at all.
  28411. */
  28412. Scene.prototype.getTransformNodeByName = function (name) {
  28413. for (var index = 0; index < this.transformNodes.length; index++) {
  28414. if (this.transformNodes[index].name === name) {
  28415. return this.transformNodes[index];
  28416. }
  28417. }
  28418. return null;
  28419. };
  28420. /**
  28421. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28422. * @param id defines the id to search for
  28423. * @return the found skeleton or null if not found at all.
  28424. */
  28425. Scene.prototype.getLastSkeletonByID = function (id) {
  28426. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28427. if (this.skeletons[index].id === id) {
  28428. return this.skeletons[index];
  28429. }
  28430. }
  28431. return null;
  28432. };
  28433. /**
  28434. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28435. * @param id defines the id to search for
  28436. * @return the found skeleton or null if not found at all.
  28437. */
  28438. Scene.prototype.getSkeletonById = function (id) {
  28439. for (var index = 0; index < this.skeletons.length; index++) {
  28440. if (this.skeletons[index].id === id) {
  28441. return this.skeletons[index];
  28442. }
  28443. }
  28444. return null;
  28445. };
  28446. /**
  28447. * Gets a skeleton using a given name
  28448. * @param name defines the name to search for
  28449. * @return the found skeleton or null if not found at all.
  28450. */
  28451. Scene.prototype.getSkeletonByName = function (name) {
  28452. for (var index = 0; index < this.skeletons.length; index++) {
  28453. if (this.skeletons[index].name === name) {
  28454. return this.skeletons[index];
  28455. }
  28456. }
  28457. return null;
  28458. };
  28459. /**
  28460. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28461. * @param id defines the id to search for
  28462. * @return the found morph target manager or null if not found at all.
  28463. */
  28464. Scene.prototype.getMorphTargetManagerById = function (id) {
  28465. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28466. if (this.morphTargetManagers[index].uniqueId === id) {
  28467. return this.morphTargetManagers[index];
  28468. }
  28469. }
  28470. return null;
  28471. };
  28472. /**
  28473. * Gets a boolean indicating if the given mesh is active
  28474. * @param mesh defines the mesh to look for
  28475. * @returns true if the mesh is in the active list
  28476. */
  28477. Scene.prototype.isActiveMesh = function (mesh) {
  28478. return (this._activeMeshes.indexOf(mesh) !== -1);
  28479. };
  28480. Object.defineProperty(Scene.prototype, "uid", {
  28481. /**
  28482. * Return a unique id as a string which can serve as an identifier for the scene
  28483. */
  28484. get: function () {
  28485. if (!this._uid) {
  28486. this._uid = BABYLON.Tools.RandomId();
  28487. }
  28488. return this._uid;
  28489. },
  28490. enumerable: true,
  28491. configurable: true
  28492. });
  28493. /**
  28494. * Add an externaly attached data from its key.
  28495. * This method call will fail and return false, if such key already exists.
  28496. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28497. * @param key the unique key that identifies the data
  28498. * @param data the data object to associate to the key for this Engine instance
  28499. * @return true if no such key were already present and the data was added successfully, false otherwise
  28500. */
  28501. Scene.prototype.addExternalData = function (key, data) {
  28502. if (!this._externalData) {
  28503. this._externalData = new BABYLON.StringDictionary();
  28504. }
  28505. return this._externalData.add(key, data);
  28506. };
  28507. /**
  28508. * Get an externaly attached data from its key
  28509. * @param key the unique key that identifies the data
  28510. * @return the associated data, if present (can be null), or undefined if not present
  28511. */
  28512. Scene.prototype.getExternalData = function (key) {
  28513. if (!this._externalData) {
  28514. return null;
  28515. }
  28516. return this._externalData.get(key);
  28517. };
  28518. /**
  28519. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28520. * @param key the unique key that identifies the data
  28521. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28522. * @return the associated data, can be null if the factory returned null.
  28523. */
  28524. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28525. if (!this._externalData) {
  28526. this._externalData = new BABYLON.StringDictionary();
  28527. }
  28528. return this._externalData.getOrAddWithFactory(key, factory);
  28529. };
  28530. /**
  28531. * Remove an externaly attached data from the Engine instance
  28532. * @param key the unique key that identifies the data
  28533. * @return true if the data was successfully removed, false if it doesn't exist
  28534. */
  28535. Scene.prototype.removeExternalData = function (key) {
  28536. return this._externalData.remove(key);
  28537. };
  28538. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28539. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28540. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28541. var step = _a[_i];
  28542. step.action(mesh, subMesh);
  28543. }
  28544. var material = subMesh.getMaterial();
  28545. if (material !== null && material !== undefined) {
  28546. // Render targets
  28547. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28548. if (this._processedMaterials.indexOf(material) === -1) {
  28549. this._processedMaterials.push(material);
  28550. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28551. }
  28552. }
  28553. // Dispatch
  28554. this._activeIndices.addCount(subMesh.indexCount, false);
  28555. this._renderingManager.dispatch(subMesh, mesh, material);
  28556. }
  28557. }
  28558. };
  28559. /**
  28560. * Clear the processed materials smart array preventing retention point in material dispose.
  28561. */
  28562. Scene.prototype.freeProcessedMaterials = function () {
  28563. this._processedMaterials.dispose();
  28564. };
  28565. /**
  28566. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28567. */
  28568. Scene.prototype.freeActiveMeshes = function () {
  28569. this._activeMeshes.dispose();
  28570. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28571. this.activeCamera._activeMeshes.dispose();
  28572. }
  28573. if (this.activeCameras) {
  28574. for (var i = 0; i < this.activeCameras.length; i++) {
  28575. var activeCamera = this.activeCameras[i];
  28576. if (activeCamera && activeCamera._activeMeshes) {
  28577. activeCamera._activeMeshes.dispose();
  28578. }
  28579. }
  28580. }
  28581. };
  28582. /**
  28583. * Clear the info related to rendering groups preventing retention points during dispose.
  28584. */
  28585. Scene.prototype.freeRenderingGroups = function () {
  28586. if (this._renderingManager) {
  28587. this._renderingManager.freeRenderingGroups();
  28588. }
  28589. if (this.textures) {
  28590. for (var i = 0; i < this.textures.length; i++) {
  28591. var texture = this.textures[i];
  28592. if (texture && texture.renderList) {
  28593. texture.freeRenderingGroups();
  28594. }
  28595. }
  28596. }
  28597. };
  28598. /** @hidden */
  28599. Scene.prototype._isInIntermediateRendering = function () {
  28600. return this._intermediateRendering;
  28601. };
  28602. /**
  28603. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28604. * @returns the current scene
  28605. */
  28606. Scene.prototype.freezeActiveMeshes = function () {
  28607. if (!this.activeCamera) {
  28608. return this;
  28609. }
  28610. if (!this._frustumPlanes) {
  28611. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28612. }
  28613. this._evaluateActiveMeshes();
  28614. this._activeMeshesFrozen = true;
  28615. return this;
  28616. };
  28617. /**
  28618. * Use this function to restart evaluating active meshes on every frame
  28619. * @returns the current scene
  28620. */
  28621. Scene.prototype.unfreezeActiveMeshes = function () {
  28622. this._activeMeshesFrozen = false;
  28623. return this;
  28624. };
  28625. Scene.prototype._evaluateActiveMeshes = function () {
  28626. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28627. return;
  28628. }
  28629. if (!this.activeCamera) {
  28630. return;
  28631. }
  28632. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28633. this.activeCamera._activeMeshes.reset();
  28634. this._activeMeshes.reset();
  28635. this._renderingManager.reset();
  28636. this._processedMaterials.reset();
  28637. this._activeParticleSystems.reset();
  28638. this._activeSkeletons.reset();
  28639. this._softwareSkinnedMeshes.reset();
  28640. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28641. var step = _a[_i];
  28642. step.action();
  28643. }
  28644. // Determine mesh candidates
  28645. var meshes = this.getActiveMeshCandidates();
  28646. // Check each mesh
  28647. var len = meshes.length;
  28648. for (var i = 0; i < len; i++) {
  28649. var mesh = meshes.data[i];
  28650. if (mesh.isBlocked) {
  28651. continue;
  28652. }
  28653. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28654. if (!mesh.isReady() || !mesh.isEnabled()) {
  28655. continue;
  28656. }
  28657. mesh.computeWorldMatrix();
  28658. // Intersections
  28659. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28660. this._meshesForIntersections.pushNoDuplicate(mesh);
  28661. }
  28662. // Switch to current LOD
  28663. var meshLOD = mesh.getLOD(this.activeCamera);
  28664. if (meshLOD === undefined || meshLOD === null) {
  28665. continue;
  28666. }
  28667. mesh._preActivate();
  28668. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28669. this._activeMeshes.push(mesh);
  28670. this.activeCamera._activeMeshes.push(mesh);
  28671. mesh._activate(this._renderId);
  28672. if (meshLOD !== mesh) {
  28673. meshLOD._activate(this._renderId);
  28674. }
  28675. this._activeMesh(mesh, meshLOD);
  28676. }
  28677. }
  28678. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28679. // Particle systems
  28680. if (this.particlesEnabled) {
  28681. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28682. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28683. var particleSystem = this.particleSystems[particleIndex];
  28684. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28685. continue;
  28686. }
  28687. var emitter = particleSystem.emitter;
  28688. if (!emitter.position || emitter.isEnabled()) {
  28689. this._activeParticleSystems.push(particleSystem);
  28690. particleSystem.animate();
  28691. this._renderingManager.dispatchParticles(particleSystem);
  28692. }
  28693. }
  28694. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28695. }
  28696. };
  28697. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28698. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28699. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28700. mesh.skeleton.prepare();
  28701. }
  28702. if (!mesh.computeBonesUsingShaders) {
  28703. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28704. }
  28705. }
  28706. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28707. var step = _a[_i];
  28708. step.action(sourceMesh, mesh);
  28709. }
  28710. if (mesh !== undefined && mesh !== null
  28711. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28712. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28713. var len = subMeshes.length;
  28714. for (var i = 0; i < len; i++) {
  28715. var subMesh = subMeshes.data[i];
  28716. this._evaluateSubMesh(subMesh, mesh);
  28717. }
  28718. }
  28719. };
  28720. /**
  28721. * Update the transform matrix to update from the current active camera
  28722. * @param force defines a boolean used to force the update even if cache is up to date
  28723. */
  28724. Scene.prototype.updateTransformMatrix = function (force) {
  28725. if (!this.activeCamera) {
  28726. return;
  28727. }
  28728. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28729. };
  28730. /**
  28731. * 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)
  28732. * @param alternateCamera defines the camera to use
  28733. */
  28734. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28735. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28736. };
  28737. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28738. if (camera && camera._skipRendering) {
  28739. return;
  28740. }
  28741. var engine = this._engine;
  28742. this.activeCamera = camera;
  28743. if (!this.activeCamera) {
  28744. throw new Error("Active camera not set");
  28745. }
  28746. // Viewport
  28747. engine.setViewport(this.activeCamera.viewport);
  28748. // Camera
  28749. this.resetCachedMaterial();
  28750. this._renderId++;
  28751. this.updateTransformMatrix();
  28752. if (camera._alternateCamera) {
  28753. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28754. this._alternateRendering = true;
  28755. }
  28756. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28757. // Meshes
  28758. this._evaluateActiveMeshes();
  28759. // Software skinning
  28760. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28761. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28762. mesh.applySkeleton(mesh.skeleton);
  28763. }
  28764. // Render targets
  28765. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28766. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28767. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28768. }
  28769. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28770. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28771. }
  28772. // Collects render targets from external components.
  28773. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28774. var step = _a[_i];
  28775. step.action(this._renderTargets);
  28776. }
  28777. if (this.renderTargetsEnabled) {
  28778. this._intermediateRendering = true;
  28779. if (this._renderTargets.length > 0) {
  28780. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28781. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28782. var renderTarget = this._renderTargets.data[renderIndex];
  28783. if (renderTarget._shouldRender()) {
  28784. this._renderId++;
  28785. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28786. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28787. }
  28788. }
  28789. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28790. this._renderId++;
  28791. }
  28792. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28793. var step = _c[_b];
  28794. step.action(this.activeCamera);
  28795. }
  28796. this._intermediateRendering = false;
  28797. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28798. }
  28799. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28800. // Prepare Frame
  28801. if (this.postProcessManager) {
  28802. this.postProcessManager._prepareFrame();
  28803. }
  28804. // Before Camera Draw
  28805. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28806. var step = _e[_d];
  28807. step.action(this.activeCamera);
  28808. }
  28809. // Render
  28810. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28811. this._renderingManager.render(null, null, true, true);
  28812. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28813. // After Camera Draw
  28814. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28815. var step = _g[_f];
  28816. step.action(this.activeCamera);
  28817. }
  28818. // Finalize frame
  28819. if (this.postProcessManager) {
  28820. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28821. }
  28822. // Reset some special arrays
  28823. this._renderTargets.reset();
  28824. this._alternateRendering = false;
  28825. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28826. };
  28827. Scene.prototype._processSubCameras = function (camera) {
  28828. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28829. this._renderForCamera(camera);
  28830. return;
  28831. }
  28832. // rig cameras
  28833. for (var index = 0; index < camera._rigCameras.length; index++) {
  28834. this._renderForCamera(camera._rigCameras[index], camera);
  28835. }
  28836. this.activeCamera = camera;
  28837. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28838. };
  28839. Scene.prototype._checkIntersections = function () {
  28840. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28841. var sourceMesh = this._meshesForIntersections.data[index];
  28842. if (!sourceMesh.actionManager) {
  28843. continue;
  28844. }
  28845. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28846. var action = sourceMesh.actionManager.actions[actionIndex];
  28847. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28848. var parameters = action.getTriggerParameter();
  28849. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28850. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28851. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28852. if (areIntersecting && currentIntersectionInProgress === -1) {
  28853. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28854. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28855. sourceMesh._intersectionsInProgress.push(otherMesh);
  28856. }
  28857. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28858. sourceMesh._intersectionsInProgress.push(otherMesh);
  28859. }
  28860. }
  28861. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28862. //They intersected, and now they don't.
  28863. //is this trigger an exit trigger? execute an event.
  28864. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28865. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28866. }
  28867. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28868. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28869. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28870. return otherMesh === parameterMesh;
  28871. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28872. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28873. }
  28874. }
  28875. }
  28876. }
  28877. }
  28878. };
  28879. /** @hidden */
  28880. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28881. // Do nothing. Code will be replaced if physics engine component is referenced
  28882. };
  28883. /**
  28884. * Render the scene
  28885. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28886. */
  28887. Scene.prototype.render = function (updateCameras) {
  28888. if (updateCameras === void 0) { updateCameras = true; }
  28889. if (this.isDisposed) {
  28890. return;
  28891. }
  28892. this._frameId++;
  28893. // Register components that have been associated lately to the scene.
  28894. this._registerTransientComponents();
  28895. this._activeParticles.fetchNewFrame();
  28896. this._totalVertices.fetchNewFrame();
  28897. this._activeIndices.fetchNewFrame();
  28898. this._activeBones.fetchNewFrame();
  28899. this._meshesForIntersections.reset();
  28900. this.resetCachedMaterial();
  28901. this.onBeforeAnimationsObservable.notifyObservers(this);
  28902. // Actions
  28903. if (this.actionManager) {
  28904. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28905. }
  28906. if (this._engine.isDeterministicLockStep()) {
  28907. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28908. var defaultFPS = (60.0 / 1000.0);
  28909. var defaultFrameTime = this.getDeterministicFrameTime();
  28910. var stepsTaken = 0;
  28911. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28912. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28913. internalSteps = Math.min(internalSteps, maxSubSteps);
  28914. do {
  28915. this.onBeforeStepObservable.notifyObservers(this);
  28916. // Animations
  28917. this._animationRatio = defaultFrameTime * defaultFPS;
  28918. this._animate();
  28919. this.onAfterAnimationsObservable.notifyObservers(this);
  28920. // Physics
  28921. this._advancePhysicsEngineStep(defaultFrameTime);
  28922. this.onAfterStepObservable.notifyObservers(this);
  28923. this._currentStepId++;
  28924. stepsTaken++;
  28925. deltaTime -= defaultFrameTime;
  28926. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28927. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28928. }
  28929. else {
  28930. // Animations
  28931. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28932. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28933. this._animate();
  28934. this.onAfterAnimationsObservable.notifyObservers(this);
  28935. // Physics
  28936. this._advancePhysicsEngineStep(deltaTime);
  28937. }
  28938. // Before camera update steps
  28939. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28940. var step = _a[_i];
  28941. step.action();
  28942. }
  28943. // Update Cameras
  28944. if (updateCameras) {
  28945. if (this.activeCameras.length > 0) {
  28946. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28947. var camera = this.activeCameras[cameraIndex];
  28948. camera.update();
  28949. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28950. // rig cameras
  28951. for (var index = 0; index < camera._rigCameras.length; index++) {
  28952. camera._rigCameras[index].update();
  28953. }
  28954. }
  28955. }
  28956. }
  28957. else if (this.activeCamera) {
  28958. this.activeCamera.update();
  28959. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28960. // rig cameras
  28961. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28962. this.activeCamera._rigCameras[index].update();
  28963. }
  28964. }
  28965. }
  28966. }
  28967. // Before render
  28968. this.onBeforeRenderObservable.notifyObservers(this);
  28969. // Customs render targets
  28970. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28971. var engine = this.getEngine();
  28972. var currentActiveCamera = this.activeCamera;
  28973. if (this.renderTargetsEnabled) {
  28974. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28975. this._intermediateRendering = true;
  28976. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28977. var renderTarget = this.customRenderTargets[customIndex];
  28978. if (renderTarget._shouldRender()) {
  28979. this._renderId++;
  28980. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28981. if (!this.activeCamera) {
  28982. throw new Error("Active camera not set");
  28983. }
  28984. // Viewport
  28985. engine.setViewport(this.activeCamera.viewport);
  28986. // Camera
  28987. this.updateTransformMatrix();
  28988. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28989. }
  28990. }
  28991. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28992. this._intermediateRendering = false;
  28993. this._renderId++;
  28994. }
  28995. // Restore back buffer
  28996. if (this.customRenderTargets.length > 0) {
  28997. engine.restoreDefaultFramebuffer();
  28998. }
  28999. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29000. this.activeCamera = currentActiveCamera;
  29001. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29002. var step = _c[_b];
  29003. step.action();
  29004. }
  29005. // Clear
  29006. if (this.autoClearDepthAndStencil || this.autoClear) {
  29007. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29008. }
  29009. // Collects render targets from external components.
  29010. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29011. var step = _e[_d];
  29012. step.action(this._renderTargets);
  29013. }
  29014. // Multi-cameras?
  29015. if (this.activeCameras.length > 0) {
  29016. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29017. if (cameraIndex > 0) {
  29018. this._engine.clear(null, false, true, true);
  29019. }
  29020. this._processSubCameras(this.activeCameras[cameraIndex]);
  29021. }
  29022. }
  29023. else {
  29024. if (!this.activeCamera) {
  29025. throw new Error("No camera defined");
  29026. }
  29027. this._processSubCameras(this.activeCamera);
  29028. }
  29029. // Intersection checks
  29030. this._checkIntersections();
  29031. // Executes the after render stage actions.
  29032. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29033. var step = _g[_f];
  29034. step.action();
  29035. }
  29036. // After render
  29037. if (this.afterRender) {
  29038. this.afterRender();
  29039. }
  29040. this.onAfterRenderObservable.notifyObservers(this);
  29041. // Cleaning
  29042. if (this._toBeDisposed.length) {
  29043. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29044. var data = this._toBeDisposed[index];
  29045. if (data) {
  29046. data.dispose();
  29047. }
  29048. }
  29049. this._toBeDisposed = [];
  29050. }
  29051. if (this.dumpNextRenderTargets) {
  29052. this.dumpNextRenderTargets = false;
  29053. }
  29054. this._activeBones.addCount(0, true);
  29055. this._activeIndices.addCount(0, true);
  29056. this._activeParticles.addCount(0, true);
  29057. };
  29058. /**
  29059. * Freeze all materials
  29060. * A frozen material will not be updatable but should be faster to render
  29061. */
  29062. Scene.prototype.freezeMaterials = function () {
  29063. for (var i = 0; i < this.materials.length; i++) {
  29064. this.materials[i].freeze();
  29065. }
  29066. };
  29067. /**
  29068. * Unfreeze all materials
  29069. * A frozen material will not be updatable but should be faster to render
  29070. */
  29071. Scene.prototype.unfreezeMaterials = function () {
  29072. for (var i = 0; i < this.materials.length; i++) {
  29073. this.materials[i].unfreeze();
  29074. }
  29075. };
  29076. /**
  29077. * Releases all held ressources
  29078. */
  29079. Scene.prototype.dispose = function () {
  29080. this.beforeRender = null;
  29081. this.afterRender = null;
  29082. this.skeletons = [];
  29083. this.morphTargetManagers = [];
  29084. this._transientComponents = [];
  29085. this._isReadyForMeshStage.clear();
  29086. this._beforeEvaluateActiveMeshStage.clear();
  29087. this._evaluateSubMeshStage.clear();
  29088. this._activeMeshStage.clear();
  29089. this._cameraDrawRenderTargetStage.clear();
  29090. this._beforeCameraDrawStage.clear();
  29091. this._beforeRenderingGroupDrawStage.clear();
  29092. this._beforeRenderingMeshStage.clear();
  29093. this._afterRenderingMeshStage.clear();
  29094. this._afterRenderingGroupDrawStage.clear();
  29095. this._afterCameraDrawStage.clear();
  29096. this._afterRenderStage.clear();
  29097. this._beforeCameraUpdateStage.clear();
  29098. this._beforeClearStage.clear();
  29099. this._gatherRenderTargetsStage.clear();
  29100. this._gatherActiveCameraRenderTargetsStage.clear();
  29101. this._pointerMoveStage.clear();
  29102. this._pointerDownStage.clear();
  29103. this._pointerUpStage.clear();
  29104. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29105. var component = _a[_i];
  29106. component.dispose();
  29107. }
  29108. this.importedMeshesFiles = new Array();
  29109. this.stopAllAnimations();
  29110. this.resetCachedMaterial();
  29111. // Smart arrays
  29112. if (this.activeCamera) {
  29113. this.activeCamera._activeMeshes.dispose();
  29114. this.activeCamera = null;
  29115. }
  29116. this._activeMeshes.dispose();
  29117. this._renderingManager.dispose();
  29118. this._processedMaterials.dispose();
  29119. this._activeParticleSystems.dispose();
  29120. this._activeSkeletons.dispose();
  29121. this._softwareSkinnedMeshes.dispose();
  29122. this._renderTargets.dispose();
  29123. this._registeredForLateAnimationBindings.dispose();
  29124. this._meshesForIntersections.dispose();
  29125. this._toBeDisposed = [];
  29126. // Abort active requests
  29127. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29128. var request = _c[_b];
  29129. request.abort();
  29130. }
  29131. // Events
  29132. this.onDisposeObservable.notifyObservers(this);
  29133. this.onDisposeObservable.clear();
  29134. this.onBeforeRenderObservable.clear();
  29135. this.onAfterRenderObservable.clear();
  29136. this.onBeforeRenderTargetsRenderObservable.clear();
  29137. this.onAfterRenderTargetsRenderObservable.clear();
  29138. this.onAfterStepObservable.clear();
  29139. this.onBeforeStepObservable.clear();
  29140. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29141. this.onAfterActiveMeshesEvaluationObservable.clear();
  29142. this.onBeforeParticlesRenderingObservable.clear();
  29143. this.onAfterParticlesRenderingObservable.clear();
  29144. this.onBeforeDrawPhaseObservable.clear();
  29145. this.onAfterDrawPhaseObservable.clear();
  29146. this.onBeforeAnimationsObservable.clear();
  29147. this.onAfterAnimationsObservable.clear();
  29148. this.onDataLoadedObservable.clear();
  29149. this.onBeforeRenderingGroupObservable.clear();
  29150. this.onAfterRenderingGroupObservable.clear();
  29151. this.onMeshImportedObservable.clear();
  29152. this.onBeforeCameraRenderObservable.clear();
  29153. this.onAfterCameraRenderObservable.clear();
  29154. this.onReadyObservable.clear();
  29155. this.onNewCameraAddedObservable.clear();
  29156. this.onCameraRemovedObservable.clear();
  29157. this.onNewLightAddedObservable.clear();
  29158. this.onLightRemovedObservable.clear();
  29159. this.onNewGeometryAddedObservable.clear();
  29160. this.onGeometryRemovedObservable.clear();
  29161. this.onNewTransformNodeAddedObservable.clear();
  29162. this.onTransformNodeRemovedObservable.clear();
  29163. this.onNewMeshAddedObservable.clear();
  29164. this.onMeshRemovedObservable.clear();
  29165. this.onNewMaterialAddedObservable.clear();
  29166. this.onMaterialRemovedObservable.clear();
  29167. this.onNewTextureAddedObservable.clear();
  29168. this.onTextureRemovedObservable.clear();
  29169. this.onPrePointerObservable.clear();
  29170. this.onPointerObservable.clear();
  29171. this.onPreKeyboardObservable.clear();
  29172. this.onKeyboardObservable.clear();
  29173. this.detachControl();
  29174. // Detach cameras
  29175. var canvas = this._engine.getRenderingCanvas();
  29176. if (canvas) {
  29177. var index;
  29178. for (index = 0; index < this.cameras.length; index++) {
  29179. this.cameras[index].detachControl(canvas);
  29180. }
  29181. }
  29182. // Release animation groups
  29183. while (this.animationGroups.length) {
  29184. this.animationGroups[0].dispose();
  29185. }
  29186. // Release lights
  29187. while (this.lights.length) {
  29188. this.lights[0].dispose();
  29189. }
  29190. // Release meshes
  29191. while (this.meshes.length) {
  29192. this.meshes[0].dispose(true);
  29193. }
  29194. while (this.transformNodes.length) {
  29195. this.removeTransformNode(this.transformNodes[0]);
  29196. }
  29197. // Release cameras
  29198. while (this.cameras.length) {
  29199. this.cameras[0].dispose();
  29200. }
  29201. // Release materials
  29202. if (this.defaultMaterial) {
  29203. this.defaultMaterial.dispose();
  29204. }
  29205. while (this.multiMaterials.length) {
  29206. this.multiMaterials[0].dispose();
  29207. }
  29208. while (this.materials.length) {
  29209. this.materials[0].dispose();
  29210. }
  29211. // Release particles
  29212. while (this.particleSystems.length) {
  29213. this.particleSystems[0].dispose();
  29214. }
  29215. // Release postProcesses
  29216. while (this.postProcesses.length) {
  29217. this.postProcesses[0].dispose();
  29218. }
  29219. // Release textures
  29220. while (this.textures.length) {
  29221. this.textures[0].dispose();
  29222. }
  29223. // Release UBO
  29224. this._sceneUbo.dispose();
  29225. if (this._alternateSceneUbo) {
  29226. this._alternateSceneUbo.dispose();
  29227. }
  29228. // Post-processes
  29229. this.postProcessManager.dispose();
  29230. // Remove from engine
  29231. index = this._engine.scenes.indexOf(this);
  29232. if (index > -1) {
  29233. this._engine.scenes.splice(index, 1);
  29234. }
  29235. this._engine.wipeCaches(true);
  29236. this._isDisposed = true;
  29237. };
  29238. Object.defineProperty(Scene.prototype, "isDisposed", {
  29239. /**
  29240. * Gets if the scene is already disposed
  29241. */
  29242. get: function () {
  29243. return this._isDisposed;
  29244. },
  29245. enumerable: true,
  29246. configurable: true
  29247. });
  29248. /**
  29249. * Call this function to reduce memory footprint of the scene.
  29250. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29251. */
  29252. Scene.prototype.clearCachedVertexData = function () {
  29253. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29254. var mesh = this.meshes[meshIndex];
  29255. var geometry = mesh.geometry;
  29256. if (geometry) {
  29257. geometry._indices = [];
  29258. for (var vbName in geometry._vertexBuffers) {
  29259. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29260. continue;
  29261. }
  29262. geometry._vertexBuffers[vbName]._buffer._data = null;
  29263. }
  29264. }
  29265. }
  29266. };
  29267. /**
  29268. * This function will remove the local cached buffer data from texture.
  29269. * It will save memory but will prevent the texture from being rebuilt
  29270. */
  29271. Scene.prototype.cleanCachedTextureBuffer = function () {
  29272. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29273. var baseTexture = _a[_i];
  29274. var buffer = baseTexture._buffer;
  29275. if (buffer) {
  29276. baseTexture._buffer = null;
  29277. }
  29278. }
  29279. };
  29280. /**
  29281. * Get the world extend vectors with an optional filter
  29282. *
  29283. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29284. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29285. */
  29286. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29287. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29288. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29289. filterPredicate = filterPredicate || (function () { return true; });
  29290. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29291. mesh.computeWorldMatrix(true);
  29292. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29293. return;
  29294. }
  29295. var boundingInfo = mesh.getBoundingInfo();
  29296. var minBox = boundingInfo.boundingBox.minimumWorld;
  29297. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29298. BABYLON.Tools.CheckExtends(minBox, min, max);
  29299. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29300. });
  29301. return {
  29302. min: min,
  29303. max: max
  29304. };
  29305. };
  29306. // Picking
  29307. /**
  29308. * Creates a ray that can be used to pick in the scene
  29309. * @param x defines the x coordinate of the origin (on-screen)
  29310. * @param y defines the y coordinate of the origin (on-screen)
  29311. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29312. * @param camera defines the camera to use for the picking
  29313. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29314. * @returns a Ray
  29315. */
  29316. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29317. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29318. var result = BABYLON.Ray.Zero();
  29319. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29320. return result;
  29321. };
  29322. /**
  29323. * Creates a ray that can be used to pick in the scene
  29324. * @param x defines the x coordinate of the origin (on-screen)
  29325. * @param y defines the y coordinate of the origin (on-screen)
  29326. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29327. * @param result defines the ray where to store the picking ray
  29328. * @param camera defines the camera to use for the picking
  29329. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29330. * @returns the current scene
  29331. */
  29332. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29333. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29334. var engine = this._engine;
  29335. if (!camera) {
  29336. if (!this.activeCamera) {
  29337. throw new Error("Active camera not set");
  29338. }
  29339. camera = this.activeCamera;
  29340. }
  29341. var cameraViewport = camera.viewport;
  29342. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29343. // Moving coordinates to local viewport world
  29344. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29345. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29346. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29347. return this;
  29348. };
  29349. /**
  29350. * Creates a ray that can be used to pick in the scene
  29351. * @param x defines the x coordinate of the origin (on-screen)
  29352. * @param y defines the y coordinate of the origin (on-screen)
  29353. * @param camera defines the camera to use for the picking
  29354. * @returns a Ray
  29355. */
  29356. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29357. var result = BABYLON.Ray.Zero();
  29358. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29359. return result;
  29360. };
  29361. /**
  29362. * Creates a ray that can be used to pick in the scene
  29363. * @param x defines the x coordinate of the origin (on-screen)
  29364. * @param y defines the y coordinate of the origin (on-screen)
  29365. * @param result defines the ray where to store the picking ray
  29366. * @param camera defines the camera to use for the picking
  29367. * @returns the current scene
  29368. */
  29369. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29370. if (!BABYLON.PickingInfo) {
  29371. return this;
  29372. }
  29373. var engine = this._engine;
  29374. if (!camera) {
  29375. if (!this.activeCamera) {
  29376. throw new Error("Active camera not set");
  29377. }
  29378. camera = this.activeCamera;
  29379. }
  29380. var cameraViewport = camera.viewport;
  29381. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29382. var identity = BABYLON.Matrix.Identity();
  29383. // Moving coordinates to local viewport world
  29384. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29385. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29386. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29387. return this;
  29388. };
  29389. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29390. if (!BABYLON.PickingInfo) {
  29391. return null;
  29392. }
  29393. var pickingInfo = null;
  29394. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29395. var mesh = this.meshes[meshIndex];
  29396. if (predicate) {
  29397. if (!predicate(mesh)) {
  29398. continue;
  29399. }
  29400. }
  29401. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29402. continue;
  29403. }
  29404. var world = mesh.getWorldMatrix();
  29405. var ray = rayFunction(world);
  29406. var result = mesh.intersects(ray, fastCheck);
  29407. if (!result || !result.hit) {
  29408. continue;
  29409. }
  29410. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  29411. continue;
  29412. }
  29413. pickingInfo = result;
  29414. if (fastCheck) {
  29415. break;
  29416. }
  29417. }
  29418. return pickingInfo || new BABYLON.PickingInfo();
  29419. };
  29420. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29421. if (!BABYLON.PickingInfo) {
  29422. return null;
  29423. }
  29424. var pickingInfos = new Array();
  29425. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29426. var mesh = this.meshes[meshIndex];
  29427. if (predicate) {
  29428. if (!predicate(mesh)) {
  29429. continue;
  29430. }
  29431. }
  29432. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29433. continue;
  29434. }
  29435. var world = mesh.getWorldMatrix();
  29436. var ray = rayFunction(world);
  29437. var result = mesh.intersects(ray, false);
  29438. if (!result || !result.hit) {
  29439. continue;
  29440. }
  29441. pickingInfos.push(result);
  29442. }
  29443. return pickingInfos;
  29444. };
  29445. /** Launch a ray to try to pick a mesh in the scene
  29446. * @param x position on screen
  29447. * @param y position on screen
  29448. * @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
  29449. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29450. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29451. * @returns a PickingInfo
  29452. */
  29453. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29454. var _this = this;
  29455. if (!BABYLON.PickingInfo) {
  29456. return null;
  29457. }
  29458. var result = this._internalPick(function (world) {
  29459. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29460. return _this._tempPickingRay;
  29461. }, predicate, fastCheck);
  29462. if (result) {
  29463. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29464. }
  29465. return result;
  29466. };
  29467. /** Use the given ray to pick a mesh in the scene
  29468. * @param ray The ray to use to pick meshes
  29469. * @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
  29470. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29471. * @returns a PickingInfo
  29472. */
  29473. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29474. var _this = this;
  29475. var result = this._internalPick(function (world) {
  29476. if (!_this._pickWithRayInverseMatrix) {
  29477. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29478. }
  29479. world.invertToRef(_this._pickWithRayInverseMatrix);
  29480. if (!_this._cachedRayForTransform) {
  29481. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29482. }
  29483. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29484. return _this._cachedRayForTransform;
  29485. }, predicate, fastCheck);
  29486. if (result) {
  29487. result.ray = ray;
  29488. }
  29489. return result;
  29490. };
  29491. /**
  29492. * Launch a ray to try to pick a mesh in the scene
  29493. * @param x X position on screen
  29494. * @param y Y position on screen
  29495. * @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
  29496. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29497. * @returns an array of PickingInfo
  29498. */
  29499. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29500. var _this = this;
  29501. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29502. };
  29503. /**
  29504. * Launch a ray to try to pick a mesh in the scene
  29505. * @param ray Ray to use
  29506. * @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
  29507. * @returns an array of PickingInfo
  29508. */
  29509. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29510. var _this = this;
  29511. return this._internalMultiPick(function (world) {
  29512. if (!_this._pickWithRayInverseMatrix) {
  29513. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29514. }
  29515. world.invertToRef(_this._pickWithRayInverseMatrix);
  29516. if (!_this._cachedRayForTransform) {
  29517. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29518. }
  29519. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29520. return _this._cachedRayForTransform;
  29521. }, predicate);
  29522. };
  29523. /**
  29524. * Force the value of meshUnderPointer
  29525. * @param mesh defines the mesh to use
  29526. */
  29527. Scene.prototype.setPointerOverMesh = function (mesh) {
  29528. if (this._pointerOverMesh === mesh) {
  29529. return;
  29530. }
  29531. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29532. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29533. }
  29534. this._pointerOverMesh = mesh;
  29535. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29536. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29537. }
  29538. };
  29539. /**
  29540. * Gets the mesh under the pointer
  29541. * @returns a Mesh or null if no mesh is under the pointer
  29542. */
  29543. Scene.prototype.getPointerOverMesh = function () {
  29544. return this._pointerOverMesh;
  29545. };
  29546. // Misc.
  29547. /** @hidden */
  29548. Scene.prototype._rebuildGeometries = function () {
  29549. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29550. var geometry = _a[_i];
  29551. geometry._rebuild();
  29552. }
  29553. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29554. var mesh = _c[_b];
  29555. mesh._rebuild();
  29556. }
  29557. if (this.postProcessManager) {
  29558. this.postProcessManager._rebuild();
  29559. }
  29560. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29561. var component = _e[_d];
  29562. component.rebuild();
  29563. }
  29564. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29565. var system = _g[_f];
  29566. system.rebuild();
  29567. }
  29568. };
  29569. /** @hidden */
  29570. Scene.prototype._rebuildTextures = function () {
  29571. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29572. var texture = _a[_i];
  29573. texture._rebuild();
  29574. }
  29575. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29576. };
  29577. // Tags
  29578. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29579. if (tagsQuery === undefined) {
  29580. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29581. return list;
  29582. }
  29583. var listByTags = [];
  29584. forEach = forEach || (function (item) { return; });
  29585. for (var i in list) {
  29586. var item = list[i];
  29587. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29588. listByTags.push(item);
  29589. forEach(item);
  29590. }
  29591. }
  29592. return listByTags;
  29593. };
  29594. /**
  29595. * Get a list of meshes by tags
  29596. * @param tagsQuery defines the tags query to use
  29597. * @param forEach defines a predicate used to filter results
  29598. * @returns an array of Mesh
  29599. */
  29600. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29601. return this._getByTags(this.meshes, tagsQuery, forEach);
  29602. };
  29603. /**
  29604. * Get a list of cameras by tags
  29605. * @param tagsQuery defines the tags query to use
  29606. * @param forEach defines a predicate used to filter results
  29607. * @returns an array of Camera
  29608. */
  29609. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29610. return this._getByTags(this.cameras, tagsQuery, forEach);
  29611. };
  29612. /**
  29613. * Get a list of lights by tags
  29614. * @param tagsQuery defines the tags query to use
  29615. * @param forEach defines a predicate used to filter results
  29616. * @returns an array of Light
  29617. */
  29618. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29619. return this._getByTags(this.lights, tagsQuery, forEach);
  29620. };
  29621. /**
  29622. * Get a list of materials by tags
  29623. * @param tagsQuery defines the tags query to use
  29624. * @param forEach defines a predicate used to filter results
  29625. * @returns an array of Material
  29626. */
  29627. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29628. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29629. };
  29630. /**
  29631. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29632. * This allowed control for front to back rendering or reversly depending of the special needs.
  29633. *
  29634. * @param renderingGroupId The rendering group id corresponding to its index
  29635. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29636. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29637. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29638. */
  29639. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29640. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29641. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29642. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29643. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29644. };
  29645. /**
  29646. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29647. *
  29648. * @param renderingGroupId The rendering group id corresponding to its index
  29649. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29650. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29651. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29652. */
  29653. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29654. if (depth === void 0) { depth = true; }
  29655. if (stencil === void 0) { stencil = true; }
  29656. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29657. };
  29658. /**
  29659. * Gets the current auto clear configuration for one rendering group of the rendering
  29660. * manager.
  29661. * @param index the rendering group index to get the information for
  29662. * @returns The auto clear setup for the requested rendering group
  29663. */
  29664. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29665. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29666. };
  29667. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29668. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29669. get: function () {
  29670. return this._blockMaterialDirtyMechanism;
  29671. },
  29672. set: function (value) {
  29673. if (this._blockMaterialDirtyMechanism === value) {
  29674. return;
  29675. }
  29676. this._blockMaterialDirtyMechanism = value;
  29677. if (!value) { // Do a complete update
  29678. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29679. }
  29680. },
  29681. enumerable: true,
  29682. configurable: true
  29683. });
  29684. /**
  29685. * Will flag all materials as dirty to trigger new shader compilation
  29686. * @param flag defines the flag used to specify which material part must be marked as dirty
  29687. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29688. */
  29689. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29690. if (this._blockMaterialDirtyMechanism) {
  29691. return;
  29692. }
  29693. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29694. var material = _a[_i];
  29695. if (predicate && !predicate(material)) {
  29696. continue;
  29697. }
  29698. material.markAsDirty(flag);
  29699. }
  29700. };
  29701. /** @hidden */
  29702. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29703. var _this = this;
  29704. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29705. this._activeRequests.push(request);
  29706. request.onCompleteObservable.add(function (request) {
  29707. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29708. });
  29709. return request;
  29710. };
  29711. /** @hidden */
  29712. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29713. var _this = this;
  29714. return new Promise(function (resolve, reject) {
  29715. _this._loadFile(url, function (data) {
  29716. resolve(data);
  29717. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29718. reject(exception);
  29719. });
  29720. });
  29721. };
  29722. // Statics
  29723. Scene._uniqueIdCounter = 0;
  29724. /** The fog is deactivated */
  29725. Scene.FOGMODE_NONE = 0;
  29726. /** The fog density is following an exponential function */
  29727. Scene.FOGMODE_EXP = 1;
  29728. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29729. Scene.FOGMODE_EXP2 = 2;
  29730. /** The fog density is following a linear function. */
  29731. Scene.FOGMODE_LINEAR = 3;
  29732. /**
  29733. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29734. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29735. */
  29736. Scene.MinDeltaTime = 1.0;
  29737. /**
  29738. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29739. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29740. */
  29741. Scene.MaxDeltaTime = 1000.0;
  29742. /** The distance in pixel that you have to move to prevent some events */
  29743. Scene.DragMovementThreshold = 10; // in pixels
  29744. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29745. Scene.LongPressDelay = 500; // in milliseconds
  29746. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29747. Scene.DoubleClickDelay = 300; // in milliseconds
  29748. /** If you need to check double click without raising a single click at first click, enable this flag */
  29749. Scene.ExclusiveDoubleClickMode = false;
  29750. return Scene;
  29751. }(BABYLON.AbstractScene));
  29752. BABYLON.Scene = Scene;
  29753. })(BABYLON || (BABYLON = {}));
  29754. //# sourceMappingURL=babylon.scene.js.map
  29755. var BABYLON;
  29756. (function (BABYLON) {
  29757. /**
  29758. * Set of assets to keep when moving a scene into an asset container.
  29759. */
  29760. var KeepAssets = /** @class */ (function (_super) {
  29761. __extends(KeepAssets, _super);
  29762. function KeepAssets() {
  29763. return _super !== null && _super.apply(this, arguments) || this;
  29764. }
  29765. return KeepAssets;
  29766. }(BABYLON.AbstractScene));
  29767. BABYLON.KeepAssets = KeepAssets;
  29768. /**
  29769. * Container with a set of assets that can be added or removed from a scene.
  29770. */
  29771. var AssetContainer = /** @class */ (function (_super) {
  29772. __extends(AssetContainer, _super);
  29773. /**
  29774. * Instantiates an AssetContainer.
  29775. * @param scene The scene the AssetContainer belongs to.
  29776. */
  29777. function AssetContainer(scene) {
  29778. var _this = _super.call(this) || this;
  29779. _this.scene = scene;
  29780. return _this;
  29781. }
  29782. /**
  29783. * Adds all the assets from the container to the scene.
  29784. */
  29785. AssetContainer.prototype.addAllToScene = function () {
  29786. var _this = this;
  29787. this.cameras.forEach(function (o) {
  29788. _this.scene.addCamera(o);
  29789. });
  29790. this.lights.forEach(function (o) {
  29791. _this.scene.addLight(o);
  29792. });
  29793. this.meshes.forEach(function (o) {
  29794. _this.scene.addMesh(o);
  29795. });
  29796. this.skeletons.forEach(function (o) {
  29797. _this.scene.addSkeleton(o);
  29798. });
  29799. this.animations.forEach(function (o) {
  29800. _this.scene.addAnimation(o);
  29801. });
  29802. this.animationGroups.forEach(function (o) {
  29803. _this.scene.addAnimationGroup(o);
  29804. });
  29805. this.multiMaterials.forEach(function (o) {
  29806. _this.scene.addMultiMaterial(o);
  29807. });
  29808. this.materials.forEach(function (o) {
  29809. _this.scene.addMaterial(o);
  29810. });
  29811. this.morphTargetManagers.forEach(function (o) {
  29812. _this.scene.addMorphTargetManager(o);
  29813. });
  29814. this.geometries.forEach(function (o) {
  29815. _this.scene.addGeometry(o);
  29816. });
  29817. this.transformNodes.forEach(function (o) {
  29818. _this.scene.addTransformNode(o);
  29819. });
  29820. this.actionManagers.forEach(function (o) {
  29821. _this.scene.addActionManager(o);
  29822. });
  29823. this.textures.forEach(function (o) {
  29824. _this.scene.addTexture(o);
  29825. });
  29826. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29827. var component = _a[_i];
  29828. component.addFromContainer(this.scene);
  29829. }
  29830. };
  29831. /**
  29832. * Removes all the assets in the container from the scene
  29833. */
  29834. AssetContainer.prototype.removeAllFromScene = function () {
  29835. var _this = this;
  29836. this.cameras.forEach(function (o) {
  29837. _this.scene.removeCamera(o);
  29838. });
  29839. this.lights.forEach(function (o) {
  29840. _this.scene.removeLight(o);
  29841. });
  29842. this.meshes.forEach(function (o) {
  29843. _this.scene.removeMesh(o);
  29844. });
  29845. this.skeletons.forEach(function (o) {
  29846. _this.scene.removeSkeleton(o);
  29847. });
  29848. this.animations.forEach(function (o) {
  29849. _this.scene.removeAnimation(o);
  29850. });
  29851. this.animationGroups.forEach(function (o) {
  29852. _this.scene.removeAnimationGroup(o);
  29853. });
  29854. this.multiMaterials.forEach(function (o) {
  29855. _this.scene.removeMultiMaterial(o);
  29856. });
  29857. this.materials.forEach(function (o) {
  29858. _this.scene.removeMaterial(o);
  29859. });
  29860. this.morphTargetManagers.forEach(function (o) {
  29861. _this.scene.removeMorphTargetManager(o);
  29862. });
  29863. this.geometries.forEach(function (o) {
  29864. _this.scene.removeGeometry(o);
  29865. });
  29866. this.transformNodes.forEach(function (o) {
  29867. _this.scene.removeTransformNode(o);
  29868. });
  29869. this.actionManagers.forEach(function (o) {
  29870. _this.scene.removeActionManager(o);
  29871. });
  29872. this.textures.forEach(function (o) {
  29873. _this.scene.removeTexture(o);
  29874. });
  29875. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29876. var component = _a[_i];
  29877. component.removeFromContainer(this.scene);
  29878. }
  29879. };
  29880. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29881. if (!sourceAssets) {
  29882. return;
  29883. }
  29884. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29885. var asset = sourceAssets_1[_i];
  29886. var move = true;
  29887. if (keepAssets) {
  29888. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29889. var keepAsset = keepAssets_1[_a];
  29890. if (asset === keepAsset) {
  29891. move = false;
  29892. break;
  29893. }
  29894. }
  29895. }
  29896. if (move) {
  29897. targetAssets.push(asset);
  29898. }
  29899. }
  29900. };
  29901. /**
  29902. * Removes all the assets contained in the scene and adds them to the container.
  29903. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29904. */
  29905. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29906. if (keepAssets === undefined) {
  29907. keepAssets = new KeepAssets();
  29908. }
  29909. for (var key in this) {
  29910. if (this.hasOwnProperty(key)) {
  29911. this[key] = this[key] || [];
  29912. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29913. }
  29914. }
  29915. this.removeAllFromScene();
  29916. };
  29917. /**
  29918. * 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.
  29919. * @returns the root mesh
  29920. */
  29921. AssetContainer.prototype.createRootMesh = function () {
  29922. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29923. this.meshes.forEach(function (m) {
  29924. if (!m.parent) {
  29925. rootMesh.addChild(m);
  29926. }
  29927. });
  29928. this.meshes.unshift(rootMesh);
  29929. return rootMesh;
  29930. };
  29931. return AssetContainer;
  29932. }(BABYLON.AbstractScene));
  29933. BABYLON.AssetContainer = AssetContainer;
  29934. })(BABYLON || (BABYLON = {}));
  29935. //# sourceMappingURL=babylon.assetContainer.js.map
  29936. var BABYLON;
  29937. (function (BABYLON) {
  29938. /**
  29939. * Class used to store data that will be store in GPU memory
  29940. */
  29941. var Buffer = /** @class */ (function () {
  29942. /**
  29943. * Constructor
  29944. * @param engine the engine
  29945. * @param data the data to use for this buffer
  29946. * @param updatable whether the data is updatable
  29947. * @param stride the stride (optional)
  29948. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29949. * @param instanced whether the buffer is instanced (optional)
  29950. * @param useBytes set to true if the stride in in bytes (optional)
  29951. */
  29952. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29953. if (stride === void 0) { stride = 0; }
  29954. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29955. if (instanced === void 0) { instanced = false; }
  29956. if (useBytes === void 0) { useBytes = false; }
  29957. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29958. this._engine = engine.getScene().getEngine();
  29959. }
  29960. else {
  29961. this._engine = engine;
  29962. }
  29963. this._updatable = updatable;
  29964. this._instanced = instanced;
  29965. this._data = data;
  29966. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29967. if (!postponeInternalCreation) { // by default
  29968. this.create();
  29969. }
  29970. }
  29971. /**
  29972. * Create a new VertexBuffer based on the current buffer
  29973. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29974. * @param offset defines offset in the buffer (0 by default)
  29975. * @param size defines the size in floats of attributes (position is 3 for instance)
  29976. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29977. * @param instanced defines if the vertex buffer contains indexed data
  29978. * @param useBytes defines if the offset and stride are in bytes
  29979. * @returns the new vertex buffer
  29980. */
  29981. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29982. if (useBytes === void 0) { useBytes = false; }
  29983. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29984. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29985. // a lot of these parameters are ignored as they are overriden by the buffer
  29986. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29987. };
  29988. // Properties
  29989. /**
  29990. * Gets a boolean indicating if the Buffer is updatable?
  29991. * @returns true if the buffer is updatable
  29992. */
  29993. Buffer.prototype.isUpdatable = function () {
  29994. return this._updatable;
  29995. };
  29996. /**
  29997. * Gets current buffer's data
  29998. * @returns a DataArray or null
  29999. */
  30000. Buffer.prototype.getData = function () {
  30001. return this._data;
  30002. };
  30003. /**
  30004. * Gets underlying native buffer
  30005. * @returns underlying native buffer
  30006. */
  30007. Buffer.prototype.getBuffer = function () {
  30008. return this._buffer;
  30009. };
  30010. /**
  30011. * Gets the stride in float32 units (i.e. byte stride / 4).
  30012. * May not be an integer if the byte stride is not divisible by 4.
  30013. * DEPRECATED. Use byteStride instead.
  30014. * @returns the stride in float32 units
  30015. */
  30016. Buffer.prototype.getStrideSize = function () {
  30017. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30018. };
  30019. // Methods
  30020. /**
  30021. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30022. * @param data defines the data to store
  30023. */
  30024. Buffer.prototype.create = function (data) {
  30025. if (data === void 0) { data = null; }
  30026. if (!data && this._buffer) {
  30027. return; // nothing to do
  30028. }
  30029. data = data || this._data;
  30030. if (!data) {
  30031. return;
  30032. }
  30033. if (!this._buffer) { // create buffer
  30034. if (this._updatable) {
  30035. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30036. this._data = data;
  30037. }
  30038. else {
  30039. this._buffer = this._engine.createVertexBuffer(data);
  30040. }
  30041. }
  30042. else if (this._updatable) { // update buffer
  30043. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30044. this._data = data;
  30045. }
  30046. };
  30047. /** @hidden */
  30048. Buffer.prototype._rebuild = function () {
  30049. this._buffer = null;
  30050. this.create(this._data);
  30051. };
  30052. /**
  30053. * Update current buffer data
  30054. * @param data defines the data to store
  30055. */
  30056. Buffer.prototype.update = function (data) {
  30057. this.create(data);
  30058. };
  30059. /**
  30060. * Updates the data directly.
  30061. * @param data the new data
  30062. * @param offset the new offset
  30063. * @param vertexCount the vertex count (optional)
  30064. * @param useBytes set to true if the offset is in bytes
  30065. */
  30066. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30067. if (useBytes === void 0) { useBytes = false; }
  30068. if (!this._buffer) {
  30069. return;
  30070. }
  30071. if (this._updatable) { // update buffer
  30072. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30073. this._data = null;
  30074. }
  30075. };
  30076. /**
  30077. * Release all resources
  30078. */
  30079. Buffer.prototype.dispose = function () {
  30080. if (!this._buffer) {
  30081. return;
  30082. }
  30083. if (this._engine._releaseBuffer(this._buffer)) {
  30084. this._buffer = null;
  30085. }
  30086. };
  30087. return Buffer;
  30088. }());
  30089. BABYLON.Buffer = Buffer;
  30090. })(BABYLON || (BABYLON = {}));
  30091. //# sourceMappingURL=babylon.buffer.js.map
  30092. var BABYLON;
  30093. (function (BABYLON) {
  30094. /**
  30095. * Specialized buffer used to store vertex data
  30096. */
  30097. var VertexBuffer = /** @class */ (function () {
  30098. /**
  30099. * Constructor
  30100. * @param engine the engine
  30101. * @param data the data to use for this vertex buffer
  30102. * @param kind the vertex buffer kind
  30103. * @param updatable whether the data is updatable
  30104. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30105. * @param stride the stride (optional)
  30106. * @param instanced whether the buffer is instanced (optional)
  30107. * @param offset the offset of the data (optional)
  30108. * @param size the number of components (optional)
  30109. * @param type the type of the component (optional)
  30110. * @param normalized whether the data contains normalized data (optional)
  30111. * @param useBytes set to true if stride and offset are in bytes (optional)
  30112. */
  30113. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30114. if (normalized === void 0) { normalized = false; }
  30115. if (useBytes === void 0) { useBytes = false; }
  30116. if (data instanceof BABYLON.Buffer) {
  30117. this._buffer = data;
  30118. this._ownsBuffer = false;
  30119. }
  30120. else {
  30121. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30122. this._ownsBuffer = true;
  30123. }
  30124. this._kind = kind;
  30125. if (type == undefined) {
  30126. var data_1 = this.getData();
  30127. this.type = VertexBuffer.FLOAT;
  30128. if (data_1 instanceof Int8Array) {
  30129. this.type = VertexBuffer.BYTE;
  30130. }
  30131. else if (data_1 instanceof Uint8Array) {
  30132. this.type = VertexBuffer.UNSIGNED_BYTE;
  30133. }
  30134. else if (data_1 instanceof Int16Array) {
  30135. this.type = VertexBuffer.SHORT;
  30136. }
  30137. else if (data_1 instanceof Uint16Array) {
  30138. this.type = VertexBuffer.UNSIGNED_SHORT;
  30139. }
  30140. else if (data_1 instanceof Int32Array) {
  30141. this.type = VertexBuffer.INT;
  30142. }
  30143. else if (data_1 instanceof Uint32Array) {
  30144. this.type = VertexBuffer.UNSIGNED_INT;
  30145. }
  30146. }
  30147. else {
  30148. this.type = type;
  30149. }
  30150. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30151. if (useBytes) {
  30152. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30153. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30154. this.byteOffset = offset || 0;
  30155. }
  30156. else {
  30157. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30158. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30159. this.byteOffset = (offset || 0) * typeByteLength;
  30160. }
  30161. this.normalized = normalized;
  30162. this._instanced = instanced !== undefined ? instanced : false;
  30163. this._instanceDivisor = instanced ? 1 : 0;
  30164. }
  30165. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30166. /**
  30167. * Gets or sets the instance divisor when in instanced mode
  30168. */
  30169. get: function () {
  30170. return this._instanceDivisor;
  30171. },
  30172. set: function (value) {
  30173. this._instanceDivisor = value;
  30174. if (value == 0) {
  30175. this._instanced = false;
  30176. }
  30177. else {
  30178. this._instanced = true;
  30179. }
  30180. },
  30181. enumerable: true,
  30182. configurable: true
  30183. });
  30184. /** @hidden */
  30185. VertexBuffer.prototype._rebuild = function () {
  30186. if (!this._buffer) {
  30187. return;
  30188. }
  30189. this._buffer._rebuild();
  30190. };
  30191. /**
  30192. * Returns the kind of the VertexBuffer (string)
  30193. * @returns a string
  30194. */
  30195. VertexBuffer.prototype.getKind = function () {
  30196. return this._kind;
  30197. };
  30198. // Properties
  30199. /**
  30200. * Gets a boolean indicating if the VertexBuffer is updatable?
  30201. * @returns true if the buffer is updatable
  30202. */
  30203. VertexBuffer.prototype.isUpdatable = function () {
  30204. return this._buffer.isUpdatable();
  30205. };
  30206. /**
  30207. * Gets current buffer's data
  30208. * @returns a DataArray or null
  30209. */
  30210. VertexBuffer.prototype.getData = function () {
  30211. return this._buffer.getData();
  30212. };
  30213. /**
  30214. * Gets underlying native buffer
  30215. * @returns underlying native buffer
  30216. */
  30217. VertexBuffer.prototype.getBuffer = function () {
  30218. return this._buffer.getBuffer();
  30219. };
  30220. /**
  30221. * Gets the stride in float32 units (i.e. byte stride / 4).
  30222. * May not be an integer if the byte stride is not divisible by 4.
  30223. * DEPRECATED. Use byteStride instead.
  30224. * @returns the stride in float32 units
  30225. */
  30226. VertexBuffer.prototype.getStrideSize = function () {
  30227. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30228. };
  30229. /**
  30230. * Returns the offset as a multiple of the type byte length.
  30231. * DEPRECATED. Use byteOffset instead.
  30232. * @returns the offset in bytes
  30233. */
  30234. VertexBuffer.prototype.getOffset = function () {
  30235. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30236. };
  30237. /**
  30238. * Returns the number of components per vertex attribute (integer)
  30239. * @returns the size in float
  30240. */
  30241. VertexBuffer.prototype.getSize = function () {
  30242. return this._size;
  30243. };
  30244. /**
  30245. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30246. * @returns true if this buffer is instanced
  30247. */
  30248. VertexBuffer.prototype.getIsInstanced = function () {
  30249. return this._instanced;
  30250. };
  30251. /**
  30252. * Returns the instancing divisor, zero for non-instanced (integer).
  30253. * @returns a number
  30254. */
  30255. VertexBuffer.prototype.getInstanceDivisor = function () {
  30256. return this._instanceDivisor;
  30257. };
  30258. // Methods
  30259. /**
  30260. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30261. * @param data defines the data to store
  30262. */
  30263. VertexBuffer.prototype.create = function (data) {
  30264. this._buffer.create(data);
  30265. };
  30266. /**
  30267. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30268. * This function will create a new buffer if the current one is not updatable
  30269. * @param data defines the data to store
  30270. */
  30271. VertexBuffer.prototype.update = function (data) {
  30272. this._buffer.update(data);
  30273. };
  30274. /**
  30275. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30276. * Returns the directly updated WebGLBuffer.
  30277. * @param data the new data
  30278. * @param offset the new offset
  30279. * @param useBytes set to true if the offset is in bytes
  30280. */
  30281. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30282. if (useBytes === void 0) { useBytes = false; }
  30283. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30284. };
  30285. /**
  30286. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30287. */
  30288. VertexBuffer.prototype.dispose = function () {
  30289. if (this._ownsBuffer) {
  30290. this._buffer.dispose();
  30291. }
  30292. };
  30293. /**
  30294. * Enumerates each value of this vertex buffer as numbers.
  30295. * @param count the number of values to enumerate
  30296. * @param callback the callback function called for each value
  30297. */
  30298. VertexBuffer.prototype.forEach = function (count, callback) {
  30299. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30300. };
  30301. /**
  30302. * Deduces the stride given a kind.
  30303. * @param kind The kind string to deduce
  30304. * @returns The deduced stride
  30305. */
  30306. VertexBuffer.DeduceStride = function (kind) {
  30307. switch (kind) {
  30308. case VertexBuffer.UVKind:
  30309. case VertexBuffer.UV2Kind:
  30310. case VertexBuffer.UV3Kind:
  30311. case VertexBuffer.UV4Kind:
  30312. case VertexBuffer.UV5Kind:
  30313. case VertexBuffer.UV6Kind:
  30314. return 2;
  30315. case VertexBuffer.NormalKind:
  30316. case VertexBuffer.PositionKind:
  30317. return 3;
  30318. case VertexBuffer.ColorKind:
  30319. case VertexBuffer.MatricesIndicesKind:
  30320. case VertexBuffer.MatricesIndicesExtraKind:
  30321. case VertexBuffer.MatricesWeightsKind:
  30322. case VertexBuffer.MatricesWeightsExtraKind:
  30323. case VertexBuffer.TangentKind:
  30324. return 4;
  30325. default:
  30326. throw new Error("Invalid kind '" + kind + "'");
  30327. }
  30328. };
  30329. /**
  30330. * Gets the byte length of the given type.
  30331. * @param type the type
  30332. * @returns the number of bytes
  30333. */
  30334. VertexBuffer.GetTypeByteLength = function (type) {
  30335. switch (type) {
  30336. case VertexBuffer.BYTE:
  30337. case VertexBuffer.UNSIGNED_BYTE:
  30338. return 1;
  30339. case VertexBuffer.SHORT:
  30340. case VertexBuffer.UNSIGNED_SHORT:
  30341. return 2;
  30342. case VertexBuffer.INT:
  30343. case VertexBuffer.FLOAT:
  30344. return 4;
  30345. default:
  30346. throw new Error("Invalid type '" + type + "'");
  30347. }
  30348. };
  30349. /**
  30350. * Enumerates each value of the given parameters as numbers.
  30351. * @param data the data to enumerate
  30352. * @param byteOffset the byte offset of the data
  30353. * @param byteStride the byte stride of the data
  30354. * @param componentCount the number of components per element
  30355. * @param componentType the type of the component
  30356. * @param count the total number of components
  30357. * @param normalized whether the data is normalized
  30358. * @param callback the callback function called for each value
  30359. */
  30360. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30361. if (data instanceof Array) {
  30362. var offset = byteOffset / 4;
  30363. var stride = byteStride / 4;
  30364. for (var index = 0; index < count; index += componentCount) {
  30365. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30366. callback(data[offset + componentIndex], index + componentIndex);
  30367. }
  30368. offset += stride;
  30369. }
  30370. }
  30371. else {
  30372. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30373. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30374. for (var index = 0; index < count; index += componentCount) {
  30375. var componentByteOffset = byteOffset;
  30376. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30377. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30378. callback(value, index + componentIndex);
  30379. componentByteOffset += componentByteLength;
  30380. }
  30381. byteOffset += byteStride;
  30382. }
  30383. }
  30384. };
  30385. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30386. switch (type) {
  30387. case VertexBuffer.BYTE: {
  30388. var value = dataView.getInt8(byteOffset);
  30389. if (normalized) {
  30390. value = Math.max(value / 127, -1);
  30391. }
  30392. return value;
  30393. }
  30394. case VertexBuffer.UNSIGNED_BYTE: {
  30395. var value = dataView.getUint8(byteOffset);
  30396. if (normalized) {
  30397. value = value / 255;
  30398. }
  30399. return value;
  30400. }
  30401. case VertexBuffer.SHORT: {
  30402. var value = dataView.getInt16(byteOffset, true);
  30403. if (normalized) {
  30404. value = Math.max(value / 16383, -1);
  30405. }
  30406. return value;
  30407. }
  30408. case VertexBuffer.UNSIGNED_SHORT: {
  30409. var value = dataView.getUint16(byteOffset, true);
  30410. if (normalized) {
  30411. value = value / 65535;
  30412. }
  30413. return value;
  30414. }
  30415. case VertexBuffer.FLOAT: {
  30416. return dataView.getFloat32(byteOffset, true);
  30417. }
  30418. default: {
  30419. throw new Error("Invalid component type " + type);
  30420. }
  30421. }
  30422. };
  30423. /**
  30424. * The byte type.
  30425. */
  30426. VertexBuffer.BYTE = 5120;
  30427. /**
  30428. * The unsigned byte type.
  30429. */
  30430. VertexBuffer.UNSIGNED_BYTE = 5121;
  30431. /**
  30432. * The short type.
  30433. */
  30434. VertexBuffer.SHORT = 5122;
  30435. /**
  30436. * The unsigned short type.
  30437. */
  30438. VertexBuffer.UNSIGNED_SHORT = 5123;
  30439. /**
  30440. * The integer type.
  30441. */
  30442. VertexBuffer.INT = 5124;
  30443. /**
  30444. * The unsigned integer type.
  30445. */
  30446. VertexBuffer.UNSIGNED_INT = 5125;
  30447. /**
  30448. * The float type.
  30449. */
  30450. VertexBuffer.FLOAT = 5126;
  30451. // Enums
  30452. /**
  30453. * Positions
  30454. */
  30455. VertexBuffer.PositionKind = "position";
  30456. /**
  30457. * Normals
  30458. */
  30459. VertexBuffer.NormalKind = "normal";
  30460. /**
  30461. * Tangents
  30462. */
  30463. VertexBuffer.TangentKind = "tangent";
  30464. /**
  30465. * Texture coordinates
  30466. */
  30467. VertexBuffer.UVKind = "uv";
  30468. /**
  30469. * Texture coordinates 2
  30470. */
  30471. VertexBuffer.UV2Kind = "uv2";
  30472. /**
  30473. * Texture coordinates 3
  30474. */
  30475. VertexBuffer.UV3Kind = "uv3";
  30476. /**
  30477. * Texture coordinates 4
  30478. */
  30479. VertexBuffer.UV4Kind = "uv4";
  30480. /**
  30481. * Texture coordinates 5
  30482. */
  30483. VertexBuffer.UV5Kind = "uv5";
  30484. /**
  30485. * Texture coordinates 6
  30486. */
  30487. VertexBuffer.UV6Kind = "uv6";
  30488. /**
  30489. * Colors
  30490. */
  30491. VertexBuffer.ColorKind = "color";
  30492. /**
  30493. * Matrix indices (for bones)
  30494. */
  30495. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30496. /**
  30497. * Matrix weights (for bones)
  30498. */
  30499. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30500. /**
  30501. * Additional matrix indices (for bones)
  30502. */
  30503. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30504. /**
  30505. * Additional matrix weights (for bones)
  30506. */
  30507. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30508. return VertexBuffer;
  30509. }());
  30510. BABYLON.VertexBuffer = VertexBuffer;
  30511. })(BABYLON || (BABYLON = {}));
  30512. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30513. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30514. var BABYLON;
  30515. (function (BABYLON) {
  30516. /**
  30517. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30518. */
  30519. var DummyInternalTextureTracker = /** @class */ (function () {
  30520. function DummyInternalTextureTracker() {
  30521. /**
  30522. * Gets or set the previous tracker in the list
  30523. */
  30524. this.previous = null;
  30525. /**
  30526. * Gets or set the next tracker in the list
  30527. */
  30528. this.next = null;
  30529. }
  30530. return DummyInternalTextureTracker;
  30531. }());
  30532. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30533. })(BABYLON || (BABYLON = {}));
  30534. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30535. var BABYLON;
  30536. (function (BABYLON) {
  30537. /**
  30538. * Class used to store data associated with WebGL texture data for the engine
  30539. * This class should not be used directly
  30540. */
  30541. var InternalTexture = /** @class */ (function () {
  30542. /**
  30543. * Creates a new InternalTexture
  30544. * @param engine defines the engine to use
  30545. * @param dataSource defines the type of data that will be used
  30546. */
  30547. function InternalTexture(engine, dataSource) {
  30548. /**
  30549. * Observable called when the texture is loaded
  30550. */
  30551. this.onLoadedObservable = new BABYLON.Observable();
  30552. /**
  30553. * Gets or set the previous tracker in the list
  30554. */
  30555. this.previous = null;
  30556. /**
  30557. * Gets or set the next tracker in the list
  30558. */
  30559. this.next = null;
  30560. // Private
  30561. /** @hidden */
  30562. this._initialSlot = -1;
  30563. /** @hidden */
  30564. this._designatedSlot = -1;
  30565. /** @hidden */
  30566. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30567. /** @hidden */
  30568. this._comparisonFunction = 0;
  30569. /** @hidden */
  30570. this._sphericalPolynomial = null;
  30571. /** @hidden */
  30572. this._lodGenerationScale = 0;
  30573. /** @hidden */
  30574. this._lodGenerationOffset = 0;
  30575. /** @hidden */
  30576. this._isRGBD = false;
  30577. /** @hidden */
  30578. this._references = 1;
  30579. this._engine = engine;
  30580. this._dataSource = dataSource;
  30581. this._webGLTexture = engine._createTexture();
  30582. }
  30583. /**
  30584. * Gets the Engine the texture belongs to.
  30585. * @returns The babylon engine
  30586. */
  30587. InternalTexture.prototype.getEngine = function () {
  30588. return this._engine;
  30589. };
  30590. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30591. /**
  30592. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30593. */
  30594. get: function () {
  30595. return this._dataSource;
  30596. },
  30597. enumerable: true,
  30598. configurable: true
  30599. });
  30600. /**
  30601. * Increments the number of references (ie. the number of Texture that point to it)
  30602. */
  30603. InternalTexture.prototype.incrementReferences = function () {
  30604. this._references++;
  30605. };
  30606. /**
  30607. * Change the size of the texture (not the size of the content)
  30608. * @param width defines the new width
  30609. * @param height defines the new height
  30610. * @param depth defines the new depth (1 by default)
  30611. */
  30612. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30613. if (depth === void 0) { depth = 1; }
  30614. this.width = width;
  30615. this.height = height;
  30616. this.depth = depth;
  30617. this.baseWidth = width;
  30618. this.baseHeight = height;
  30619. this.baseDepth = depth;
  30620. this._size = width * height * depth;
  30621. };
  30622. /** @hidden */
  30623. InternalTexture.prototype._rebuild = function () {
  30624. var _this = this;
  30625. var proxy;
  30626. this.isReady = false;
  30627. this._cachedCoordinatesMode = null;
  30628. this._cachedWrapU = null;
  30629. this._cachedWrapV = null;
  30630. this._cachedAnisotropicFilteringLevel = null;
  30631. switch (this._dataSource) {
  30632. case InternalTexture.DATASOURCE_TEMP:
  30633. return;
  30634. case InternalTexture.DATASOURCE_URL:
  30635. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30636. _this.isReady = true;
  30637. }, null, this._buffer, undefined, this.format);
  30638. proxy._swapAndDie(this);
  30639. return;
  30640. case InternalTexture.DATASOURCE_RAW:
  30641. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30642. proxy._swapAndDie(this);
  30643. this.isReady = true;
  30644. return;
  30645. case InternalTexture.DATASOURCE_RAW3D:
  30646. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30647. proxy._swapAndDie(this);
  30648. this.isReady = true;
  30649. return;
  30650. case InternalTexture.DATASOURCE_DYNAMIC:
  30651. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30652. proxy._swapAndDie(this);
  30653. // The engine will make sure to update content so no need to flag it as isReady = true
  30654. return;
  30655. case InternalTexture.DATASOURCE_RENDERTARGET:
  30656. var options = new BABYLON.RenderTargetCreationOptions();
  30657. options.generateDepthBuffer = this._generateDepthBuffer;
  30658. options.generateMipMaps = this.generateMipMaps;
  30659. options.generateStencilBuffer = this._generateStencilBuffer;
  30660. options.samplingMode = this.samplingMode;
  30661. options.type = this.type;
  30662. if (this.isCube) {
  30663. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30664. }
  30665. else {
  30666. var size = {
  30667. width: this.width,
  30668. height: this.height
  30669. };
  30670. proxy = this._engine.createRenderTargetTexture(size, options);
  30671. }
  30672. proxy._swapAndDie(this);
  30673. this.isReady = true;
  30674. return;
  30675. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30676. var depthTextureOptions = {
  30677. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30678. comparisonFunction: this._comparisonFunction,
  30679. generateStencil: this._generateStencilBuffer,
  30680. isCube: this.isCube
  30681. };
  30682. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30683. proxy._swapAndDie(this);
  30684. this.isReady = true;
  30685. return;
  30686. case InternalTexture.DATASOURCE_CUBE:
  30687. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30688. _this.isReady = true;
  30689. }, null, this.format, this._extension);
  30690. proxy._swapAndDie(this);
  30691. return;
  30692. case InternalTexture.DATASOURCE_CUBERAW:
  30693. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30694. proxy._swapAndDie(this);
  30695. this.isReady = true;
  30696. return;
  30697. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30698. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30699. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30700. _this.isReady = true;
  30701. });
  30702. proxy._swapAndDie(this);
  30703. return;
  30704. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30705. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30706. if (proxy) {
  30707. proxy._swapAndDie(_this);
  30708. }
  30709. _this.isReady = true;
  30710. }, null, this.format, this._extension);
  30711. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30712. return;
  30713. }
  30714. };
  30715. /** @hidden */
  30716. InternalTexture.prototype._swapAndDie = function (target) {
  30717. target._webGLTexture = this._webGLTexture;
  30718. if (this._framebuffer) {
  30719. target._framebuffer = this._framebuffer;
  30720. }
  30721. if (this._depthStencilBuffer) {
  30722. target._depthStencilBuffer = this._depthStencilBuffer;
  30723. }
  30724. if (this._lodTextureHigh) {
  30725. if (target._lodTextureHigh) {
  30726. target._lodTextureHigh.dispose();
  30727. }
  30728. target._lodTextureHigh = this._lodTextureHigh;
  30729. }
  30730. if (this._lodTextureMid) {
  30731. if (target._lodTextureMid) {
  30732. target._lodTextureMid.dispose();
  30733. }
  30734. target._lodTextureMid = this._lodTextureMid;
  30735. }
  30736. if (this._lodTextureLow) {
  30737. if (target._lodTextureLow) {
  30738. target._lodTextureLow.dispose();
  30739. }
  30740. target._lodTextureLow = this._lodTextureLow;
  30741. }
  30742. var cache = this._engine.getLoadedTexturesCache();
  30743. var index = cache.indexOf(this);
  30744. if (index !== -1) {
  30745. cache.splice(index, 1);
  30746. }
  30747. };
  30748. /**
  30749. * Dispose the current allocated resources
  30750. */
  30751. InternalTexture.prototype.dispose = function () {
  30752. if (!this._webGLTexture) {
  30753. return;
  30754. }
  30755. this._references--;
  30756. if (this._references === 0) {
  30757. this._engine._releaseTexture(this);
  30758. this._webGLTexture = null;
  30759. this.previous = null;
  30760. this.next = null;
  30761. }
  30762. };
  30763. /**
  30764. * The source of the texture data is unknown
  30765. */
  30766. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30767. /**
  30768. * Texture data comes from an URL
  30769. */
  30770. InternalTexture.DATASOURCE_URL = 1;
  30771. /**
  30772. * Texture data is only used for temporary storage
  30773. */
  30774. InternalTexture.DATASOURCE_TEMP = 2;
  30775. /**
  30776. * Texture data comes from raw data (ArrayBuffer)
  30777. */
  30778. InternalTexture.DATASOURCE_RAW = 3;
  30779. /**
  30780. * Texture content is dynamic (video or dynamic texture)
  30781. */
  30782. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30783. /**
  30784. * Texture content is generated by rendering to it
  30785. */
  30786. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30787. /**
  30788. * Texture content is part of a multi render target process
  30789. */
  30790. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30791. /**
  30792. * Texture data comes from a cube data file
  30793. */
  30794. InternalTexture.DATASOURCE_CUBE = 7;
  30795. /**
  30796. * Texture data comes from a raw cube data
  30797. */
  30798. InternalTexture.DATASOURCE_CUBERAW = 8;
  30799. /**
  30800. * Texture data come from a prefiltered cube data file
  30801. */
  30802. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30803. /**
  30804. * Texture content is raw 3D data
  30805. */
  30806. InternalTexture.DATASOURCE_RAW3D = 10;
  30807. /**
  30808. * Texture content is a depth texture
  30809. */
  30810. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30811. /**
  30812. * Texture data comes from a raw cube data encoded with RGBD
  30813. */
  30814. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30815. return InternalTexture;
  30816. }());
  30817. BABYLON.InternalTexture = InternalTexture;
  30818. })(BABYLON || (BABYLON = {}));
  30819. //# sourceMappingURL=babylon.internalTexture.js.map
  30820. var BABYLON;
  30821. (function (BABYLON) {
  30822. /**
  30823. * Base class of all the textures in babylon.
  30824. * It groups all the common properties the materials, post process, lights... might need
  30825. * in order to make a correct use of the texture.
  30826. */
  30827. var BaseTexture = /** @class */ (function () {
  30828. /**
  30829. * Instantiates a new BaseTexture.
  30830. * Base class of all the textures in babylon.
  30831. * It groups all the common properties the materials, post process, lights... might need
  30832. * in order to make a correct use of the texture.
  30833. * @param scene Define the scene the texture blongs to
  30834. */
  30835. function BaseTexture(scene) {
  30836. this._hasAlpha = false;
  30837. /**
  30838. * Defines if the alpha value should be determined via the rgb values.
  30839. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30840. */
  30841. this.getAlphaFromRGB = false;
  30842. /**
  30843. * Intensity or strength of the texture.
  30844. * It is commonly used by materials to fine tune the intensity of the texture
  30845. */
  30846. this.level = 1;
  30847. /**
  30848. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30849. * This is part of the texture as textures usually maps to one uv set.
  30850. */
  30851. this.coordinatesIndex = 0;
  30852. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30853. /**
  30854. * | Value | Type | Description |
  30855. * | ----- | ------------------ | ----------- |
  30856. * | 0 | CLAMP_ADDRESSMODE | |
  30857. * | 1 | WRAP_ADDRESSMODE | |
  30858. * | 2 | MIRROR_ADDRESSMODE | |
  30859. */
  30860. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30861. /**
  30862. * | Value | Type | Description |
  30863. * | ----- | ------------------ | ----------- |
  30864. * | 0 | CLAMP_ADDRESSMODE | |
  30865. * | 1 | WRAP_ADDRESSMODE | |
  30866. * | 2 | MIRROR_ADDRESSMODE | |
  30867. */
  30868. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30869. /**
  30870. * | Value | Type | Description |
  30871. * | ----- | ------------------ | ----------- |
  30872. * | 0 | CLAMP_ADDRESSMODE | |
  30873. * | 1 | WRAP_ADDRESSMODE | |
  30874. * | 2 | MIRROR_ADDRESSMODE | |
  30875. */
  30876. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30877. /**
  30878. * With compliant hardware and browser (supporting anisotropic filtering)
  30879. * this defines the level of anisotropic filtering in the texture.
  30880. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30881. */
  30882. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30883. /**
  30884. * Define if the texture is a cube texture or if false a 2d texture.
  30885. */
  30886. this.isCube = false;
  30887. /**
  30888. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30889. */
  30890. this.is3D = false;
  30891. /**
  30892. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30893. * HDR texture are usually stored in linear space.
  30894. * This only impacts the PBR and Background materials
  30895. */
  30896. this.gammaSpace = true;
  30897. /**
  30898. * Is Z inverted in the texture (useful in a cube texture).
  30899. */
  30900. this.invertZ = false;
  30901. /**
  30902. * @hidden
  30903. */
  30904. this.lodLevelInAlpha = false;
  30905. /**
  30906. * Define if the texture is a render target.
  30907. */
  30908. this.isRenderTarget = false;
  30909. /**
  30910. * Define the list of animation attached to the texture.
  30911. */
  30912. this.animations = new Array();
  30913. /**
  30914. * An event triggered when the texture is disposed.
  30915. */
  30916. this.onDisposeObservable = new BABYLON.Observable();
  30917. /**
  30918. * Define the current state of the loading sequence when in delayed load mode.
  30919. */
  30920. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30921. this._cachedSize = BABYLON.Size.Zero();
  30922. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30923. if (this._scene) {
  30924. this._scene.textures.push(this);
  30925. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30926. }
  30927. this._uid = null;
  30928. }
  30929. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30930. get: function () {
  30931. return this._hasAlpha;
  30932. },
  30933. /**
  30934. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30935. */
  30936. set: function (value) {
  30937. if (this._hasAlpha === value) {
  30938. return;
  30939. }
  30940. this._hasAlpha = value;
  30941. if (this._scene) {
  30942. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30943. }
  30944. },
  30945. enumerable: true,
  30946. configurable: true
  30947. });
  30948. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30949. get: function () {
  30950. return this._coordinatesMode;
  30951. },
  30952. /**
  30953. * How a texture is mapped.
  30954. *
  30955. * | Value | Type | Description |
  30956. * | ----- | ----------------------------------- | ----------- |
  30957. * | 0 | EXPLICIT_MODE | |
  30958. * | 1 | SPHERICAL_MODE | |
  30959. * | 2 | PLANAR_MODE | |
  30960. * | 3 | CUBIC_MODE | |
  30961. * | 4 | PROJECTION_MODE | |
  30962. * | 5 | SKYBOX_MODE | |
  30963. * | 6 | INVCUBIC_MODE | |
  30964. * | 7 | EQUIRECTANGULAR_MODE | |
  30965. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30966. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30967. */
  30968. set: function (value) {
  30969. if (this._coordinatesMode === value) {
  30970. return;
  30971. }
  30972. this._coordinatesMode = value;
  30973. if (this._scene) {
  30974. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30975. }
  30976. },
  30977. enumerable: true,
  30978. configurable: true
  30979. });
  30980. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30981. /**
  30982. * Gets whether or not the texture contains RGBD data.
  30983. */
  30984. get: function () {
  30985. return this._texture != null && this._texture._isRGBD;
  30986. },
  30987. enumerable: true,
  30988. configurable: true
  30989. });
  30990. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30991. /**
  30992. * With prefiltered texture, defined the offset used during the prefiltering steps.
  30993. */
  30994. get: function () {
  30995. if (this._texture) {
  30996. return this._texture._lodGenerationOffset;
  30997. }
  30998. return 0.0;
  30999. },
  31000. set: function (value) {
  31001. if (this._texture) {
  31002. this._texture._lodGenerationOffset = value;
  31003. }
  31004. },
  31005. enumerable: true,
  31006. configurable: true
  31007. });
  31008. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31009. /**
  31010. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31011. */
  31012. get: function () {
  31013. if (this._texture) {
  31014. return this._texture._lodGenerationScale;
  31015. }
  31016. return 0.0;
  31017. },
  31018. set: function (value) {
  31019. if (this._texture) {
  31020. this._texture._lodGenerationScale = value;
  31021. }
  31022. },
  31023. enumerable: true,
  31024. configurable: true
  31025. });
  31026. Object.defineProperty(BaseTexture.prototype, "uid", {
  31027. /**
  31028. * Define the unique id of the texture in the scene.
  31029. */
  31030. get: function () {
  31031. if (!this._uid) {
  31032. this._uid = BABYLON.Tools.RandomId();
  31033. }
  31034. return this._uid;
  31035. },
  31036. enumerable: true,
  31037. configurable: true
  31038. });
  31039. /**
  31040. * Return a string representation of the texture.
  31041. * @returns the texture as a string
  31042. */
  31043. BaseTexture.prototype.toString = function () {
  31044. return this.name;
  31045. };
  31046. /**
  31047. * Get the class name of the texture.
  31048. * @returns "BaseTexture"
  31049. */
  31050. BaseTexture.prototype.getClassName = function () {
  31051. return "BaseTexture";
  31052. };
  31053. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31054. /**
  31055. * Callback triggered when the texture has been disposed.
  31056. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31057. */
  31058. set: function (callback) {
  31059. if (this._onDisposeObserver) {
  31060. this.onDisposeObservable.remove(this._onDisposeObserver);
  31061. }
  31062. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31063. },
  31064. enumerable: true,
  31065. configurable: true
  31066. });
  31067. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31068. /**
  31069. * Define if the texture is preventinga material to render or not.
  31070. * If not and the texture is not ready, the engine will use a default black texture instead.
  31071. */
  31072. get: function () {
  31073. return true;
  31074. },
  31075. enumerable: true,
  31076. configurable: true
  31077. });
  31078. /**
  31079. * Get the scene the texture belongs to.
  31080. * @returns the scene or null if undefined
  31081. */
  31082. BaseTexture.prototype.getScene = function () {
  31083. return this._scene;
  31084. };
  31085. /**
  31086. * Get the texture transform matrix used to offset tile the texture for istance.
  31087. * @returns the transformation matrix
  31088. */
  31089. BaseTexture.prototype.getTextureMatrix = function () {
  31090. return BABYLON.Matrix.IdentityReadOnly;
  31091. };
  31092. /**
  31093. * Get the texture reflection matrix used to rotate/transform the reflection.
  31094. * @returns the reflection matrix
  31095. */
  31096. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31097. return BABYLON.Matrix.IdentityReadOnly;
  31098. };
  31099. /**
  31100. * Get the underlying lower level texture from Babylon.
  31101. * @returns the insternal texture
  31102. */
  31103. BaseTexture.prototype.getInternalTexture = function () {
  31104. return this._texture;
  31105. };
  31106. /**
  31107. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31108. * @returns true if ready or not blocking
  31109. */
  31110. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31111. return !this.isBlocking || this.isReady();
  31112. };
  31113. /**
  31114. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31115. * @returns true if fully ready
  31116. */
  31117. BaseTexture.prototype.isReady = function () {
  31118. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31119. this.delayLoad();
  31120. return false;
  31121. }
  31122. if (this._texture) {
  31123. return this._texture.isReady;
  31124. }
  31125. return false;
  31126. };
  31127. /**
  31128. * Get the size of the texture.
  31129. * @returns the texture size.
  31130. */
  31131. BaseTexture.prototype.getSize = function () {
  31132. if (this._texture) {
  31133. if (this._texture.width) {
  31134. this._cachedSize.width = this._texture.width;
  31135. this._cachedSize.height = this._texture.height;
  31136. return this._cachedSize;
  31137. }
  31138. if (this._texture._size) {
  31139. this._cachedSize.width = this._texture._size;
  31140. this._cachedSize.height = this._texture._size;
  31141. return this._cachedSize;
  31142. }
  31143. }
  31144. return this._cachedSize;
  31145. };
  31146. /**
  31147. * Get the base size of the texture.
  31148. * It can be different from the size if the texture has been resized for POT for instance
  31149. * @returns the base size
  31150. */
  31151. BaseTexture.prototype.getBaseSize = function () {
  31152. if (!this.isReady() || !this._texture) {
  31153. return BABYLON.Size.Zero();
  31154. }
  31155. if (this._texture._size) {
  31156. return new BABYLON.Size(this._texture._size, this._texture._size);
  31157. }
  31158. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31159. };
  31160. /**
  31161. * Scales the texture if is `canRescale()`
  31162. * @param ratio the resize factor we want to use to rescale
  31163. */
  31164. BaseTexture.prototype.scale = function (ratio) {
  31165. };
  31166. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31167. /**
  31168. * Get if the texture can rescale.
  31169. */
  31170. get: function () {
  31171. return false;
  31172. },
  31173. enumerable: true,
  31174. configurable: true
  31175. });
  31176. /** @hidden */
  31177. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31178. if (!this._scene) {
  31179. return null;
  31180. }
  31181. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31182. for (var index = 0; index < texturesCache.length; index++) {
  31183. var texturesCacheEntry = texturesCache[index];
  31184. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31185. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31186. texturesCacheEntry.incrementReferences();
  31187. return texturesCacheEntry;
  31188. }
  31189. }
  31190. }
  31191. return null;
  31192. };
  31193. /** @hidden */
  31194. BaseTexture.prototype._rebuild = function () {
  31195. };
  31196. /**
  31197. * Triggers the load sequence in delayed load mode.
  31198. */
  31199. BaseTexture.prototype.delayLoad = function () {
  31200. };
  31201. /**
  31202. * Clones the texture.
  31203. * @returns the cloned texture
  31204. */
  31205. BaseTexture.prototype.clone = function () {
  31206. return null;
  31207. };
  31208. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31209. /**
  31210. * Get the texture underlying type (INT, FLOAT...)
  31211. */
  31212. get: function () {
  31213. if (!this._texture) {
  31214. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31215. }
  31216. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31217. },
  31218. enumerable: true,
  31219. configurable: true
  31220. });
  31221. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31222. /**
  31223. * Get the texture underlying format (RGB, RGBA...)
  31224. */
  31225. get: function () {
  31226. if (!this._texture) {
  31227. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31228. }
  31229. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31230. },
  31231. enumerable: true,
  31232. configurable: true
  31233. });
  31234. /**
  31235. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31236. * This will returns an RGBA array buffer containing either in values (0-255) or
  31237. * float values (0-1) depending of the underlying buffer type.
  31238. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31239. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31240. * @param buffer defines a user defined buffer to fill with data (can be null)
  31241. * @returns The Array buffer containing the pixels data.
  31242. */
  31243. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31244. if (faceIndex === void 0) { faceIndex = 0; }
  31245. if (level === void 0) { level = 0; }
  31246. if (buffer === void 0) { buffer = null; }
  31247. if (!this._texture) {
  31248. return null;
  31249. }
  31250. var size = this.getSize();
  31251. var width = size.width;
  31252. var height = size.height;
  31253. var scene = this.getScene();
  31254. if (!scene) {
  31255. return null;
  31256. }
  31257. var engine = scene.getEngine();
  31258. if (level != 0) {
  31259. width = width / Math.pow(2, level);
  31260. height = height / Math.pow(2, level);
  31261. width = Math.round(width);
  31262. height = Math.round(height);
  31263. }
  31264. if (this._texture.isCube) {
  31265. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31266. }
  31267. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31268. };
  31269. /**
  31270. * Release and destroy the underlying lower level texture aka internalTexture.
  31271. */
  31272. BaseTexture.prototype.releaseInternalTexture = function () {
  31273. if (this._texture) {
  31274. this._texture.dispose();
  31275. this._texture = null;
  31276. }
  31277. };
  31278. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31279. /**
  31280. * Get the polynomial representation of the texture data.
  31281. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31282. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31283. */
  31284. get: function () {
  31285. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31286. return null;
  31287. }
  31288. if (!this._texture._sphericalPolynomial) {
  31289. this._texture._sphericalPolynomial =
  31290. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31291. }
  31292. return this._texture._sphericalPolynomial;
  31293. },
  31294. set: function (value) {
  31295. if (this._texture) {
  31296. this._texture._sphericalPolynomial = value;
  31297. }
  31298. },
  31299. enumerable: true,
  31300. configurable: true
  31301. });
  31302. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31303. /** @hidden */
  31304. get: function () {
  31305. if (this._texture) {
  31306. return this._texture._lodTextureHigh;
  31307. }
  31308. return null;
  31309. },
  31310. enumerable: true,
  31311. configurable: true
  31312. });
  31313. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31314. /** @hidden */
  31315. get: function () {
  31316. if (this._texture) {
  31317. return this._texture._lodTextureMid;
  31318. }
  31319. return null;
  31320. },
  31321. enumerable: true,
  31322. configurable: true
  31323. });
  31324. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31325. /** @hidden */
  31326. get: function () {
  31327. if (this._texture) {
  31328. return this._texture._lodTextureLow;
  31329. }
  31330. return null;
  31331. },
  31332. enumerable: true,
  31333. configurable: true
  31334. });
  31335. /**
  31336. * Dispose the texture and release its associated resources.
  31337. */
  31338. BaseTexture.prototype.dispose = function () {
  31339. if (!this._scene) {
  31340. return;
  31341. }
  31342. // Animations
  31343. this._scene.stopAnimation(this);
  31344. // Remove from scene
  31345. this._scene._removePendingData(this);
  31346. var index = this._scene.textures.indexOf(this);
  31347. if (index >= 0) {
  31348. this._scene.textures.splice(index, 1);
  31349. }
  31350. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31351. if (this._texture === undefined) {
  31352. return;
  31353. }
  31354. // Release
  31355. this.releaseInternalTexture();
  31356. // Callback
  31357. this.onDisposeObservable.notifyObservers(this);
  31358. this.onDisposeObservable.clear();
  31359. };
  31360. /**
  31361. * Serialize the texture into a JSON representation that can be parsed later on.
  31362. * @returns the JSON representation of the texture
  31363. */
  31364. BaseTexture.prototype.serialize = function () {
  31365. if (!this.name) {
  31366. return null;
  31367. }
  31368. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31369. // Animations
  31370. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31371. return serializationObject;
  31372. };
  31373. /**
  31374. * Helper function to be called back once a list of texture contains only ready textures.
  31375. * @param textures Define the list of textures to wait for
  31376. * @param callback Define the callback triggered once the entire list will be ready
  31377. */
  31378. BaseTexture.WhenAllReady = function (textures, callback) {
  31379. var numRemaining = textures.length;
  31380. if (numRemaining === 0) {
  31381. callback();
  31382. return;
  31383. }
  31384. var _loop_1 = function () {
  31385. texture = textures[i];
  31386. if (texture.isReady()) {
  31387. if (--numRemaining === 0) {
  31388. callback();
  31389. }
  31390. }
  31391. else {
  31392. onLoadObservable = texture.onLoadObservable;
  31393. var onLoadCallback_1 = function () {
  31394. onLoadObservable.removeCallback(onLoadCallback_1);
  31395. if (--numRemaining === 0) {
  31396. callback();
  31397. }
  31398. };
  31399. onLoadObservable.add(onLoadCallback_1);
  31400. }
  31401. };
  31402. var texture, onLoadObservable;
  31403. for (var i = 0; i < textures.length; i++) {
  31404. _loop_1();
  31405. }
  31406. };
  31407. /**
  31408. * Default anisotropic filtering level for the application.
  31409. * It is set to 4 as a good tradeoff between perf and quality.
  31410. */
  31411. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31412. __decorate([
  31413. BABYLON.serialize()
  31414. ], BaseTexture.prototype, "name", void 0);
  31415. __decorate([
  31416. BABYLON.serialize("hasAlpha")
  31417. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31418. __decorate([
  31419. BABYLON.serialize()
  31420. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31421. __decorate([
  31422. BABYLON.serialize()
  31423. ], BaseTexture.prototype, "level", void 0);
  31424. __decorate([
  31425. BABYLON.serialize()
  31426. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31427. __decorate([
  31428. BABYLON.serialize("coordinatesMode")
  31429. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31430. __decorate([
  31431. BABYLON.serialize()
  31432. ], BaseTexture.prototype, "wrapU", void 0);
  31433. __decorate([
  31434. BABYLON.serialize()
  31435. ], BaseTexture.prototype, "wrapV", void 0);
  31436. __decorate([
  31437. BABYLON.serialize()
  31438. ], BaseTexture.prototype, "wrapR", void 0);
  31439. __decorate([
  31440. BABYLON.serialize()
  31441. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31442. __decorate([
  31443. BABYLON.serialize()
  31444. ], BaseTexture.prototype, "isCube", void 0);
  31445. __decorate([
  31446. BABYLON.serialize()
  31447. ], BaseTexture.prototype, "is3D", void 0);
  31448. __decorate([
  31449. BABYLON.serialize()
  31450. ], BaseTexture.prototype, "gammaSpace", void 0);
  31451. __decorate([
  31452. BABYLON.serialize()
  31453. ], BaseTexture.prototype, "invertZ", void 0);
  31454. __decorate([
  31455. BABYLON.serialize()
  31456. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31457. __decorate([
  31458. BABYLON.serialize()
  31459. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31460. __decorate([
  31461. BABYLON.serialize()
  31462. ], BaseTexture.prototype, "lodGenerationScale", null);
  31463. __decorate([
  31464. BABYLON.serialize()
  31465. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31466. return BaseTexture;
  31467. }());
  31468. BABYLON.BaseTexture = BaseTexture;
  31469. })(BABYLON || (BABYLON = {}));
  31470. //# sourceMappingURL=babylon.baseTexture.js.map
  31471. var BABYLON;
  31472. (function (BABYLON) {
  31473. /**
  31474. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31475. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31476. */
  31477. var Texture = /** @class */ (function (_super) {
  31478. __extends(Texture, _super);
  31479. /**
  31480. * Instantiates a new texture.
  31481. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31482. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31483. * @param url define the url of the picture to load as a texture
  31484. * @param scene define the scene the texture will belong to
  31485. * @param noMipmap define if the texture will require mip maps or not
  31486. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31487. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31488. * @param onLoad define a callback triggered when the texture has been loaded
  31489. * @param onError define a callback triggered when an error occurred during the loading session
  31490. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31491. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31492. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31493. */
  31494. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31495. if (noMipmap === void 0) { noMipmap = false; }
  31496. if (invertY === void 0) { invertY = true; }
  31497. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31498. if (onLoad === void 0) { onLoad = null; }
  31499. if (onError === void 0) { onError = null; }
  31500. if (buffer === void 0) { buffer = null; }
  31501. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31502. var _this = _super.call(this, scene) || this;
  31503. /**
  31504. * Define an offset on the texture to offset the u coordinates of the UVs
  31505. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31506. */
  31507. _this.uOffset = 0;
  31508. /**
  31509. * Define an offset on the texture to offset the v coordinates of the UVs
  31510. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31511. */
  31512. _this.vOffset = 0;
  31513. /**
  31514. * Define an offset on the texture to scale the u coordinates of the UVs
  31515. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31516. */
  31517. _this.uScale = 1.0;
  31518. /**
  31519. * Define an offset on the texture to scale the v coordinates of the UVs
  31520. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31521. */
  31522. _this.vScale = 1.0;
  31523. /**
  31524. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31525. * @see http://doc.babylonjs.com/how_to/more_materials
  31526. */
  31527. _this.uAng = 0;
  31528. /**
  31529. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31530. * @see http://doc.babylonjs.com/how_to/more_materials
  31531. */
  31532. _this.vAng = 0;
  31533. /**
  31534. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31535. * @see http://doc.babylonjs.com/how_to/more_materials
  31536. */
  31537. _this.wAng = 0;
  31538. /**
  31539. * Defines the center of rotation (U)
  31540. */
  31541. _this.uRotationCenter = 0.5;
  31542. /**
  31543. * Defines the center of rotation (V)
  31544. */
  31545. _this.vRotationCenter = 0.5;
  31546. /**
  31547. * Defines the center of rotation (W)
  31548. */
  31549. _this.wRotationCenter = 0.5;
  31550. /**
  31551. * Observable triggered once the texture has been loaded.
  31552. */
  31553. _this.onLoadObservable = new BABYLON.Observable();
  31554. _this._isBlocking = true;
  31555. _this.name = url || "";
  31556. _this.url = url;
  31557. _this._noMipmap = noMipmap;
  31558. _this._invertY = invertY;
  31559. _this._samplingMode = samplingMode;
  31560. _this._buffer = buffer;
  31561. _this._deleteBuffer = deleteBuffer;
  31562. if (format) {
  31563. _this._format = format;
  31564. }
  31565. scene = _this.getScene();
  31566. if (!scene) {
  31567. return _this;
  31568. }
  31569. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31570. var load = function () {
  31571. if (_this.onLoadObservable.hasObservers()) {
  31572. _this.onLoadObservable.notifyObservers(_this);
  31573. }
  31574. if (onLoad) {
  31575. onLoad();
  31576. }
  31577. if (!_this.isBlocking && scene) {
  31578. scene.resetCachedMaterial();
  31579. }
  31580. };
  31581. if (!_this.url) {
  31582. _this._delayedOnLoad = load;
  31583. _this._delayedOnError = onError;
  31584. return _this;
  31585. }
  31586. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31587. if (!_this._texture) {
  31588. if (!scene.useDelayedTextureLoading) {
  31589. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31590. if (deleteBuffer) {
  31591. delete _this._buffer;
  31592. }
  31593. }
  31594. else {
  31595. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31596. _this._delayedOnLoad = load;
  31597. _this._delayedOnError = onError;
  31598. }
  31599. }
  31600. else {
  31601. if (_this._texture.isReady) {
  31602. BABYLON.Tools.SetImmediate(function () { return load(); });
  31603. }
  31604. else {
  31605. _this._texture.onLoadedObservable.add(load);
  31606. }
  31607. }
  31608. return _this;
  31609. }
  31610. Object.defineProperty(Texture.prototype, "noMipmap", {
  31611. /**
  31612. * Are mip maps generated for this texture or not.
  31613. */
  31614. get: function () {
  31615. return this._noMipmap;
  31616. },
  31617. enumerable: true,
  31618. configurable: true
  31619. });
  31620. Object.defineProperty(Texture.prototype, "isBlocking", {
  31621. get: function () {
  31622. return this._isBlocking;
  31623. },
  31624. /**
  31625. * Is the texture preventing material to render while loading.
  31626. * If false, a default texture will be used instead of the loading one during the preparation step.
  31627. */
  31628. set: function (value) {
  31629. this._isBlocking = value;
  31630. },
  31631. enumerable: true,
  31632. configurable: true
  31633. });
  31634. Object.defineProperty(Texture.prototype, "samplingMode", {
  31635. /**
  31636. * Get the current sampling mode associated with the texture.
  31637. */
  31638. get: function () {
  31639. return this._samplingMode;
  31640. },
  31641. enumerable: true,
  31642. configurable: true
  31643. });
  31644. /**
  31645. * Update the url (and optional buffer) of this texture if url was null during construction.
  31646. * @param url the url of the texture
  31647. * @param buffer the buffer of the texture (defaults to null)
  31648. */
  31649. Texture.prototype.updateURL = function (url, buffer) {
  31650. if (buffer === void 0) { buffer = null; }
  31651. if (this.url) {
  31652. throw new Error("URL is already set");
  31653. }
  31654. this.url = url;
  31655. this._buffer = buffer;
  31656. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31657. this.delayLoad();
  31658. };
  31659. /**
  31660. * Finish the loading sequence of a texture flagged as delayed load.
  31661. * @hidden
  31662. */
  31663. Texture.prototype.delayLoad = function () {
  31664. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31665. return;
  31666. }
  31667. var scene = this.getScene();
  31668. if (!scene) {
  31669. return;
  31670. }
  31671. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31672. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31673. if (!this._texture) {
  31674. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31675. if (this._deleteBuffer) {
  31676. delete this._buffer;
  31677. }
  31678. }
  31679. else {
  31680. if (this._delayedOnLoad) {
  31681. if (this._texture.isReady) {
  31682. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31683. }
  31684. else {
  31685. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31686. }
  31687. }
  31688. }
  31689. this._delayedOnLoad = null;
  31690. this._delayedOnError = null;
  31691. };
  31692. /**
  31693. * Update the sampling mode of the texture.
  31694. * Default is Trilinear mode.
  31695. *
  31696. * | Value | Type | Description |
  31697. * | ----- | ------------------ | ----------- |
  31698. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31699. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31700. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31701. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31702. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31703. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31704. * | 7 | NEAREST_LINEAR | |
  31705. * | 8 | NEAREST_NEAREST | |
  31706. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31707. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31708. * | 11 | LINEAR_LINEAR | |
  31709. * | 12 | LINEAR_NEAREST | |
  31710. *
  31711. * > _mag_: magnification filter (close to the viewer)
  31712. * > _min_: minification filter (far from the viewer)
  31713. * > _mip_: filter used between mip map levels
  31714. *@param samplingMode Define the new sampling mode of the texture
  31715. */
  31716. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31717. if (!this._texture) {
  31718. return;
  31719. }
  31720. var scene = this.getScene();
  31721. if (!scene) {
  31722. return;
  31723. }
  31724. this._samplingMode = samplingMode;
  31725. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31726. };
  31727. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31728. x *= this.uScale;
  31729. y *= this.vScale;
  31730. x -= this.uRotationCenter * this.uScale;
  31731. y -= this.vRotationCenter * this.vScale;
  31732. z -= this.wRotationCenter;
  31733. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31734. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31735. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31736. t.z += this.wRotationCenter;
  31737. };
  31738. /**
  31739. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  31740. * @returns the transform matrix of the texture.
  31741. */
  31742. Texture.prototype.getTextureMatrix = function () {
  31743. var _this = this;
  31744. if (this.uOffset === this._cachedUOffset &&
  31745. this.vOffset === this._cachedVOffset &&
  31746. this.uScale === this._cachedUScale &&
  31747. this.vScale === this._cachedVScale &&
  31748. this.uAng === this._cachedUAng &&
  31749. this.vAng === this._cachedVAng &&
  31750. this.wAng === this._cachedWAng) {
  31751. return this._cachedTextureMatrix;
  31752. }
  31753. this._cachedUOffset = this.uOffset;
  31754. this._cachedVOffset = this.vOffset;
  31755. this._cachedUScale = this.uScale;
  31756. this._cachedVScale = this.vScale;
  31757. this._cachedUAng = this.uAng;
  31758. this._cachedVAng = this.vAng;
  31759. this._cachedWAng = this.wAng;
  31760. if (!this._cachedTextureMatrix) {
  31761. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31762. this._rowGenerationMatrix = new BABYLON.Matrix();
  31763. this._t0 = BABYLON.Vector3.Zero();
  31764. this._t1 = BABYLON.Vector3.Zero();
  31765. this._t2 = BABYLON.Vector3.Zero();
  31766. }
  31767. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31768. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31769. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31770. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31771. this._t1.subtractInPlace(this._t0);
  31772. this._t2.subtractInPlace(this._t0);
  31773. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31774. this._cachedTextureMatrix.m[0] = this._t1.x;
  31775. this._cachedTextureMatrix.m[1] = this._t1.y;
  31776. this._cachedTextureMatrix.m[2] = this._t1.z;
  31777. this._cachedTextureMatrix.m[4] = this._t2.x;
  31778. this._cachedTextureMatrix.m[5] = this._t2.y;
  31779. this._cachedTextureMatrix.m[6] = this._t2.z;
  31780. this._cachedTextureMatrix.m[8] = this._t0.x;
  31781. this._cachedTextureMatrix.m[9] = this._t0.y;
  31782. this._cachedTextureMatrix.m[10] = this._t0.z;
  31783. var scene = this.getScene();
  31784. if (!scene) {
  31785. return this._cachedTextureMatrix;
  31786. }
  31787. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31788. return mat.hasTexture(_this);
  31789. });
  31790. return this._cachedTextureMatrix;
  31791. };
  31792. /**
  31793. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  31794. * @returns The reflection texture transform
  31795. */
  31796. Texture.prototype.getReflectionTextureMatrix = function () {
  31797. var _this = this;
  31798. var scene = this.getScene();
  31799. if (!scene) {
  31800. return this._cachedTextureMatrix;
  31801. }
  31802. if (this.uOffset === this._cachedUOffset &&
  31803. this.vOffset === this._cachedVOffset &&
  31804. this.uScale === this._cachedUScale &&
  31805. this.vScale === this._cachedVScale &&
  31806. this.coordinatesMode === this._cachedCoordinatesMode) {
  31807. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31808. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31809. return this._cachedTextureMatrix;
  31810. }
  31811. }
  31812. else {
  31813. return this._cachedTextureMatrix;
  31814. }
  31815. }
  31816. if (!this._cachedTextureMatrix) {
  31817. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31818. }
  31819. if (!this._projectionModeMatrix) {
  31820. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31821. }
  31822. this._cachedUOffset = this.uOffset;
  31823. this._cachedVOffset = this.vOffset;
  31824. this._cachedUScale = this.uScale;
  31825. this._cachedVScale = this.vScale;
  31826. this._cachedCoordinatesMode = this.coordinatesMode;
  31827. switch (this.coordinatesMode) {
  31828. case Texture.PLANAR_MODE:
  31829. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31830. this._cachedTextureMatrix[0] = this.uScale;
  31831. this._cachedTextureMatrix[5] = this.vScale;
  31832. this._cachedTextureMatrix[12] = this.uOffset;
  31833. this._cachedTextureMatrix[13] = this.vOffset;
  31834. break;
  31835. case Texture.PROJECTION_MODE:
  31836. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31837. this._projectionModeMatrix.m[0] = 0.5;
  31838. this._projectionModeMatrix.m[5] = -0.5;
  31839. this._projectionModeMatrix.m[10] = 0.0;
  31840. this._projectionModeMatrix.m[12] = 0.5;
  31841. this._projectionModeMatrix.m[13] = 0.5;
  31842. this._projectionModeMatrix.m[14] = 1.0;
  31843. this._projectionModeMatrix.m[15] = 1.0;
  31844. var projectionMatrix = scene.getProjectionMatrix();
  31845. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31846. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31847. break;
  31848. default:
  31849. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31850. break;
  31851. }
  31852. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31853. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31854. });
  31855. return this._cachedTextureMatrix;
  31856. };
  31857. /**
  31858. * Clones the texture.
  31859. * @returns the cloned texture
  31860. */
  31861. Texture.prototype.clone = function () {
  31862. var _this = this;
  31863. return BABYLON.SerializationHelper.Clone(function () {
  31864. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31865. }, this);
  31866. };
  31867. /**
  31868. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  31869. * @returns The JSON representation of the texture
  31870. */
  31871. Texture.prototype.serialize = function () {
  31872. var serializationObject = _super.prototype.serialize.call(this);
  31873. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31874. serializationObject.base64String = this._buffer;
  31875. serializationObject.name = serializationObject.name.replace("data:", "");
  31876. }
  31877. serializationObject.invertY = this._invertY;
  31878. serializationObject.samplingMode = this.samplingMode;
  31879. return serializationObject;
  31880. };
  31881. /**
  31882. * Get the current class name of the texture usefull for serialization or dynamic coding.
  31883. * @returns "Texture"
  31884. */
  31885. Texture.prototype.getClassName = function () {
  31886. return "Texture";
  31887. };
  31888. /**
  31889. * Dispose the texture and release its associated resources.
  31890. */
  31891. Texture.prototype.dispose = function () {
  31892. _super.prototype.dispose.call(this);
  31893. this.onLoadObservable.clear();
  31894. this._delayedOnLoad = null;
  31895. this._delayedOnError = null;
  31896. };
  31897. /**
  31898. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  31899. * @param parsedTexture Define the JSON representation of the texture
  31900. * @param scene Define the scene the parsed texture should be instantiated in
  31901. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  31902. * @returns The parsed texture if successful
  31903. */
  31904. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31905. if (parsedTexture.customType) {
  31906. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31907. // Update Sampling Mode
  31908. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31909. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31910. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31911. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31912. }
  31913. }
  31914. return parsedCustomTexture;
  31915. }
  31916. if (parsedTexture.isCube) {
  31917. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31918. }
  31919. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31920. return null;
  31921. }
  31922. var texture = BABYLON.SerializationHelper.Parse(function () {
  31923. var generateMipMaps = true;
  31924. if (parsedTexture.noMipmap) {
  31925. generateMipMaps = false;
  31926. }
  31927. if (parsedTexture.mirrorPlane) {
  31928. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31929. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31930. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31931. return mirrorTexture;
  31932. }
  31933. else if (parsedTexture.isRenderTarget) {
  31934. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31935. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31936. return renderTargetTexture;
  31937. }
  31938. else {
  31939. var texture;
  31940. if (parsedTexture.base64String) {
  31941. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31942. }
  31943. else {
  31944. var url = rootUrl + parsedTexture.name;
  31945. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31946. url = parsedTexture.url;
  31947. }
  31948. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31949. }
  31950. return texture;
  31951. }
  31952. }, parsedTexture, scene);
  31953. // Update Sampling Mode
  31954. if (parsedTexture.samplingMode) {
  31955. var sampling = parsedTexture.samplingMode;
  31956. if (texture._samplingMode !== sampling) {
  31957. texture.updateSamplingMode(sampling);
  31958. }
  31959. }
  31960. // Animations
  31961. if (parsedTexture.animations) {
  31962. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31963. var parsedAnimation = parsedTexture.animations[animationIndex];
  31964. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31965. }
  31966. }
  31967. return texture;
  31968. };
  31969. /**
  31970. * Creates a texture from its base 64 representation.
  31971. * @param data Define the base64 payload without the data: prefix
  31972. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  31973. * @param scene Define the scene the texture should belong to
  31974. * @param noMipmap Forces the texture to not create mip map information if true
  31975. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31976. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31977. * @param onLoad define a callback triggered when the texture has been loaded
  31978. * @param onError define a callback triggered when an error occurred during the loading session
  31979. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31980. * @returns the created texture
  31981. */
  31982. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31983. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31984. if (onLoad === void 0) { onLoad = null; }
  31985. if (onError === void 0) { onError = null; }
  31986. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31987. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31988. };
  31989. /**
  31990. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  31991. * @param data Define the base64 payload without the data: prefix
  31992. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  31993. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31994. * @param scene Define the scene the texture should belong to
  31995. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31996. * @param noMipmap Forces the texture to not create mip map information if true
  31997. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31998. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31999. * @param onLoad define a callback triggered when the texture has been loaded
  32000. * @param onError define a callback triggered when an error occurred during the loading session
  32001. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32002. * @returns the created texture
  32003. */
  32004. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32005. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32006. if (noMipmap === void 0) { noMipmap = false; }
  32007. if (invertY === void 0) { invertY = true; }
  32008. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32009. if (onLoad === void 0) { onLoad = null; }
  32010. if (onError === void 0) { onError = null; }
  32011. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32012. if (name.substr(0, 5) !== "data:") {
  32013. name = "data:" + name;
  32014. }
  32015. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32016. };
  32017. /** nearest is mag = nearest and min = nearest and mip = linear */
  32018. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32019. /** nearest is mag = nearest and min = nearest and mip = linear */
  32020. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32021. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32022. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32023. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32024. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32025. /** Trilinear is mag = linear and min = linear and mip = linear */
  32026. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32027. /** Trilinear is mag = linear and min = linear and mip = linear */
  32028. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32029. /** mag = nearest and min = nearest and mip = nearest */
  32030. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32031. /** mag = nearest and min = linear and mip = nearest */
  32032. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32033. /** mag = nearest and min = linear and mip = linear */
  32034. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32035. /** mag = nearest and min = linear and mip = none */
  32036. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32037. /** mag = nearest and min = nearest and mip = none */
  32038. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32039. /** mag = linear and min = nearest and mip = nearest */
  32040. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32041. /** mag = linear and min = nearest and mip = linear */
  32042. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32043. /** mag = linear and min = linear and mip = none */
  32044. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32045. /** mag = linear and min = nearest and mip = none */
  32046. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32047. /** Explicit coordinates mode */
  32048. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32049. /** Spherical coordinates mode */
  32050. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32051. /** Planar coordinates mode */
  32052. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32053. /** Cubic coordinates mode */
  32054. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32055. /** Projection coordinates mode */
  32056. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32057. /** Inverse Cubic coordinates mode */
  32058. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32059. /** Inverse Cubic coordinates mode */
  32060. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32061. /** Equirectangular coordinates mode */
  32062. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32063. /** Equirectangular Fixed coordinates mode */
  32064. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32065. /** Equirectangular Fixed Mirrored coordinates mode */
  32066. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32067. /** Texture is not repeating outside of 0..1 UVs */
  32068. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32069. /** Texture is repeating outside of 0..1 UVs */
  32070. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32071. /** Texture is repeating and mirrored */
  32072. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32073. /**
  32074. * 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
  32075. */
  32076. Texture.UseSerializedUrlIfAny = false;
  32077. __decorate([
  32078. BABYLON.serialize()
  32079. ], Texture.prototype, "url", void 0);
  32080. __decorate([
  32081. BABYLON.serialize()
  32082. ], Texture.prototype, "uOffset", void 0);
  32083. __decorate([
  32084. BABYLON.serialize()
  32085. ], Texture.prototype, "vOffset", void 0);
  32086. __decorate([
  32087. BABYLON.serialize()
  32088. ], Texture.prototype, "uScale", void 0);
  32089. __decorate([
  32090. BABYLON.serialize()
  32091. ], Texture.prototype, "vScale", void 0);
  32092. __decorate([
  32093. BABYLON.serialize()
  32094. ], Texture.prototype, "uAng", void 0);
  32095. __decorate([
  32096. BABYLON.serialize()
  32097. ], Texture.prototype, "vAng", void 0);
  32098. __decorate([
  32099. BABYLON.serialize()
  32100. ], Texture.prototype, "wAng", void 0);
  32101. __decorate([
  32102. BABYLON.serialize()
  32103. ], Texture.prototype, "uRotationCenter", void 0);
  32104. __decorate([
  32105. BABYLON.serialize()
  32106. ], Texture.prototype, "vRotationCenter", void 0);
  32107. __decorate([
  32108. BABYLON.serialize()
  32109. ], Texture.prototype, "wRotationCenter", void 0);
  32110. __decorate([
  32111. BABYLON.serialize()
  32112. ], Texture.prototype, "isBlocking", null);
  32113. return Texture;
  32114. }(BABYLON.BaseTexture));
  32115. BABYLON.Texture = Texture;
  32116. })(BABYLON || (BABYLON = {}));
  32117. //# sourceMappingURL=babylon.texture.js.map
  32118. var BABYLON;
  32119. (function (BABYLON) {
  32120. /**
  32121. * @hidden
  32122. **/
  32123. var _CreationDataStorage = /** @class */ (function () {
  32124. function _CreationDataStorage() {
  32125. }
  32126. return _CreationDataStorage;
  32127. }());
  32128. BABYLON._CreationDataStorage = _CreationDataStorage;
  32129. /**
  32130. * @hidden
  32131. **/
  32132. var _InstanceDataStorage = /** @class */ (function () {
  32133. function _InstanceDataStorage() {
  32134. this.visibleInstances = {};
  32135. this.renderIdForInstances = new Array();
  32136. this.batchCache = new _InstancesBatch();
  32137. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32138. }
  32139. return _InstanceDataStorage;
  32140. }());
  32141. /**
  32142. * @hidden
  32143. **/
  32144. var _InstancesBatch = /** @class */ (function () {
  32145. function _InstancesBatch() {
  32146. this.mustReturn = false;
  32147. this.visibleInstances = new Array();
  32148. this.renderSelf = new Array();
  32149. }
  32150. return _InstancesBatch;
  32151. }());
  32152. BABYLON._InstancesBatch = _InstancesBatch;
  32153. /**
  32154. * Class used to represent renderable models
  32155. */
  32156. var Mesh = /** @class */ (function (_super) {
  32157. __extends(Mesh, _super);
  32158. /**
  32159. * @constructor
  32160. * @param name The value used by scene.getMeshByName() to do a lookup.
  32161. * @param scene The scene to add this mesh to.
  32162. * @param parent The parent of this mesh, if it has one
  32163. * @param source An optional Mesh from which geometry is shared, cloned.
  32164. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32165. * When false, achieved by calling a clone(), also passing False.
  32166. * This will make creation of children, recursive.
  32167. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32168. */
  32169. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32170. if (scene === void 0) { scene = null; }
  32171. if (parent === void 0) { parent = null; }
  32172. if (source === void 0) { source = null; }
  32173. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32174. var _this = _super.call(this, name, scene) || this;
  32175. // Members
  32176. /**
  32177. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32178. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32179. */
  32180. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32181. /**
  32182. * Gets the list of instances created from this mesh
  32183. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32184. */
  32185. _this.instances = new Array();
  32186. _this._LODLevels = new Array();
  32187. /** @hidden */
  32188. _this._instanceDataStorage = new _InstanceDataStorage();
  32189. // Use by builder only to know what orientation were the mesh build in.
  32190. /** @hidden */
  32191. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32192. /**
  32193. * Use this property to change the original side orientation defined at construction time
  32194. */
  32195. _this.overrideMaterialSideOrientation = null;
  32196. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32197. // Will be used to save a source mesh reference, If any
  32198. _this._source = null;
  32199. scene = _this.getScene();
  32200. if (source) {
  32201. // Geometry
  32202. if (source._geometry) {
  32203. source._geometry.applyToMesh(_this);
  32204. }
  32205. // Deep copy
  32206. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32207. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32208. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32209. ], ["_poseMatrix"]);
  32210. // Source mesh
  32211. _this._source = source;
  32212. // Construction Params
  32213. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32214. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32215. _this._creationDataStorage = source._creationDataStorage;
  32216. // Animation ranges
  32217. if (_this._source._ranges) {
  32218. var ranges = _this._source._ranges;
  32219. for (var name in ranges) {
  32220. if (!ranges.hasOwnProperty(name)) {
  32221. continue;
  32222. }
  32223. if (!ranges[name]) {
  32224. continue;
  32225. }
  32226. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32227. }
  32228. }
  32229. // Metadata
  32230. if (source.metadata && source.metadata.clone) {
  32231. _this.metadata = source.metadata.clone();
  32232. }
  32233. else {
  32234. _this.metadata = source.metadata;
  32235. }
  32236. // Tags
  32237. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32238. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32239. }
  32240. // Parent
  32241. _this.parent = source.parent;
  32242. // Pivot
  32243. _this.setPivotMatrix(source.getPivotMatrix());
  32244. _this.id = name + "." + source.id;
  32245. // Material
  32246. _this.material = source.material;
  32247. var index;
  32248. if (!doNotCloneChildren) {
  32249. // Children
  32250. var directDescendants = source.getDescendants(true);
  32251. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32252. var child = directDescendants[index_1];
  32253. if (child.clone) {
  32254. child.clone(name + "." + child.name, _this);
  32255. }
  32256. }
  32257. }
  32258. // Physics clone
  32259. var physicsEngine = _this.getScene().getPhysicsEngine();
  32260. if (clonePhysicsImpostor && physicsEngine) {
  32261. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32262. if (impostor) {
  32263. _this.physicsImpostor = impostor.clone(_this);
  32264. }
  32265. }
  32266. // Particles
  32267. for (index = 0; index < scene.particleSystems.length; index++) {
  32268. var system = scene.particleSystems[index];
  32269. if (system.emitter === source) {
  32270. system.clone(system.name, _this);
  32271. }
  32272. }
  32273. _this.refreshBoundingInfo();
  32274. _this.computeWorldMatrix(true);
  32275. }
  32276. // Parent
  32277. if (parent !== null) {
  32278. _this.parent = parent;
  32279. }
  32280. return _this;
  32281. }
  32282. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32283. /**
  32284. * An event triggered before rendering the mesh
  32285. */
  32286. get: function () {
  32287. if (!this._onBeforeRenderObservable) {
  32288. this._onBeforeRenderObservable = new BABYLON.Observable();
  32289. }
  32290. return this._onBeforeRenderObservable;
  32291. },
  32292. enumerable: true,
  32293. configurable: true
  32294. });
  32295. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32296. /**
  32297. * An event triggered after rendering the mesh
  32298. */
  32299. get: function () {
  32300. if (!this._onAfterRenderObservable) {
  32301. this._onAfterRenderObservable = new BABYLON.Observable();
  32302. }
  32303. return this._onAfterRenderObservable;
  32304. },
  32305. enumerable: true,
  32306. configurable: true
  32307. });
  32308. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32309. /**
  32310. * An event triggered before drawing the mesh
  32311. */
  32312. get: function () {
  32313. if (!this._onBeforeDrawObservable) {
  32314. this._onBeforeDrawObservable = new BABYLON.Observable();
  32315. }
  32316. return this._onBeforeDrawObservable;
  32317. },
  32318. enumerable: true,
  32319. configurable: true
  32320. });
  32321. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32322. /**
  32323. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32324. */
  32325. set: function (callback) {
  32326. if (this._onBeforeDrawObserver) {
  32327. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32328. }
  32329. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32330. },
  32331. enumerable: true,
  32332. configurable: true
  32333. });
  32334. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32335. /**
  32336. * Gets or sets the morph target manager
  32337. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32338. */
  32339. get: function () {
  32340. return this._morphTargetManager;
  32341. },
  32342. set: function (value) {
  32343. if (this._morphTargetManager === value) {
  32344. return;
  32345. }
  32346. this._morphTargetManager = value;
  32347. this._syncGeometryWithMorphTargetManager();
  32348. },
  32349. enumerable: true,
  32350. configurable: true
  32351. });
  32352. Object.defineProperty(Mesh.prototype, "source", {
  32353. /**
  32354. * Gets the source mesh (the one used to clone this one from)
  32355. */
  32356. get: function () {
  32357. return this._source;
  32358. },
  32359. enumerable: true,
  32360. configurable: true
  32361. });
  32362. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32363. /**
  32364. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32365. */
  32366. get: function () {
  32367. return this._unIndexed;
  32368. },
  32369. set: function (value) {
  32370. if (this._unIndexed !== value) {
  32371. this._unIndexed = value;
  32372. this._markSubMeshesAsAttributesDirty();
  32373. }
  32374. },
  32375. enumerable: true,
  32376. configurable: true
  32377. });
  32378. // Methods
  32379. /**
  32380. * Gets the class name
  32381. * @returns the string "Mesh".
  32382. */
  32383. Mesh.prototype.getClassName = function () {
  32384. return "Mesh";
  32385. };
  32386. /**
  32387. * Returns a description of this mesh
  32388. * @param fullDetails define if full details about this mesh must be used
  32389. * @returns a descriptive string representing this mesh
  32390. */
  32391. Mesh.prototype.toString = function (fullDetails) {
  32392. var ret = _super.prototype.toString.call(this, fullDetails);
  32393. ret += ", n vertices: " + this.getTotalVertices();
  32394. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32395. if (this.animations) {
  32396. for (var i = 0; i < this.animations.length; i++) {
  32397. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32398. }
  32399. }
  32400. if (fullDetails) {
  32401. if (this._geometry) {
  32402. var ib = this.getIndices();
  32403. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32404. if (vb && ib) {
  32405. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32406. }
  32407. }
  32408. else {
  32409. ret += ", flat shading: UNKNOWN";
  32410. }
  32411. }
  32412. return ret;
  32413. };
  32414. /** @hidden */
  32415. Mesh.prototype._unBindEffect = function () {
  32416. _super.prototype._unBindEffect.call(this);
  32417. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32418. var instance = _a[_i];
  32419. instance._unBindEffect();
  32420. }
  32421. };
  32422. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32423. /**
  32424. * Gets a boolean indicating if this mesh has LOD
  32425. */
  32426. get: function () {
  32427. return this._LODLevels.length > 0;
  32428. },
  32429. enumerable: true,
  32430. configurable: true
  32431. });
  32432. /**
  32433. * Gets the list of MeshLODLevel associated with the current mesh
  32434. * @returns an array of MeshLODLevel
  32435. */
  32436. Mesh.prototype.getLODLevels = function () {
  32437. return this._LODLevels;
  32438. };
  32439. Mesh.prototype._sortLODLevels = function () {
  32440. this._LODLevels.sort(function (a, b) {
  32441. if (a.distance < b.distance) {
  32442. return 1;
  32443. }
  32444. if (a.distance > b.distance) {
  32445. return -1;
  32446. }
  32447. return 0;
  32448. });
  32449. };
  32450. /**
  32451. * Add a mesh as LOD level triggered at the given distance.
  32452. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32453. * @param distance The distance from the center of the object to show this level
  32454. * @param mesh The mesh to be added as LOD level (can be null)
  32455. * @return This mesh (for chaining)
  32456. */
  32457. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32458. if (mesh && mesh._masterMesh) {
  32459. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32460. return this;
  32461. }
  32462. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32463. this._LODLevels.push(level);
  32464. if (mesh) {
  32465. mesh._masterMesh = this;
  32466. }
  32467. this._sortLODLevels();
  32468. return this;
  32469. };
  32470. /**
  32471. * Returns the LOD level mesh at the passed distance or null if not found.
  32472. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32473. * @param distance The distance from the center of the object to show this level
  32474. * @returns a Mesh or `null`
  32475. */
  32476. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32477. for (var index = 0; index < this._LODLevels.length; index++) {
  32478. var level = this._LODLevels[index];
  32479. if (level.distance === distance) {
  32480. return level.mesh;
  32481. }
  32482. }
  32483. return null;
  32484. };
  32485. /**
  32486. * Remove a mesh from the LOD array
  32487. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32488. * @param mesh defines the mesh to be removed
  32489. * @return This mesh (for chaining)
  32490. */
  32491. Mesh.prototype.removeLODLevel = function (mesh) {
  32492. for (var index = 0; index < this._LODLevels.length; index++) {
  32493. if (this._LODLevels[index].mesh === mesh) {
  32494. this._LODLevels.splice(index, 1);
  32495. if (mesh) {
  32496. mesh._masterMesh = null;
  32497. }
  32498. }
  32499. }
  32500. this._sortLODLevels();
  32501. return this;
  32502. };
  32503. /**
  32504. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32505. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32506. * @param camera defines the camera to use to compute distance
  32507. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32508. * @return This mesh (for chaining)
  32509. */
  32510. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32511. if (!this._LODLevels || this._LODLevels.length === 0) {
  32512. return this;
  32513. }
  32514. var bSphere;
  32515. if (boundingSphere) {
  32516. bSphere = boundingSphere;
  32517. }
  32518. else {
  32519. var boundingInfo = this.getBoundingInfo();
  32520. bSphere = boundingInfo.boundingSphere;
  32521. }
  32522. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32523. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32524. if (this.onLODLevelSelection) {
  32525. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32526. }
  32527. return this;
  32528. }
  32529. for (var index = 0; index < this._LODLevels.length; index++) {
  32530. var level = this._LODLevels[index];
  32531. if (level.distance < distanceToCamera) {
  32532. if (level.mesh) {
  32533. level.mesh._preActivate();
  32534. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32535. }
  32536. if (this.onLODLevelSelection) {
  32537. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32538. }
  32539. return level.mesh;
  32540. }
  32541. }
  32542. if (this.onLODLevelSelection) {
  32543. this.onLODLevelSelection(distanceToCamera, this, this);
  32544. }
  32545. return this;
  32546. };
  32547. Object.defineProperty(Mesh.prototype, "geometry", {
  32548. /**
  32549. * Gets the mesh internal Geometry object
  32550. */
  32551. get: function () {
  32552. return this._geometry;
  32553. },
  32554. enumerable: true,
  32555. configurable: true
  32556. });
  32557. /**
  32558. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32559. * @returns the total number of vertices
  32560. */
  32561. Mesh.prototype.getTotalVertices = function () {
  32562. if (this._geometry === null || this._geometry === undefined) {
  32563. return 0;
  32564. }
  32565. return this._geometry.getTotalVertices();
  32566. };
  32567. /**
  32568. * Returns the content of an associated vertex buffer
  32569. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32570. * - BABYLON.VertexBuffer.PositionKind
  32571. * - BABYLON.VertexBuffer.UVKind
  32572. * - BABYLON.VertexBuffer.UV2Kind
  32573. * - BABYLON.VertexBuffer.UV3Kind
  32574. * - BABYLON.VertexBuffer.UV4Kind
  32575. * - BABYLON.VertexBuffer.UV5Kind
  32576. * - BABYLON.VertexBuffer.UV6Kind
  32577. * - BABYLON.VertexBuffer.ColorKind
  32578. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32579. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32580. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32581. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32582. * @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
  32583. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32584. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32585. */
  32586. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32587. if (!this._geometry) {
  32588. return null;
  32589. }
  32590. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32591. };
  32592. /**
  32593. * Returns the mesh VertexBuffer object from the requested `kind`
  32594. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32595. * - BABYLON.VertexBuffer.PositionKind
  32596. * - BABYLON.VertexBuffer.UVKind
  32597. * - BABYLON.VertexBuffer.UV2Kind
  32598. * - BABYLON.VertexBuffer.UV3Kind
  32599. * - BABYLON.VertexBuffer.UV4Kind
  32600. * - BABYLON.VertexBuffer.UV5Kind
  32601. * - BABYLON.VertexBuffer.UV6Kind
  32602. * - BABYLON.VertexBuffer.ColorKind
  32603. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32604. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32605. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32606. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32607. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32608. */
  32609. Mesh.prototype.getVertexBuffer = function (kind) {
  32610. if (!this._geometry) {
  32611. return null;
  32612. }
  32613. return this._geometry.getVertexBuffer(kind);
  32614. };
  32615. /**
  32616. * Tests if a specific vertex buffer is associated with this mesh
  32617. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32618. * - BABYLON.VertexBuffer.PositionKind
  32619. * - BABYLON.VertexBuffer.UVKind
  32620. * - BABYLON.VertexBuffer.UV2Kind
  32621. * - BABYLON.VertexBuffer.UV3Kind
  32622. * - BABYLON.VertexBuffer.UV4Kind
  32623. * - BABYLON.VertexBuffer.UV5Kind
  32624. * - BABYLON.VertexBuffer.UV6Kind
  32625. * - BABYLON.VertexBuffer.ColorKind
  32626. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32627. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32628. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32629. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32630. * @returns a boolean
  32631. */
  32632. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32633. if (!this._geometry) {
  32634. if (this._delayInfo) {
  32635. return this._delayInfo.indexOf(kind) !== -1;
  32636. }
  32637. return false;
  32638. }
  32639. return this._geometry.isVerticesDataPresent(kind);
  32640. };
  32641. /**
  32642. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32643. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32644. * - BABYLON.VertexBuffer.PositionKind
  32645. * - BABYLON.VertexBuffer.UVKind
  32646. * - BABYLON.VertexBuffer.UV2Kind
  32647. * - BABYLON.VertexBuffer.UV3Kind
  32648. * - BABYLON.VertexBuffer.UV4Kind
  32649. * - BABYLON.VertexBuffer.UV5Kind
  32650. * - BABYLON.VertexBuffer.UV6Kind
  32651. * - BABYLON.VertexBuffer.ColorKind
  32652. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32653. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32654. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32655. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32656. * @returns a boolean
  32657. */
  32658. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32659. if (!this._geometry) {
  32660. if (this._delayInfo) {
  32661. return this._delayInfo.indexOf(kind) !== -1;
  32662. }
  32663. return false;
  32664. }
  32665. return this._geometry.isVertexBufferUpdatable(kind);
  32666. };
  32667. /**
  32668. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32669. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32670. * - BABYLON.VertexBuffer.PositionKind
  32671. * - BABYLON.VertexBuffer.UVKind
  32672. * - BABYLON.VertexBuffer.UV2Kind
  32673. * - BABYLON.VertexBuffer.UV3Kind
  32674. * - BABYLON.VertexBuffer.UV4Kind
  32675. * - BABYLON.VertexBuffer.UV5Kind
  32676. * - BABYLON.VertexBuffer.UV6Kind
  32677. * - BABYLON.VertexBuffer.ColorKind
  32678. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32679. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32680. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32681. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32682. * @returns an array of strings
  32683. */
  32684. Mesh.prototype.getVerticesDataKinds = function () {
  32685. if (!this._geometry) {
  32686. var result = new Array();
  32687. if (this._delayInfo) {
  32688. this._delayInfo.forEach(function (kind, index, array) {
  32689. result.push(kind);
  32690. });
  32691. }
  32692. return result;
  32693. }
  32694. return this._geometry.getVerticesDataKinds();
  32695. };
  32696. /**
  32697. * Returns a positive integer : the total number of indices in this mesh geometry.
  32698. * @returns the numner of indices or zero if the mesh has no geometry.
  32699. */
  32700. Mesh.prototype.getTotalIndices = function () {
  32701. if (!this._geometry) {
  32702. return 0;
  32703. }
  32704. return this._geometry.getTotalIndices();
  32705. };
  32706. /**
  32707. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32708. * @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.
  32709. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32710. * @returns the indices array or an empty array if the mesh has no geometry
  32711. */
  32712. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32713. if (!this._geometry) {
  32714. return [];
  32715. }
  32716. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32717. };
  32718. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32719. get: function () {
  32720. return this._masterMesh !== null && this._masterMesh !== undefined;
  32721. },
  32722. enumerable: true,
  32723. configurable: true
  32724. });
  32725. /**
  32726. * Determine if the current mesh is ready to be rendered
  32727. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32728. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32729. * @returns true if all associated assets are ready (material, textures, shaders)
  32730. */
  32731. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32732. if (completeCheck === void 0) { completeCheck = false; }
  32733. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32734. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32735. return false;
  32736. }
  32737. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32738. return false;
  32739. }
  32740. if (!this.subMeshes || this.subMeshes.length === 0) {
  32741. return true;
  32742. }
  32743. if (!completeCheck) {
  32744. return true;
  32745. }
  32746. var engine = this.getEngine();
  32747. var scene = this.getScene();
  32748. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32749. this.computeWorldMatrix();
  32750. var mat = this.material || scene.defaultMaterial;
  32751. if (mat) {
  32752. if (mat.storeEffectOnSubMeshes) {
  32753. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32754. var subMesh = _a[_i];
  32755. var effectiveMaterial = subMesh.getMaterial();
  32756. if (effectiveMaterial) {
  32757. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32758. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32759. return false;
  32760. }
  32761. }
  32762. else {
  32763. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32764. return false;
  32765. }
  32766. }
  32767. }
  32768. }
  32769. }
  32770. else {
  32771. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32772. return false;
  32773. }
  32774. }
  32775. }
  32776. // Shadows
  32777. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32778. var light = _c[_b];
  32779. var generator = light.getShadowGenerator();
  32780. if (generator) {
  32781. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32782. var subMesh = _e[_d];
  32783. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32784. return false;
  32785. }
  32786. }
  32787. }
  32788. }
  32789. // LOD
  32790. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32791. var lod = _g[_f];
  32792. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32793. return false;
  32794. }
  32795. }
  32796. return true;
  32797. };
  32798. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32799. /**
  32800. * 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.
  32801. */
  32802. get: function () {
  32803. return this._areNormalsFrozen;
  32804. },
  32805. enumerable: true,
  32806. configurable: true
  32807. });
  32808. /**
  32809. * 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.
  32810. * @returns the current mesh
  32811. */
  32812. Mesh.prototype.freezeNormals = function () {
  32813. this._areNormalsFrozen = true;
  32814. return this;
  32815. };
  32816. /**
  32817. * 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
  32818. * @returns the current mesh
  32819. */
  32820. Mesh.prototype.unfreezeNormals = function () {
  32821. this._areNormalsFrozen = false;
  32822. return this;
  32823. };
  32824. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32825. /**
  32826. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32827. */
  32828. set: function (count) {
  32829. this._instanceDataStorage.overridenInstanceCount = count;
  32830. },
  32831. enumerable: true,
  32832. configurable: true
  32833. });
  32834. // Methods
  32835. /** @hidden */
  32836. Mesh.prototype._preActivate = function () {
  32837. var sceneRenderId = this.getScene().getRenderId();
  32838. if (this._preActivateId === sceneRenderId) {
  32839. return this;
  32840. }
  32841. this._preActivateId = sceneRenderId;
  32842. this._instanceDataStorage.visibleInstances = null;
  32843. return this;
  32844. };
  32845. /** @hidden */
  32846. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32847. if (this._instanceDataStorage.visibleInstances) {
  32848. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32849. }
  32850. return this;
  32851. };
  32852. /** @hidden */
  32853. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32854. if (!this._instanceDataStorage.visibleInstances) {
  32855. this._instanceDataStorage.visibleInstances = {};
  32856. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32857. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32858. }
  32859. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32860. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32861. }
  32862. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32863. return this;
  32864. };
  32865. /**
  32866. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32867. * This means the mesh underlying bounding box and sphere are recomputed.
  32868. * @returns the current mesh
  32869. */
  32870. Mesh.prototype.refreshBoundingInfo = function () {
  32871. return this._refreshBoundingInfo(false);
  32872. };
  32873. /** @hidden */
  32874. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32875. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32876. return this;
  32877. }
  32878. var data = this._getPositionData(applySkeleton);
  32879. if (data) {
  32880. var bias = this.geometry ? this.geometry.boundingBias : null;
  32881. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32882. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32883. }
  32884. if (this.subMeshes) {
  32885. for (var index = 0; index < this.subMeshes.length; index++) {
  32886. this.subMeshes[index].refreshBoundingInfo();
  32887. }
  32888. }
  32889. this._updateBoundingInfo();
  32890. return this;
  32891. };
  32892. Mesh.prototype._getPositionData = function (applySkeleton) {
  32893. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32894. if (data && applySkeleton && this.skeleton) {
  32895. data = BABYLON.Tools.Slice(data);
  32896. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32897. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32898. if (matricesWeightsData && matricesIndicesData) {
  32899. var needExtras = this.numBoneInfluencers > 4;
  32900. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32901. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32902. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32903. var tempVector = BABYLON.Tmp.Vector3[0];
  32904. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32905. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32906. var matWeightIdx = 0;
  32907. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32908. finalMatrix.reset();
  32909. var inf;
  32910. var weight;
  32911. for (inf = 0; inf < 4; inf++) {
  32912. weight = matricesWeightsData[matWeightIdx + inf];
  32913. if (weight > 0) {
  32914. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32915. finalMatrix.addToSelf(tempMatrix);
  32916. }
  32917. }
  32918. if (needExtras) {
  32919. for (inf = 0; inf < 4; inf++) {
  32920. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32921. if (weight > 0) {
  32922. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32923. finalMatrix.addToSelf(tempMatrix);
  32924. }
  32925. }
  32926. }
  32927. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32928. tempVector.toArray(data, index);
  32929. }
  32930. }
  32931. }
  32932. return data;
  32933. };
  32934. /** @hidden */
  32935. Mesh.prototype._createGlobalSubMesh = function (force) {
  32936. var totalVertices = this.getTotalVertices();
  32937. if (!totalVertices || !this.getIndices()) {
  32938. return null;
  32939. }
  32940. // Check if we need to recreate the submeshes
  32941. if (this.subMeshes && this.subMeshes.length > 0) {
  32942. var ib = this.getIndices();
  32943. if (!ib) {
  32944. return null;
  32945. }
  32946. var totalIndices = ib.length;
  32947. var needToRecreate = false;
  32948. if (force) {
  32949. needToRecreate = true;
  32950. }
  32951. else {
  32952. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32953. var submesh = _a[_i];
  32954. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32955. needToRecreate = true;
  32956. break;
  32957. }
  32958. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32959. needToRecreate = true;
  32960. break;
  32961. }
  32962. }
  32963. }
  32964. if (!needToRecreate) {
  32965. return this.subMeshes[0];
  32966. }
  32967. }
  32968. this.releaseSubMeshes();
  32969. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32970. };
  32971. /**
  32972. * This function will subdivide the mesh into multiple submeshes
  32973. * @param count defines the expected number of submeshes
  32974. */
  32975. Mesh.prototype.subdivide = function (count) {
  32976. if (count < 1) {
  32977. return;
  32978. }
  32979. var totalIndices = this.getTotalIndices();
  32980. var subdivisionSize = (totalIndices / count) | 0;
  32981. var offset = 0;
  32982. // Ensure that subdivisionSize is a multiple of 3
  32983. while (subdivisionSize % 3 !== 0) {
  32984. subdivisionSize++;
  32985. }
  32986. this.releaseSubMeshes();
  32987. for (var index = 0; index < count; index++) {
  32988. if (offset >= totalIndices) {
  32989. break;
  32990. }
  32991. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32992. offset += subdivisionSize;
  32993. }
  32994. this.synchronizeInstances();
  32995. };
  32996. /**
  32997. * Copy a FloatArray into a specific associated vertex buffer
  32998. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32999. * - BABYLON.VertexBuffer.PositionKind
  33000. * - BABYLON.VertexBuffer.UVKind
  33001. * - BABYLON.VertexBuffer.UV2Kind
  33002. * - BABYLON.VertexBuffer.UV3Kind
  33003. * - BABYLON.VertexBuffer.UV4Kind
  33004. * - BABYLON.VertexBuffer.UV5Kind
  33005. * - BABYLON.VertexBuffer.UV6Kind
  33006. * - BABYLON.VertexBuffer.ColorKind
  33007. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33008. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33009. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33010. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33011. * @param data defines the data source
  33012. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33013. * @param stride defines the data stride size (can be null)
  33014. * @returns the current mesh
  33015. */
  33016. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33017. if (updatable === void 0) { updatable = false; }
  33018. if (!this._geometry) {
  33019. var vertexData = new BABYLON.VertexData();
  33020. vertexData.set(data, kind);
  33021. var scene = this.getScene();
  33022. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33023. }
  33024. else {
  33025. this._geometry.setVerticesData(kind, data, updatable, stride);
  33026. }
  33027. return this;
  33028. };
  33029. /**
  33030. * Flags an associated vertex buffer as updatable
  33031. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33032. * - BABYLON.VertexBuffer.PositionKind
  33033. * - BABYLON.VertexBuffer.UVKind
  33034. * - BABYLON.VertexBuffer.UV2Kind
  33035. * - BABYLON.VertexBuffer.UV3Kind
  33036. * - BABYLON.VertexBuffer.UV4Kind
  33037. * - BABYLON.VertexBuffer.UV5Kind
  33038. * - BABYLON.VertexBuffer.UV6Kind
  33039. * - BABYLON.VertexBuffer.ColorKind
  33040. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33041. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33042. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33043. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33044. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33045. */
  33046. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33047. if (updatable === void 0) { updatable = true; }
  33048. var vb = this.getVertexBuffer(kind);
  33049. if (!vb || vb.isUpdatable() === updatable) {
  33050. return;
  33051. }
  33052. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33053. };
  33054. /**
  33055. * Sets the mesh global Vertex Buffer
  33056. * @param buffer defines the buffer to use
  33057. * @returns the current mesh
  33058. */
  33059. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33060. if (!this._geometry) {
  33061. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33062. }
  33063. this._geometry.setVerticesBuffer(buffer);
  33064. return this;
  33065. };
  33066. /**
  33067. * Update a specific associated vertex buffer
  33068. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33069. * - BABYLON.VertexBuffer.PositionKind
  33070. * - BABYLON.VertexBuffer.UVKind
  33071. * - BABYLON.VertexBuffer.UV2Kind
  33072. * - BABYLON.VertexBuffer.UV3Kind
  33073. * - BABYLON.VertexBuffer.UV4Kind
  33074. * - BABYLON.VertexBuffer.UV5Kind
  33075. * - BABYLON.VertexBuffer.UV6Kind
  33076. * - BABYLON.VertexBuffer.ColorKind
  33077. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33078. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33079. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33080. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33081. * @param data defines the data source
  33082. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33083. * @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)
  33084. * @returns the current mesh
  33085. */
  33086. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33087. if (!this._geometry) {
  33088. return this;
  33089. }
  33090. if (!makeItUnique) {
  33091. this._geometry.updateVerticesData(kind, data, updateExtends);
  33092. }
  33093. else {
  33094. this.makeGeometryUnique();
  33095. this.updateVerticesData(kind, data, updateExtends, false);
  33096. }
  33097. return this;
  33098. };
  33099. /**
  33100. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33101. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33102. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33103. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33104. * @returns the current mesh
  33105. */
  33106. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33107. if (computeNormals === void 0) { computeNormals = true; }
  33108. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33109. if (!positions) {
  33110. return this;
  33111. }
  33112. positionFunction(positions);
  33113. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33114. if (computeNormals) {
  33115. var indices = this.getIndices();
  33116. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33117. if (!normals) {
  33118. return this;
  33119. }
  33120. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33121. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33122. }
  33123. return this;
  33124. };
  33125. /**
  33126. * Creates a un-shared specific occurence of the geometry for the mesh.
  33127. * @returns the current mesh
  33128. */
  33129. Mesh.prototype.makeGeometryUnique = function () {
  33130. if (!this._geometry) {
  33131. return this;
  33132. }
  33133. var oldGeometry = this._geometry;
  33134. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33135. oldGeometry.releaseForMesh(this, true);
  33136. geometry.applyToMesh(this);
  33137. return this;
  33138. };
  33139. /**
  33140. * Set the index buffer of this mesh
  33141. * @param indices defines the source data
  33142. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33143. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33144. * @returns the current mesh
  33145. */
  33146. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33147. if (totalVertices === void 0) { totalVertices = null; }
  33148. if (updatable === void 0) { updatable = false; }
  33149. if (!this._geometry) {
  33150. var vertexData = new BABYLON.VertexData();
  33151. vertexData.indices = indices;
  33152. var scene = this.getScene();
  33153. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33154. }
  33155. else {
  33156. this._geometry.setIndices(indices, totalVertices, updatable);
  33157. }
  33158. return this;
  33159. };
  33160. /**
  33161. * Update the current index buffer
  33162. * @param indices defines the source data
  33163. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33164. * @returns the current mesh
  33165. */
  33166. Mesh.prototype.updateIndices = function (indices, offset) {
  33167. if (!this._geometry) {
  33168. return this;
  33169. }
  33170. this._geometry.updateIndices(indices, offset);
  33171. return this;
  33172. };
  33173. /**
  33174. * Invert the geometry to move from a right handed system to a left handed one.
  33175. * @returns the current mesh
  33176. */
  33177. Mesh.prototype.toLeftHanded = function () {
  33178. if (!this._geometry) {
  33179. return this;
  33180. }
  33181. this._geometry.toLeftHanded();
  33182. return this;
  33183. };
  33184. /** @hidden */
  33185. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33186. if (!this._geometry) {
  33187. return this;
  33188. }
  33189. var engine = this.getScene().getEngine();
  33190. // Wireframe
  33191. var indexToBind;
  33192. if (this._unIndexed) {
  33193. indexToBind = null;
  33194. }
  33195. else {
  33196. switch (fillMode) {
  33197. case BABYLON.Material.PointFillMode:
  33198. indexToBind = null;
  33199. break;
  33200. case BABYLON.Material.WireFrameFillMode:
  33201. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33202. break;
  33203. default:
  33204. case BABYLON.Material.TriangleFillMode:
  33205. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33206. break;
  33207. }
  33208. }
  33209. // VBOs
  33210. this._geometry._bind(effect, indexToBind);
  33211. return this;
  33212. };
  33213. /** @hidden */
  33214. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33215. if (alternate === void 0) { alternate = false; }
  33216. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33217. return this;
  33218. }
  33219. if (this._onBeforeDrawObservable) {
  33220. this._onBeforeDrawObservable.notifyObservers(this);
  33221. }
  33222. var scene = this.getScene();
  33223. var engine = scene.getEngine();
  33224. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33225. // or triangles as points
  33226. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33227. }
  33228. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33229. // Triangles as wireframe
  33230. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33231. }
  33232. else {
  33233. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33234. }
  33235. if (scene._isAlternateRenderingEnabled && !alternate) {
  33236. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33237. if (!effect || !scene.activeCamera) {
  33238. return this;
  33239. }
  33240. scene._switchToAlternateCameraConfiguration(true);
  33241. this._effectiveMaterial.bindView(effect);
  33242. this._effectiveMaterial.bindViewProjection(effect);
  33243. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33244. this._draw(subMesh, fillMode, instancesCount, true);
  33245. engine.setViewport(scene.activeCamera.viewport);
  33246. scene._switchToAlternateCameraConfiguration(false);
  33247. this._effectiveMaterial.bindView(effect);
  33248. this._effectiveMaterial.bindViewProjection(effect);
  33249. }
  33250. return this;
  33251. };
  33252. /**
  33253. * Registers for this mesh a javascript function called just before the rendering process
  33254. * @param func defines the function to call before rendering this mesh
  33255. * @returns the current mesh
  33256. */
  33257. Mesh.prototype.registerBeforeRender = function (func) {
  33258. this.onBeforeRenderObservable.add(func);
  33259. return this;
  33260. };
  33261. /**
  33262. * Disposes a previously registered javascript function called before the rendering
  33263. * @param func defines the function to remove
  33264. * @returns the current mesh
  33265. */
  33266. Mesh.prototype.unregisterBeforeRender = function (func) {
  33267. this.onBeforeRenderObservable.removeCallback(func);
  33268. return this;
  33269. };
  33270. /**
  33271. * Registers for this mesh a javascript function called just after the rendering is complete
  33272. * @param func defines the function to call after rendering this mesh
  33273. * @returns the current mesh
  33274. */
  33275. Mesh.prototype.registerAfterRender = function (func) {
  33276. this.onAfterRenderObservable.add(func);
  33277. return this;
  33278. };
  33279. /**
  33280. * Disposes a previously registered javascript function called after the rendering.
  33281. * @param func defines the function to remove
  33282. * @returns the current mesh
  33283. */
  33284. Mesh.prototype.unregisterAfterRender = function (func) {
  33285. this.onAfterRenderObservable.removeCallback(func);
  33286. return this;
  33287. };
  33288. /** @hidden */
  33289. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33290. var scene = this.getScene();
  33291. var batchCache = this._instanceDataStorage.batchCache;
  33292. batchCache.mustReturn = false;
  33293. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33294. batchCache.visibleInstances[subMeshId] = null;
  33295. if (this._instanceDataStorage.visibleInstances) {
  33296. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33297. var currentRenderId = scene.getRenderId();
  33298. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33299. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33300. var selfRenderId = this._renderId;
  33301. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33302. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33303. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33304. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33305. }
  33306. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33307. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33308. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33309. batchCache.mustReturn = true;
  33310. return batchCache;
  33311. }
  33312. if (currentRenderId !== selfRenderId) {
  33313. batchCache.renderSelf[subMeshId] = false;
  33314. }
  33315. }
  33316. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33317. }
  33318. return batchCache;
  33319. };
  33320. /** @hidden */
  33321. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33322. var visibleInstances = batch.visibleInstances[subMesh._id];
  33323. if (!visibleInstances) {
  33324. return this;
  33325. }
  33326. var matricesCount = visibleInstances.length + 1;
  33327. var bufferSize = matricesCount * 16 * 4;
  33328. var instanceStorage = this._instanceDataStorage;
  33329. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33330. var instancesBuffer = instanceStorage.instancesBuffer;
  33331. while (instanceStorage.instancesBufferSize < bufferSize) {
  33332. instanceStorage.instancesBufferSize *= 2;
  33333. }
  33334. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33335. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33336. }
  33337. var offset = 0;
  33338. var instancesCount = 0;
  33339. var world = this.getWorldMatrix();
  33340. if (batch.renderSelf[subMesh._id]) {
  33341. world.copyToArray(instanceStorage.instancesData, offset);
  33342. offset += 16;
  33343. instancesCount++;
  33344. }
  33345. if (visibleInstances) {
  33346. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33347. var instance = visibleInstances[instanceIndex];
  33348. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33349. offset += 16;
  33350. instancesCount++;
  33351. }
  33352. }
  33353. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33354. if (instancesBuffer) {
  33355. instancesBuffer.dispose();
  33356. }
  33357. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33358. instanceStorage.instancesBuffer = instancesBuffer;
  33359. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33360. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33361. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33362. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33363. }
  33364. else {
  33365. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33366. }
  33367. this._bind(subMesh, effect, fillMode);
  33368. this._draw(subMesh, fillMode, instancesCount);
  33369. engine.unbindInstanceAttributes();
  33370. return this;
  33371. };
  33372. /** @hidden */
  33373. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33374. var scene = this.getScene();
  33375. var engine = scene.getEngine();
  33376. if (hardwareInstancedRendering) {
  33377. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33378. }
  33379. else {
  33380. if (batch.renderSelf[subMesh._id]) {
  33381. // Draw
  33382. if (onBeforeDraw) {
  33383. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33384. }
  33385. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33386. }
  33387. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33388. if (visibleInstancesForSubMesh) {
  33389. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33390. var instance = visibleInstancesForSubMesh[instanceIndex];
  33391. // World
  33392. var world = instance.getWorldMatrix();
  33393. if (onBeforeDraw) {
  33394. onBeforeDraw(true, world, effectiveMaterial);
  33395. }
  33396. // Draw
  33397. this._draw(subMesh, fillMode);
  33398. }
  33399. }
  33400. }
  33401. return this;
  33402. };
  33403. /**
  33404. * 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
  33405. * @param subMesh defines the subMesh to render
  33406. * @param enableAlphaMode defines if alpha mode can be changed
  33407. * @returns the current mesh
  33408. */
  33409. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33410. if (this._checkOcclusionQuery()) {
  33411. return this;
  33412. }
  33413. var scene = this.getScene();
  33414. // Managing instances
  33415. var batch = this._getInstancesRenderList(subMesh._id);
  33416. if (batch.mustReturn) {
  33417. return this;
  33418. }
  33419. // Checking geometry state
  33420. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33421. return this;
  33422. }
  33423. if (this._onBeforeRenderObservable) {
  33424. this._onBeforeRenderObservable.notifyObservers(this);
  33425. }
  33426. var engine = scene.getEngine();
  33427. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33428. // Material
  33429. var material = subMesh.getMaterial();
  33430. if (!material) {
  33431. return this;
  33432. }
  33433. this._effectiveMaterial = material;
  33434. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33435. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33436. return this;
  33437. }
  33438. }
  33439. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33440. return this;
  33441. }
  33442. // Alpha mode
  33443. if (enableAlphaMode) {
  33444. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33445. }
  33446. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33447. var step = _a[_i];
  33448. step.action(this, subMesh, batch);
  33449. }
  33450. var effect;
  33451. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33452. effect = subMesh.effect;
  33453. }
  33454. else {
  33455. effect = this._effectiveMaterial.getEffect();
  33456. }
  33457. if (!effect) {
  33458. return this;
  33459. }
  33460. var sideOrientation = this.overrideMaterialSideOrientation;
  33461. if (sideOrientation == null) {
  33462. sideOrientation = this._effectiveMaterial.sideOrientation;
  33463. if (this._getWorldMatrixDeterminant() < 0) {
  33464. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33465. }
  33466. }
  33467. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33468. if (this._effectiveMaterial.forceDepthWrite) {
  33469. engine.setDepthWrite(true);
  33470. }
  33471. // Bind
  33472. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33473. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33474. this._bind(subMesh, effect, fillMode);
  33475. }
  33476. var world = this.getWorldMatrix();
  33477. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33478. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33479. }
  33480. else {
  33481. this._effectiveMaterial.bind(world, this);
  33482. }
  33483. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33484. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33485. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33486. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33487. }
  33488. // Draw
  33489. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33490. // Unbind
  33491. this._effectiveMaterial.unbind();
  33492. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33493. var step = _c[_b];
  33494. step.action(this, subMesh, batch);
  33495. }
  33496. if (this._onAfterRenderObservable) {
  33497. this._onAfterRenderObservable.notifyObservers(this);
  33498. }
  33499. return this;
  33500. };
  33501. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33502. if (isInstance && effectiveMaterial) {
  33503. effectiveMaterial.bindOnlyWorldMatrix(world);
  33504. }
  33505. };
  33506. /**
  33507. * Renormalize the mesh and patch it up if there are no weights
  33508. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33509. * However in the case of zero weights then we set just a single influence to 1.
  33510. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33511. */
  33512. Mesh.prototype.cleanMatrixWeights = function () {
  33513. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33514. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33515. this.normalizeSkinWeightsAndExtra();
  33516. }
  33517. else {
  33518. this.normalizeSkinFourWeights();
  33519. }
  33520. }
  33521. };
  33522. // faster 4 weight version.
  33523. Mesh.prototype.normalizeSkinFourWeights = function () {
  33524. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33525. var numWeights = matricesWeights.length;
  33526. for (var a = 0; a < numWeights; a += 4) {
  33527. // accumulate weights
  33528. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33529. // check for invalid weight and just set it to 1.
  33530. if (t === 0) {
  33531. matricesWeights[a] = 1;
  33532. }
  33533. else {
  33534. // renormalize so everything adds to 1 use reciprical
  33535. var recip = 1 / t;
  33536. matricesWeights[a] *= recip;
  33537. matricesWeights[a + 1] *= recip;
  33538. matricesWeights[a + 2] *= recip;
  33539. matricesWeights[a + 3] *= recip;
  33540. }
  33541. }
  33542. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33543. };
  33544. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33545. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33546. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33547. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33548. var numWeights = matricesWeights.length;
  33549. for (var a = 0; a < numWeights; a += 4) {
  33550. // accumulate weights
  33551. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33552. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33553. // check for invalid weight and just set it to 1.
  33554. if (t === 0) {
  33555. matricesWeights[a] = 1;
  33556. }
  33557. else {
  33558. // renormalize so everything adds to 1 use reciprical
  33559. var recip = 1 / t;
  33560. matricesWeights[a] *= recip;
  33561. matricesWeights[a + 1] *= recip;
  33562. matricesWeights[a + 2] *= recip;
  33563. matricesWeights[a + 3] *= recip;
  33564. // same goes for extras
  33565. matricesWeightsExtra[a] *= recip;
  33566. matricesWeightsExtra[a + 1] *= recip;
  33567. matricesWeightsExtra[a + 2] *= recip;
  33568. matricesWeightsExtra[a + 3] *= recip;
  33569. }
  33570. }
  33571. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33572. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33573. };
  33574. /**
  33575. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33576. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33577. * the user know there was an issue with importing the mesh
  33578. * @returns a validation object with skinned, valid and report string
  33579. */
  33580. Mesh.prototype.validateSkinning = function () {
  33581. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33582. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33583. if (matricesWeights === null || this.skeleton == null) {
  33584. return { skinned: false, valid: true, report: "not skinned" };
  33585. }
  33586. var numWeights = matricesWeights.length;
  33587. var numberNotSorted = 0;
  33588. var missingWeights = 0;
  33589. var maxUsedWeights = 0;
  33590. var numberNotNormalized = 0;
  33591. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33592. var usedWeightCounts = new Array();
  33593. for (var a = 0; a <= numInfluences; a++) {
  33594. usedWeightCounts[a] = 0;
  33595. }
  33596. var toleranceEpsilon = 0.001;
  33597. for (var a = 0; a < numWeights; a += 4) {
  33598. var lastWeight = matricesWeights[a];
  33599. var t = lastWeight;
  33600. var usedWeights = t === 0 ? 0 : 1;
  33601. for (var b = 1; b < numInfluences; b++) {
  33602. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33603. if (d > lastWeight) {
  33604. numberNotSorted++;
  33605. }
  33606. if (d !== 0) {
  33607. usedWeights++;
  33608. }
  33609. t += d;
  33610. lastWeight = d;
  33611. }
  33612. // count the buffer weights usage
  33613. usedWeightCounts[usedWeights]++;
  33614. // max influences
  33615. if (usedWeights > maxUsedWeights) {
  33616. maxUsedWeights = usedWeights;
  33617. }
  33618. // check for invalid weight and just set it to 1.
  33619. if (t === 0) {
  33620. missingWeights++;
  33621. }
  33622. else {
  33623. // renormalize so everything adds to 1 use reciprical
  33624. var recip = 1 / t;
  33625. var tolerance = 0;
  33626. for (b = 0; b < numInfluences; b++) {
  33627. if (b < 4) {
  33628. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33629. }
  33630. else {
  33631. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33632. }
  33633. }
  33634. // arbitary epsilon value for dicdating not normalized
  33635. if (tolerance > toleranceEpsilon) {
  33636. numberNotNormalized++;
  33637. }
  33638. }
  33639. }
  33640. // validate bone indices are in range of the skeleton
  33641. var numBones = this.skeleton.bones.length;
  33642. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33643. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33644. var numBadBoneIndices = 0;
  33645. for (var a = 0; a < numWeights; a++) {
  33646. for (var b = 0; b < numInfluences; b++) {
  33647. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33648. if (index >= numBones || index < 0) {
  33649. numBadBoneIndices++;
  33650. }
  33651. }
  33652. }
  33653. // log mesh stats
  33654. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33655. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33656. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33657. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33658. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33659. };
  33660. /** @hidden */
  33661. Mesh.prototype._checkDelayState = function () {
  33662. var scene = this.getScene();
  33663. if (this._geometry) {
  33664. this._geometry.load(scene);
  33665. }
  33666. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33667. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33668. this._queueLoad(scene);
  33669. }
  33670. return this;
  33671. };
  33672. Mesh.prototype._queueLoad = function (scene) {
  33673. var _this = this;
  33674. scene._addPendingData(this);
  33675. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33676. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33677. if (data instanceof ArrayBuffer) {
  33678. _this._delayLoadingFunction(data, _this);
  33679. }
  33680. else {
  33681. _this._delayLoadingFunction(JSON.parse(data), _this);
  33682. }
  33683. _this.instances.forEach(function (instance) {
  33684. instance._syncSubMeshes();
  33685. });
  33686. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33687. scene._removePendingData(_this);
  33688. }, function () { }, scene.database, getBinaryData);
  33689. return this;
  33690. };
  33691. /**
  33692. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33693. * A mesh is in the frustum if its bounding box intersects the frustum
  33694. * @param frustumPlanes defines the frustum to test
  33695. * @returns true if the mesh is in the frustum planes
  33696. */
  33697. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33698. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33699. return false;
  33700. }
  33701. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33702. return false;
  33703. }
  33704. this._checkDelayState();
  33705. return true;
  33706. };
  33707. /**
  33708. * Sets the mesh material by the material or multiMaterial `id` property
  33709. * @param id is a string identifying the material or the multiMaterial
  33710. * @returns the current mesh
  33711. */
  33712. Mesh.prototype.setMaterialByID = function (id) {
  33713. var materials = this.getScene().materials;
  33714. var index;
  33715. for (index = materials.length - 1; index > -1; index--) {
  33716. if (materials[index].id === id) {
  33717. this.material = materials[index];
  33718. return this;
  33719. }
  33720. }
  33721. // Multi
  33722. var multiMaterials = this.getScene().multiMaterials;
  33723. for (index = multiMaterials.length - 1; index > -1; index--) {
  33724. if (multiMaterials[index].id === id) {
  33725. this.material = multiMaterials[index];
  33726. return this;
  33727. }
  33728. }
  33729. return this;
  33730. };
  33731. /**
  33732. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33733. * @returns an array of IAnimatable
  33734. */
  33735. Mesh.prototype.getAnimatables = function () {
  33736. var results = new Array();
  33737. if (this.material) {
  33738. results.push(this.material);
  33739. }
  33740. if (this.skeleton) {
  33741. results.push(this.skeleton);
  33742. }
  33743. return results;
  33744. };
  33745. /**
  33746. * Modifies the mesh geometry according to the passed transformation matrix.
  33747. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33748. * The mesh normals are modified using the same transformation.
  33749. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33750. * @param transform defines the transform matrix to use
  33751. * @see http://doc.babylonjs.com/resources/baking_transformations
  33752. * @returns the current mesh
  33753. */
  33754. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33755. // Position
  33756. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33757. return this;
  33758. }
  33759. var submeshes = this.subMeshes.splice(0);
  33760. this._resetPointsArrayCache();
  33761. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33762. var temp = new Array();
  33763. var index;
  33764. for (index = 0; index < data.length; index += 3) {
  33765. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33766. }
  33767. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33768. // Normals
  33769. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33770. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33771. temp = [];
  33772. for (index = 0; index < data.length; index += 3) {
  33773. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33774. }
  33775. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33776. }
  33777. // flip faces?
  33778. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33779. this.flipFaces();
  33780. }
  33781. // Restore submeshes
  33782. this.releaseSubMeshes();
  33783. this.subMeshes = submeshes;
  33784. return this;
  33785. };
  33786. /**
  33787. * Modifies the mesh geometry according to its own current World Matrix.
  33788. * The mesh World Matrix is then reset.
  33789. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33790. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33791. * @see http://doc.babylonjs.com/resources/baking_transformations
  33792. * @returns the current mesh
  33793. */
  33794. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33795. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33796. this.scaling.copyFromFloats(1, 1, 1);
  33797. this.position.copyFromFloats(0, 0, 0);
  33798. this.rotation.copyFromFloats(0, 0, 0);
  33799. //only if quaternion is already set
  33800. if (this.rotationQuaternion) {
  33801. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33802. }
  33803. this._worldMatrix = BABYLON.Matrix.Identity();
  33804. return this;
  33805. };
  33806. Object.defineProperty(Mesh.prototype, "_positions", {
  33807. // Cache
  33808. /** @hidden */
  33809. get: function () {
  33810. if (this._geometry) {
  33811. return this._geometry._positions;
  33812. }
  33813. return null;
  33814. },
  33815. enumerable: true,
  33816. configurable: true
  33817. });
  33818. /** @hidden */
  33819. Mesh.prototype._resetPointsArrayCache = function () {
  33820. if (this._geometry) {
  33821. this._geometry._resetPointsArrayCache();
  33822. }
  33823. return this;
  33824. };
  33825. /** @hidden */
  33826. Mesh.prototype._generatePointsArray = function () {
  33827. if (this._geometry) {
  33828. return this._geometry._generatePointsArray();
  33829. }
  33830. return false;
  33831. };
  33832. /**
  33833. * Returns a new Mesh object generated from the current mesh properties.
  33834. * This method must not get confused with createInstance()
  33835. * @param name is a string, the name given to the new mesh
  33836. * @param newParent can be any Node object (default `null`)
  33837. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33838. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33839. * @returns a new mesh
  33840. */
  33841. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33842. if (name === void 0) { name = ""; }
  33843. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33844. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33845. };
  33846. /**
  33847. * Releases resources associated with this mesh.
  33848. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33849. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33850. */
  33851. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33852. var _this = this;
  33853. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33854. this.morphTargetManager = null;
  33855. if (this._geometry) {
  33856. this._geometry.releaseForMesh(this, true);
  33857. }
  33858. if (this._onBeforeDrawObservable) {
  33859. this._onBeforeDrawObservable.clear();
  33860. }
  33861. if (this._onBeforeRenderObservable) {
  33862. this._onBeforeRenderObservable.clear();
  33863. }
  33864. if (this._onAfterRenderObservable) {
  33865. this._onAfterRenderObservable.clear();
  33866. }
  33867. // Sources
  33868. var meshes = this.getScene().meshes;
  33869. meshes.forEach(function (abstractMesh) {
  33870. var mesh = abstractMesh;
  33871. if (mesh._source && mesh._source === _this) {
  33872. mesh._source = null;
  33873. }
  33874. });
  33875. this._source = null;
  33876. // Instances
  33877. if (this._instanceDataStorage.instancesBuffer) {
  33878. this._instanceDataStorage.instancesBuffer.dispose();
  33879. this._instanceDataStorage.instancesBuffer = null;
  33880. }
  33881. while (this.instances.length) {
  33882. this.instances[0].dispose();
  33883. }
  33884. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33885. };
  33886. /**
  33887. * Modifies the mesh geometry according to a displacement map.
  33888. * 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.
  33889. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33890. * @param url is a string, the URL from the image file is to be downloaded.
  33891. * @param minHeight is the lower limit of the displacement.
  33892. * @param maxHeight is the upper limit of the displacement.
  33893. * @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.
  33894. * @param uvOffset is an optional vector2 used to offset UV.
  33895. * @param uvScale is an optional vector2 used to scale UV.
  33896. * @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.
  33897. * @returns the Mesh.
  33898. */
  33899. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33900. var _this = this;
  33901. if (forceUpdate === void 0) { forceUpdate = false; }
  33902. var scene = this.getScene();
  33903. var onload = function (img) {
  33904. // Getting height map data
  33905. var canvas = document.createElement("canvas");
  33906. var context = canvas.getContext("2d");
  33907. var heightMapWidth = img.width;
  33908. var heightMapHeight = img.height;
  33909. canvas.width = heightMapWidth;
  33910. canvas.height = heightMapHeight;
  33911. context.drawImage(img, 0, 0);
  33912. // Create VertexData from map data
  33913. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33914. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33915. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33916. //execute success callback, if set
  33917. if (onSuccess) {
  33918. onSuccess(_this);
  33919. }
  33920. };
  33921. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33922. return this;
  33923. };
  33924. /**
  33925. * Modifies the mesh geometry according to a displacementMap buffer.
  33926. * 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.
  33927. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33928. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33929. * @param heightMapWidth is the width of the buffer image.
  33930. * @param heightMapHeight is the height of the buffer image.
  33931. * @param minHeight is the lower limit of the displacement.
  33932. * @param maxHeight is the upper limit of the displacement.
  33933. * @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.
  33934. * @param uvOffset is an optional vector2 used to offset UV.
  33935. * @param uvScale is an optional vector2 used to scale UV.
  33936. * @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.
  33937. * @returns the Mesh.
  33938. */
  33939. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33940. if (forceUpdate === void 0) { forceUpdate = false; }
  33941. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33942. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33943. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33944. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33945. return this;
  33946. }
  33947. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33948. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33949. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33950. var position = BABYLON.Vector3.Zero();
  33951. var normal = BABYLON.Vector3.Zero();
  33952. var uv = BABYLON.Vector2.Zero();
  33953. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33954. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33955. for (var index = 0; index < positions.length; index += 3) {
  33956. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33957. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33958. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33959. // Compute height
  33960. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33961. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33962. var pos = (u + v * heightMapWidth) * 4;
  33963. var r = buffer[pos] / 255.0;
  33964. var g = buffer[pos + 1] / 255.0;
  33965. var b = buffer[pos + 2] / 255.0;
  33966. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33967. normal.normalize();
  33968. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33969. position = position.add(normal);
  33970. position.toArray(positions, index);
  33971. }
  33972. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33973. if (forceUpdate) {
  33974. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33975. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33976. }
  33977. else {
  33978. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33979. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33980. }
  33981. return this;
  33982. };
  33983. /**
  33984. * Modify the mesh to get a flat shading rendering.
  33985. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33986. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33987. * @returns current mesh
  33988. */
  33989. Mesh.prototype.convertToFlatShadedMesh = function () {
  33990. var kinds = this.getVerticesDataKinds();
  33991. var vbs = {};
  33992. var data = {};
  33993. var newdata = {};
  33994. var updatableNormals = false;
  33995. var kindIndex;
  33996. var kind;
  33997. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33998. kind = kinds[kindIndex];
  33999. var vertexBuffer = this.getVertexBuffer(kind);
  34000. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34001. updatableNormals = vertexBuffer.isUpdatable();
  34002. kinds.splice(kindIndex, 1);
  34003. kindIndex--;
  34004. continue;
  34005. }
  34006. vbs[kind] = vertexBuffer;
  34007. data[kind] = vbs[kind].getData();
  34008. newdata[kind] = [];
  34009. }
  34010. // Save previous submeshes
  34011. var previousSubmeshes = this.subMeshes.slice(0);
  34012. var indices = this.getIndices();
  34013. var totalIndices = this.getTotalIndices();
  34014. // Generating unique vertices per face
  34015. var index;
  34016. for (index = 0; index < totalIndices; index++) {
  34017. var vertexIndex = indices[index];
  34018. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34019. kind = kinds[kindIndex];
  34020. var stride = vbs[kind].getStrideSize();
  34021. for (var offset = 0; offset < stride; offset++) {
  34022. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34023. }
  34024. }
  34025. }
  34026. // Updating faces & normal
  34027. var normals = [];
  34028. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34029. for (index = 0; index < totalIndices; index += 3) {
  34030. indices[index] = index;
  34031. indices[index + 1] = index + 1;
  34032. indices[index + 2] = index + 2;
  34033. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34034. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34035. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34036. var p1p2 = p1.subtract(p2);
  34037. var p3p2 = p3.subtract(p2);
  34038. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34039. // Store same normals for every vertex
  34040. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34041. normals.push(normal.x);
  34042. normals.push(normal.y);
  34043. normals.push(normal.z);
  34044. }
  34045. }
  34046. this.setIndices(indices);
  34047. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34048. // Updating vertex buffers
  34049. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34050. kind = kinds[kindIndex];
  34051. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34052. }
  34053. // Updating submeshes
  34054. this.releaseSubMeshes();
  34055. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34056. var previousOne = previousSubmeshes[submeshIndex];
  34057. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34058. }
  34059. this.synchronizeInstances();
  34060. return this;
  34061. };
  34062. /**
  34063. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34064. * In other words, more vertices, no more indices and a single bigger VBO.
  34065. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34066. * @returns current mesh
  34067. */
  34068. Mesh.prototype.convertToUnIndexedMesh = function () {
  34069. var kinds = this.getVerticesDataKinds();
  34070. var vbs = {};
  34071. var data = {};
  34072. var newdata = {};
  34073. var kindIndex;
  34074. var kind;
  34075. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34076. kind = kinds[kindIndex];
  34077. var vertexBuffer = this.getVertexBuffer(kind);
  34078. vbs[kind] = vertexBuffer;
  34079. data[kind] = vbs[kind].getData();
  34080. newdata[kind] = [];
  34081. }
  34082. // Save previous submeshes
  34083. var previousSubmeshes = this.subMeshes.slice(0);
  34084. var indices = this.getIndices();
  34085. var totalIndices = this.getTotalIndices();
  34086. // Generating unique vertices per face
  34087. var index;
  34088. for (index = 0; index < totalIndices; index++) {
  34089. var vertexIndex = indices[index];
  34090. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34091. kind = kinds[kindIndex];
  34092. var stride = vbs[kind].getStrideSize();
  34093. for (var offset = 0; offset < stride; offset++) {
  34094. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34095. }
  34096. }
  34097. }
  34098. // Updating indices
  34099. for (index = 0; index < totalIndices; index += 3) {
  34100. indices[index] = index;
  34101. indices[index + 1] = index + 1;
  34102. indices[index + 2] = index + 2;
  34103. }
  34104. this.setIndices(indices);
  34105. // Updating vertex buffers
  34106. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34107. kind = kinds[kindIndex];
  34108. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34109. }
  34110. // Updating submeshes
  34111. this.releaseSubMeshes();
  34112. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34113. var previousOne = previousSubmeshes[submeshIndex];
  34114. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34115. }
  34116. this._unIndexed = true;
  34117. this.synchronizeInstances();
  34118. return this;
  34119. };
  34120. /**
  34121. * Inverses facet orientations.
  34122. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34123. * @param flipNormals will also inverts the normals
  34124. * @returns current mesh
  34125. */
  34126. Mesh.prototype.flipFaces = function (flipNormals) {
  34127. if (flipNormals === void 0) { flipNormals = false; }
  34128. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34129. var i;
  34130. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34131. for (i = 0; i < vertex_data.normals.length; i++) {
  34132. vertex_data.normals[i] *= -1;
  34133. }
  34134. }
  34135. if (vertex_data.indices) {
  34136. var temp;
  34137. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34138. // reassign indices
  34139. temp = vertex_data.indices[i + 1];
  34140. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34141. vertex_data.indices[i + 2] = temp;
  34142. }
  34143. }
  34144. vertex_data.applyToMesh(this);
  34145. return this;
  34146. };
  34147. // Instances
  34148. /**
  34149. * Creates a new InstancedMesh object from the mesh model.
  34150. * Warning : this method is not supported for Line mesh and LineSystem
  34151. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34152. * @param name defines the name of the new instance
  34153. * @returns a new InstancedMesh
  34154. */
  34155. Mesh.prototype.createInstance = function (name) {
  34156. return new BABYLON.InstancedMesh(name, this);
  34157. };
  34158. /**
  34159. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34160. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34161. * @returns the current mesh
  34162. */
  34163. Mesh.prototype.synchronizeInstances = function () {
  34164. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34165. var instance = this.instances[instanceIndex];
  34166. instance._syncSubMeshes();
  34167. }
  34168. return this;
  34169. };
  34170. /**
  34171. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34172. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34173. * This should be used together with the simplification to avoid disappearing triangles.
  34174. * @param successCallback an optional success callback to be called after the optimization finished.
  34175. * @returns the current mesh
  34176. */
  34177. Mesh.prototype.optimizeIndices = function (successCallback) {
  34178. var _this = this;
  34179. var indices = this.getIndices();
  34180. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34181. if (!positions || !indices) {
  34182. return this;
  34183. }
  34184. var vectorPositions = new Array();
  34185. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34186. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34187. }
  34188. var dupes = new Array();
  34189. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34190. var realPos = vectorPositions.length - 1 - iteration;
  34191. var testedPosition = vectorPositions[realPos];
  34192. for (var j = 0; j < realPos; ++j) {
  34193. var againstPosition = vectorPositions[j];
  34194. if (testedPosition.equals(againstPosition)) {
  34195. dupes[realPos] = j;
  34196. break;
  34197. }
  34198. }
  34199. }, function () {
  34200. for (var i = 0; i < indices.length; ++i) {
  34201. indices[i] = dupes[indices[i]] || indices[i];
  34202. }
  34203. //indices are now reordered
  34204. var originalSubMeshes = _this.subMeshes.slice(0);
  34205. _this.setIndices(indices);
  34206. _this.subMeshes = originalSubMeshes;
  34207. if (successCallback) {
  34208. successCallback(_this);
  34209. }
  34210. });
  34211. return this;
  34212. };
  34213. /**
  34214. * Serialize current mesh
  34215. * @param serializationObject defines the object which will receive the serialization data
  34216. */
  34217. Mesh.prototype.serialize = function (serializationObject) {
  34218. serializationObject.name = this.name;
  34219. serializationObject.id = this.id;
  34220. serializationObject.type = this.getClassName();
  34221. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34222. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34223. }
  34224. serializationObject.position = this.position.asArray();
  34225. if (this.rotationQuaternion) {
  34226. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34227. }
  34228. else if (this.rotation) {
  34229. serializationObject.rotation = this.rotation.asArray();
  34230. }
  34231. serializationObject.scaling = this.scaling.asArray();
  34232. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34233. serializationObject.isEnabled = this.isEnabled(false);
  34234. serializationObject.isVisible = this.isVisible;
  34235. serializationObject.infiniteDistance = this.infiniteDistance;
  34236. serializationObject.pickable = this.isPickable;
  34237. serializationObject.receiveShadows = this.receiveShadows;
  34238. serializationObject.billboardMode = this.billboardMode;
  34239. serializationObject.visibility = this.visibility;
  34240. serializationObject.checkCollisions = this.checkCollisions;
  34241. serializationObject.isBlocker = this.isBlocker;
  34242. // Parent
  34243. if (this.parent) {
  34244. serializationObject.parentId = this.parent.id;
  34245. }
  34246. // Geometry
  34247. serializationObject.isUnIndexed = this.isUnIndexed;
  34248. var geometry = this._geometry;
  34249. if (geometry) {
  34250. var geometryId = geometry.id;
  34251. serializationObject.geometryId = geometryId;
  34252. // SubMeshes
  34253. serializationObject.subMeshes = [];
  34254. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34255. var subMesh = this.subMeshes[subIndex];
  34256. serializationObject.subMeshes.push({
  34257. materialIndex: subMesh.materialIndex,
  34258. verticesStart: subMesh.verticesStart,
  34259. verticesCount: subMesh.verticesCount,
  34260. indexStart: subMesh.indexStart,
  34261. indexCount: subMesh.indexCount
  34262. });
  34263. }
  34264. }
  34265. // Material
  34266. if (this.material) {
  34267. serializationObject.materialId = this.material.id;
  34268. }
  34269. else {
  34270. this.material = null;
  34271. }
  34272. // Morph targets
  34273. if (this.morphTargetManager) {
  34274. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34275. }
  34276. // Skeleton
  34277. if (this.skeleton) {
  34278. serializationObject.skeletonId = this.skeleton.id;
  34279. }
  34280. // Physics
  34281. //TODO implement correct serialization for physics impostors.
  34282. var impostor = this.getPhysicsImpostor();
  34283. if (impostor) {
  34284. serializationObject.physicsMass = impostor.getParam("mass");
  34285. serializationObject.physicsFriction = impostor.getParam("friction");
  34286. serializationObject.physicsRestitution = impostor.getParam("mass");
  34287. serializationObject.physicsImpostor = impostor.type;
  34288. }
  34289. // Metadata
  34290. if (this.metadata) {
  34291. serializationObject.metadata = this.metadata;
  34292. }
  34293. // Instances
  34294. serializationObject.instances = [];
  34295. for (var index = 0; index < this.instances.length; index++) {
  34296. var instance = this.instances[index];
  34297. if (instance.doNotSerialize) {
  34298. continue;
  34299. }
  34300. var serializationInstance = {
  34301. name: instance.name,
  34302. id: instance.id,
  34303. position: instance.position.asArray(),
  34304. scaling: instance.scaling.asArray()
  34305. };
  34306. if (instance.parent) {
  34307. serializationInstance.parentId = instance.parent.id;
  34308. }
  34309. if (instance.rotationQuaternion) {
  34310. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34311. }
  34312. else if (instance.rotation) {
  34313. serializationInstance.rotation = instance.rotation.asArray();
  34314. }
  34315. serializationObject.instances.push(serializationInstance);
  34316. // Animations
  34317. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34318. serializationInstance.ranges = instance.serializeAnimationRanges();
  34319. }
  34320. //
  34321. // Animations
  34322. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34323. serializationObject.ranges = this.serializeAnimationRanges();
  34324. // Layer mask
  34325. serializationObject.layerMask = this.layerMask;
  34326. // Alpha
  34327. serializationObject.alphaIndex = this.alphaIndex;
  34328. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34329. // Overlay
  34330. serializationObject.overlayAlpha = this.overlayAlpha;
  34331. serializationObject.overlayColor = this.overlayColor.asArray();
  34332. serializationObject.renderOverlay = this.renderOverlay;
  34333. // Fog
  34334. serializationObject.applyFog = this.applyFog;
  34335. // Action Manager
  34336. if (this.actionManager) {
  34337. serializationObject.actions = this.actionManager.serialize(this.name);
  34338. }
  34339. };
  34340. /** @hidden */
  34341. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34342. if (!this.geometry) {
  34343. return;
  34344. }
  34345. this._markSubMeshesAsAttributesDirty();
  34346. var morphTargetManager = this._morphTargetManager;
  34347. if (morphTargetManager && morphTargetManager.vertexCount) {
  34348. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34349. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34350. this.morphTargetManager = null;
  34351. return;
  34352. }
  34353. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34354. var morphTarget = morphTargetManager.getActiveTarget(index);
  34355. var positions = morphTarget.getPositions();
  34356. if (!positions) {
  34357. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34358. return;
  34359. }
  34360. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34361. var normals = morphTarget.getNormals();
  34362. if (normals) {
  34363. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34364. }
  34365. var tangents = morphTarget.getTangents();
  34366. if (tangents) {
  34367. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34368. }
  34369. }
  34370. }
  34371. else {
  34372. var index = 0;
  34373. // Positions
  34374. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34375. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34376. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34377. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34378. }
  34379. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34380. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34381. }
  34382. index++;
  34383. }
  34384. }
  34385. };
  34386. // Statics
  34387. /**
  34388. * Returns a new Mesh object parsed from the source provided.
  34389. * @param parsedMesh is the source
  34390. * @param scene defines the hosting scene
  34391. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34392. * @returns a new Mesh
  34393. */
  34394. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34395. var mesh;
  34396. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34397. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34398. }
  34399. else {
  34400. mesh = new Mesh(parsedMesh.name, scene);
  34401. }
  34402. mesh.id = parsedMesh.id;
  34403. if (BABYLON.Tags) {
  34404. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34405. }
  34406. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34407. if (parsedMesh.metadata !== undefined) {
  34408. mesh.metadata = parsedMesh.metadata;
  34409. }
  34410. if (parsedMesh.rotationQuaternion) {
  34411. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34412. }
  34413. else if (parsedMesh.rotation) {
  34414. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34415. }
  34416. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34417. if (parsedMesh.localMatrix) {
  34418. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34419. }
  34420. else if (parsedMesh.pivotMatrix) {
  34421. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34422. }
  34423. mesh.setEnabled(parsedMesh.isEnabled);
  34424. mesh.isVisible = parsedMesh.isVisible;
  34425. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34426. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34427. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34428. if (parsedMesh.applyFog !== undefined) {
  34429. mesh.applyFog = parsedMesh.applyFog;
  34430. }
  34431. if (parsedMesh.pickable !== undefined) {
  34432. mesh.isPickable = parsedMesh.pickable;
  34433. }
  34434. if (parsedMesh.alphaIndex !== undefined) {
  34435. mesh.alphaIndex = parsedMesh.alphaIndex;
  34436. }
  34437. mesh.receiveShadows = parsedMesh.receiveShadows;
  34438. mesh.billboardMode = parsedMesh.billboardMode;
  34439. if (parsedMesh.visibility !== undefined) {
  34440. mesh.visibility = parsedMesh.visibility;
  34441. }
  34442. mesh.checkCollisions = parsedMesh.checkCollisions;
  34443. if (parsedMesh.isBlocker !== undefined) {
  34444. mesh.isBlocker = parsedMesh.isBlocker;
  34445. }
  34446. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34447. // freezeWorldMatrix
  34448. if (parsedMesh.freezeWorldMatrix) {
  34449. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34450. }
  34451. // Parent
  34452. if (parsedMesh.parentId) {
  34453. mesh._waitingParentId = parsedMesh.parentId;
  34454. }
  34455. // Actions
  34456. if (parsedMesh.actions !== undefined) {
  34457. mesh._waitingActions = parsedMesh.actions;
  34458. }
  34459. // Overlay
  34460. if (parsedMesh.overlayAlpha !== undefined) {
  34461. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34462. }
  34463. if (parsedMesh.overlayColor !== undefined) {
  34464. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34465. }
  34466. if (parsedMesh.renderOverlay !== undefined) {
  34467. mesh.renderOverlay = parsedMesh.renderOverlay;
  34468. }
  34469. // Geometry
  34470. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34471. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34472. if (parsedMesh.delayLoadingFile) {
  34473. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34474. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34475. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34476. if (parsedMesh._binaryInfo) {
  34477. mesh._binaryInfo = parsedMesh._binaryInfo;
  34478. }
  34479. mesh._delayInfo = [];
  34480. if (parsedMesh.hasUVs) {
  34481. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34482. }
  34483. if (parsedMesh.hasUVs2) {
  34484. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34485. }
  34486. if (parsedMesh.hasUVs3) {
  34487. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34488. }
  34489. if (parsedMesh.hasUVs4) {
  34490. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34491. }
  34492. if (parsedMesh.hasUVs5) {
  34493. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34494. }
  34495. if (parsedMesh.hasUVs6) {
  34496. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34497. }
  34498. if (parsedMesh.hasColors) {
  34499. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34500. }
  34501. if (parsedMesh.hasMatricesIndices) {
  34502. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34503. }
  34504. if (parsedMesh.hasMatricesWeights) {
  34505. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34506. }
  34507. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34508. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34509. mesh._checkDelayState();
  34510. }
  34511. }
  34512. else {
  34513. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34514. }
  34515. // Material
  34516. if (parsedMesh.materialId) {
  34517. mesh.setMaterialByID(parsedMesh.materialId);
  34518. }
  34519. else {
  34520. mesh.material = null;
  34521. }
  34522. // Morph targets
  34523. if (parsedMesh.morphTargetManagerId > -1) {
  34524. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34525. }
  34526. // Skeleton
  34527. if (parsedMesh.skeletonId > -1) {
  34528. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34529. if (parsedMesh.numBoneInfluencers) {
  34530. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34531. }
  34532. }
  34533. // Animations
  34534. if (parsedMesh.animations) {
  34535. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34536. var parsedAnimation = parsedMesh.animations[animationIndex];
  34537. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34538. }
  34539. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34540. }
  34541. if (parsedMesh.autoAnimate) {
  34542. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34543. }
  34544. // Layer Mask
  34545. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34546. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34547. }
  34548. else {
  34549. mesh.layerMask = 0x0FFFFFFF;
  34550. }
  34551. // Physics
  34552. if (parsedMesh.physicsImpostor) {
  34553. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34554. mass: parsedMesh.physicsMass,
  34555. friction: parsedMesh.physicsFriction,
  34556. restitution: parsedMesh.physicsRestitution
  34557. }, scene);
  34558. }
  34559. // Instances
  34560. if (parsedMesh.instances) {
  34561. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34562. var parsedInstance = parsedMesh.instances[index];
  34563. var instance = mesh.createInstance(parsedInstance.name);
  34564. if (parsedInstance.id) {
  34565. instance.id = parsedInstance.id;
  34566. }
  34567. if (BABYLON.Tags) {
  34568. if (parsedInstance.tags) {
  34569. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34570. }
  34571. else {
  34572. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34573. }
  34574. }
  34575. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34576. if (parsedInstance.parentId) {
  34577. instance._waitingParentId = parsedInstance.parentId;
  34578. }
  34579. if (parsedInstance.rotationQuaternion) {
  34580. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34581. }
  34582. else if (parsedInstance.rotation) {
  34583. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34584. }
  34585. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34586. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34587. instance.checkCollisions = parsedInstance.checkCollisions;
  34588. }
  34589. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34590. instance.isPickable = parsedInstance.pickable;
  34591. }
  34592. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34593. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34594. }
  34595. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34596. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34597. }
  34598. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34599. instance.alphaIndex = parsedInstance.alphaIndex;
  34600. }
  34601. // Physics
  34602. if (parsedInstance.physicsImpostor) {
  34603. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34604. mass: parsedInstance.physicsMass,
  34605. friction: parsedInstance.physicsFriction,
  34606. restitution: parsedInstance.physicsRestitution
  34607. }, scene);
  34608. }
  34609. // Animation
  34610. if (parsedInstance.animations) {
  34611. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34612. parsedAnimation = parsedInstance.animations[animationIndex];
  34613. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34614. }
  34615. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34616. if (parsedInstance.autoAnimate) {
  34617. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34618. }
  34619. }
  34620. }
  34621. }
  34622. return mesh;
  34623. };
  34624. /**
  34625. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34626. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34627. * @param name defines the name of the mesh to create
  34628. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34629. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34630. * @param closePath creates a seam between the first and the last points of each path of the path array
  34631. * @param offset is taken in account only if the `pathArray` is containing a single path
  34632. * @param scene defines the hosting scene
  34633. * @param updatable defines if the mesh must be flagged as updatable
  34634. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34635. * @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)
  34636. * @returns a new Mesh
  34637. */
  34638. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34639. if (closeArray === void 0) { closeArray = false; }
  34640. if (updatable === void 0) { updatable = false; }
  34641. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34642. pathArray: pathArray,
  34643. closeArray: closeArray,
  34644. closePath: closePath,
  34645. offset: offset,
  34646. updatable: updatable,
  34647. sideOrientation: sideOrientation,
  34648. instance: instance
  34649. }, scene);
  34650. };
  34651. /**
  34652. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34653. * @param name defines the name of the mesh to create
  34654. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34655. * @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
  34656. * @param scene defines the hosting scene
  34657. * @param updatable defines if the mesh must be flagged as updatable
  34658. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34659. * @returns a new Mesh
  34660. */
  34661. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34662. if (scene === void 0) { scene = null; }
  34663. var options = {
  34664. radius: radius,
  34665. tessellation: tessellation,
  34666. sideOrientation: sideOrientation,
  34667. updatable: updatable
  34668. };
  34669. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34670. };
  34671. /**
  34672. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34673. * @param name defines the name of the mesh to create
  34674. * @param size sets the size (float) of each box side (default 1)
  34675. * @param scene defines the hosting scene
  34676. * @param updatable defines if the mesh must be flagged as updatable
  34677. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34678. * @returns a new Mesh
  34679. */
  34680. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34681. if (scene === void 0) { scene = null; }
  34682. var options = {
  34683. size: size,
  34684. sideOrientation: sideOrientation,
  34685. updatable: updatable
  34686. };
  34687. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34688. };
  34689. /**
  34690. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34691. * @param name defines the name of the mesh to create
  34692. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34693. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34694. * @param scene defines the hosting scene
  34695. * @param updatable defines if the mesh must be flagged as updatable
  34696. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34697. * @returns a new Mesh
  34698. */
  34699. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34700. var options = {
  34701. segments: segments,
  34702. diameterX: diameter,
  34703. diameterY: diameter,
  34704. diameterZ: diameter,
  34705. sideOrientation: sideOrientation,
  34706. updatable: updatable
  34707. };
  34708. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34709. };
  34710. /**
  34711. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34712. * @param name defines the name of the mesh to create
  34713. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34714. * @param diameterTop set the top cap diameter (floats, default 1)
  34715. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34716. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34717. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34718. * @param scene defines the hosting scene
  34719. * @param updatable defines if the mesh must be flagged as updatable
  34720. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34721. * @returns a new Mesh
  34722. */
  34723. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34724. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34725. if (scene !== undefined) {
  34726. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34727. updatable = scene;
  34728. }
  34729. scene = subdivisions;
  34730. subdivisions = 1;
  34731. }
  34732. var options = {
  34733. height: height,
  34734. diameterTop: diameterTop,
  34735. diameterBottom: diameterBottom,
  34736. tessellation: tessellation,
  34737. subdivisions: subdivisions,
  34738. sideOrientation: sideOrientation,
  34739. updatable: updatable
  34740. };
  34741. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34742. };
  34743. // Torus (Code from SharpDX.org)
  34744. /**
  34745. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34746. * @param name defines the name of the mesh to create
  34747. * @param diameter sets the diameter size (float) of the torus (default 1)
  34748. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34749. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34750. * @param scene defines the hosting scene
  34751. * @param updatable defines if the mesh must be flagged as updatable
  34752. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34753. * @returns a new Mesh
  34754. */
  34755. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34756. var options = {
  34757. diameter: diameter,
  34758. thickness: thickness,
  34759. tessellation: tessellation,
  34760. sideOrientation: sideOrientation,
  34761. updatable: updatable
  34762. };
  34763. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34764. };
  34765. /**
  34766. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34767. * @param name defines the name of the mesh to create
  34768. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34769. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34770. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34771. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34772. * @param p the number of windings on X axis (positive integers, default 2)
  34773. * @param q the number of windings on Y axis (positive integers, default 3)
  34774. * @param scene defines the hosting scene
  34775. * @param updatable defines if the mesh must be flagged as updatable
  34776. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34777. * @returns a new Mesh
  34778. */
  34779. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34780. var options = {
  34781. radius: radius,
  34782. tube: tube,
  34783. radialSegments: radialSegments,
  34784. tubularSegments: tubularSegments,
  34785. p: p,
  34786. q: q,
  34787. sideOrientation: sideOrientation,
  34788. updatable: updatable
  34789. };
  34790. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34791. };
  34792. /**
  34793. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34794. * @param name defines the name of the mesh to create
  34795. * @param points is an array successive Vector3
  34796. * @param scene defines the hosting scene
  34797. * @param updatable defines if the mesh must be flagged as updatable
  34798. * @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).
  34799. * @returns a new Mesh
  34800. */
  34801. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34802. if (scene === void 0) { scene = null; }
  34803. if (updatable === void 0) { updatable = false; }
  34804. if (instance === void 0) { instance = null; }
  34805. var options = {
  34806. points: points,
  34807. updatable: updatable,
  34808. instance: instance
  34809. };
  34810. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34811. };
  34812. /**
  34813. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34814. * @param name defines the name of the mesh to create
  34815. * @param points is an array successive Vector3
  34816. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34817. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34818. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34819. * @param scene defines the hosting scene
  34820. * @param updatable defines if the mesh must be flagged as updatable
  34821. * @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)
  34822. * @returns a new Mesh
  34823. */
  34824. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34825. if (scene === void 0) { scene = null; }
  34826. var options = {
  34827. points: points,
  34828. dashSize: dashSize,
  34829. gapSize: gapSize,
  34830. dashNb: dashNb,
  34831. updatable: updatable,
  34832. instance: instance
  34833. };
  34834. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34835. };
  34836. /**
  34837. * Creates a polygon mesh.
  34838. * Please consider using the same method from the MeshBuilder class instead.
  34839. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34840. * 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.
  34841. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34843. * Remember you can only change the shape positions, not their number when updating a polygon.
  34844. */
  34845. /**
  34846. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34847. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34848. * @param name defines the name of the mesh to create
  34849. * @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
  34850. * @param scene defines the hosting scene
  34851. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34852. * @param updatable defines if the mesh must be flagged as updatable
  34853. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34854. * @returns a new Mesh
  34855. */
  34856. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34857. var options = {
  34858. shape: shape,
  34859. holes: holes,
  34860. updatable: updatable,
  34861. sideOrientation: sideOrientation
  34862. };
  34863. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34864. };
  34865. /**
  34866. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34867. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34868. * @param name defines the name of the mesh to create
  34869. * @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
  34870. * @param depth defines the height of extrusion
  34871. * @param scene defines the hosting scene
  34872. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34873. * @param updatable defines if the mesh must be flagged as updatable
  34874. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34875. * @returns a new Mesh
  34876. */
  34877. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34878. var options = {
  34879. shape: shape,
  34880. holes: holes,
  34881. depth: depth,
  34882. updatable: updatable,
  34883. sideOrientation: sideOrientation
  34884. };
  34885. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34886. };
  34887. /**
  34888. * Creates an extruded shape mesh.
  34889. * 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
  34890. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34891. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34892. * @param name defines the name of the mesh to create
  34893. * @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
  34894. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34895. * @param scale is the value to scale the shape
  34896. * @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
  34897. * @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
  34898. * @param scene defines the hosting scene
  34899. * @param updatable defines if the mesh must be flagged as updatable
  34900. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34901. * @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)
  34902. * @returns a new Mesh
  34903. */
  34904. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34905. if (scene === void 0) { scene = null; }
  34906. var options = {
  34907. shape: shape,
  34908. path: path,
  34909. scale: scale,
  34910. rotation: rotation,
  34911. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34912. sideOrientation: sideOrientation,
  34913. instance: instance,
  34914. updatable: updatable
  34915. };
  34916. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34917. };
  34918. /**
  34919. * Creates an custom extruded shape mesh.
  34920. * The custom extrusion is a parametric shape.
  34921. * It has no predefined shape. Its final shape will depend on the input parameters.
  34922. * Please consider using the same method from the MeshBuilder class instead
  34923. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34924. * @param name defines the name of the mesh to create
  34925. * @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
  34926. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34927. * @param scaleFunction is a custom Javascript function called on each path point
  34928. * @param rotationFunction is a custom Javascript function called on each path point
  34929. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34930. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34931. * @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
  34932. * @param scene defines the hosting scene
  34933. * @param updatable defines if the mesh must be flagged as updatable
  34934. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34935. * @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)
  34936. * @returns a new Mesh
  34937. */
  34938. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34939. var options = {
  34940. shape: shape,
  34941. path: path,
  34942. scaleFunction: scaleFunction,
  34943. rotationFunction: rotationFunction,
  34944. ribbonCloseArray: ribbonCloseArray,
  34945. ribbonClosePath: ribbonClosePath,
  34946. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34947. sideOrientation: sideOrientation,
  34948. instance: instance,
  34949. updatable: updatable
  34950. };
  34951. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34952. };
  34953. /**
  34954. * Creates lathe mesh.
  34955. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34956. * Please consider using the same method from the MeshBuilder class instead
  34957. * @param name defines the name of the mesh to create
  34958. * @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
  34959. * @param radius is the radius value of the lathe
  34960. * @param tessellation is the side number of the lathe.
  34961. * @param scene defines the hosting scene
  34962. * @param updatable defines if the mesh must be flagged as updatable
  34963. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34964. * @returns a new Mesh
  34965. */
  34966. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34967. var options = {
  34968. shape: shape,
  34969. radius: radius,
  34970. tessellation: tessellation,
  34971. sideOrientation: sideOrientation,
  34972. updatable: updatable
  34973. };
  34974. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34975. };
  34976. /**
  34977. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34978. * @param name defines the name of the mesh to create
  34979. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34980. * @param scene defines the hosting scene
  34981. * @param updatable defines if the mesh must be flagged as updatable
  34982. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34983. * @returns a new Mesh
  34984. */
  34985. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34986. var options = {
  34987. size: size,
  34988. width: size,
  34989. height: size,
  34990. sideOrientation: sideOrientation,
  34991. updatable: updatable
  34992. };
  34993. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34994. };
  34995. /**
  34996. * Creates a ground mesh.
  34997. * Please consider using the same method from the MeshBuilder class instead
  34998. * @param name defines the name of the mesh to create
  34999. * @param width set the width of the ground
  35000. * @param height set the height of the ground
  35001. * @param subdivisions sets the number of subdivisions per side
  35002. * @param scene defines the hosting scene
  35003. * @param updatable defines if the mesh must be flagged as updatable
  35004. * @returns a new Mesh
  35005. */
  35006. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35007. var options = {
  35008. width: width,
  35009. height: height,
  35010. subdivisions: subdivisions,
  35011. updatable: updatable
  35012. };
  35013. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35014. };
  35015. /**
  35016. * Creates a tiled ground mesh.
  35017. * Please consider using the same method from the MeshBuilder class instead
  35018. * @param name defines the name of the mesh to create
  35019. * @param xmin set the ground minimum X coordinate
  35020. * @param zmin set the ground minimum Y coordinate
  35021. * @param xmax set the ground maximum X coordinate
  35022. * @param zmax set the ground maximum Z coordinate
  35023. * @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
  35024. * @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
  35025. * @param scene defines the hosting scene
  35026. * @param updatable defines if the mesh must be flagged as updatable
  35027. * @returns a new Mesh
  35028. */
  35029. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35030. var options = {
  35031. xmin: xmin,
  35032. zmin: zmin,
  35033. xmax: xmax,
  35034. zmax: zmax,
  35035. subdivisions: subdivisions,
  35036. precision: precision,
  35037. updatable: updatable
  35038. };
  35039. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35040. };
  35041. /**
  35042. * Creates a ground mesh from a height map.
  35043. * Please consider using the same method from the MeshBuilder class instead
  35044. * @see http://doc.babylonjs.com/babylon101/height_map
  35045. * @param name defines the name of the mesh to create
  35046. * @param url sets the URL of the height map image resource
  35047. * @param width set the ground width size
  35048. * @param height set the ground height size
  35049. * @param subdivisions sets the number of subdivision per side
  35050. * @param minHeight is the minimum altitude on the ground
  35051. * @param maxHeight is the maximum altitude on the ground
  35052. * @param scene defines the hosting scene
  35053. * @param updatable defines if the mesh must be flagged as updatable
  35054. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35055. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35056. * @returns a new Mesh
  35057. */
  35058. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35059. var options = {
  35060. width: width,
  35061. height: height,
  35062. subdivisions: subdivisions,
  35063. minHeight: minHeight,
  35064. maxHeight: maxHeight,
  35065. updatable: updatable,
  35066. onReady: onReady,
  35067. alphaFilter: alphaFilter
  35068. };
  35069. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35070. };
  35071. /**
  35072. * Creates a tube mesh.
  35073. * The tube is a parametric shape.
  35074. * It has no predefined shape. Its final shape will depend on the input parameters.
  35075. * Please consider using the same method from the MeshBuilder class instead
  35076. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35077. * @param name defines the name of the mesh to create
  35078. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35079. * @param radius sets the tube radius size
  35080. * @param tessellation is the number of sides on the tubular surface
  35081. * @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
  35082. * @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
  35083. * @param scene defines the hosting scene
  35084. * @param updatable defines if the mesh must be flagged as updatable
  35085. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35086. * @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)
  35087. * @returns a new Mesh
  35088. */
  35089. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35090. var options = {
  35091. path: path,
  35092. radius: radius,
  35093. tessellation: tessellation,
  35094. radiusFunction: radiusFunction,
  35095. arc: 1,
  35096. cap: cap,
  35097. updatable: updatable,
  35098. sideOrientation: sideOrientation,
  35099. instance: instance
  35100. };
  35101. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35102. };
  35103. /**
  35104. * Creates a polyhedron mesh.
  35105. * Please consider using the same method from the MeshBuilder class instead.
  35106. * * 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
  35107. * * The parameter `size` (positive float, default 1) sets the polygon size
  35108. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35109. * * 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`
  35110. * * 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
  35111. * * 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)`)
  35112. * * 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
  35113. * * 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
  35114. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35115. * * 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
  35116. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35117. * @param name defines the name of the mesh to create
  35118. * @param options defines the options used to create the mesh
  35119. * @param scene defines the hosting scene
  35120. * @returns a new Mesh
  35121. */
  35122. Mesh.CreatePolyhedron = function (name, options, scene) {
  35123. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35124. };
  35125. /**
  35126. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35127. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35128. * * 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`)
  35129. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35130. * * 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
  35131. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35132. * * 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
  35133. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35134. * @param name defines the name of the mesh
  35135. * @param options defines the options used to create the mesh
  35136. * @param scene defines the hosting scene
  35137. * @returns a new Mesh
  35138. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35139. */
  35140. Mesh.CreateIcoSphere = function (name, options, scene) {
  35141. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35142. };
  35143. /**
  35144. * Creates a decal mesh.
  35145. * Please consider using the same method from the MeshBuilder class instead.
  35146. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35147. * @param name defines the name of the mesh
  35148. * @param sourceMesh defines the mesh receiving the decal
  35149. * @param position sets the position of the decal in world coordinates
  35150. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35151. * @param size sets the decal scaling
  35152. * @param angle sets the angle to rotate the decal
  35153. * @returns a new Mesh
  35154. */
  35155. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35156. var options = {
  35157. position: position,
  35158. normal: normal,
  35159. size: size,
  35160. angle: angle
  35161. };
  35162. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35163. };
  35164. // Skeletons
  35165. /**
  35166. * Prepare internal position array for software CPU skinning
  35167. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35168. */
  35169. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35170. if (!this._sourcePositions) {
  35171. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35172. if (!source) {
  35173. return this._sourcePositions;
  35174. }
  35175. this._sourcePositions = new Float32Array(source);
  35176. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35177. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35178. }
  35179. }
  35180. return this._sourcePositions;
  35181. };
  35182. /**
  35183. * Prepare internal normal array for software CPU skinning
  35184. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35185. */
  35186. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35187. if (!this._sourceNormals) {
  35188. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35189. if (!source) {
  35190. return this._sourceNormals;
  35191. }
  35192. this._sourceNormals = new Float32Array(source);
  35193. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35194. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35195. }
  35196. }
  35197. return this._sourceNormals;
  35198. };
  35199. /**
  35200. * Updates the vertex buffer by applying transformation from the bones
  35201. * @param skeleton defines the skeleton to apply to current mesh
  35202. * @returns the current mesh
  35203. */
  35204. Mesh.prototype.applySkeleton = function (skeleton) {
  35205. if (!this.geometry) {
  35206. return this;
  35207. }
  35208. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35209. return this;
  35210. }
  35211. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35212. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35213. return this;
  35214. }
  35215. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35216. return this;
  35217. }
  35218. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35219. return this;
  35220. }
  35221. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35222. return this;
  35223. }
  35224. if (!this._sourcePositions) {
  35225. var submeshes = this.subMeshes.slice();
  35226. this.setPositionsForCPUSkinning();
  35227. this.subMeshes = submeshes;
  35228. }
  35229. if (!this._sourceNormals) {
  35230. this.setNormalsForCPUSkinning();
  35231. }
  35232. // positionsData checks for not being Float32Array will only pass at most once
  35233. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35234. if (!positionsData) {
  35235. return this;
  35236. }
  35237. if (!(positionsData instanceof Float32Array)) {
  35238. positionsData = new Float32Array(positionsData);
  35239. }
  35240. // normalsData checks for not being Float32Array will only pass at most once
  35241. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35242. if (!normalsData) {
  35243. return this;
  35244. }
  35245. if (!(normalsData instanceof Float32Array)) {
  35246. normalsData = new Float32Array(normalsData);
  35247. }
  35248. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35249. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35250. if (!matricesWeightsData || !matricesIndicesData) {
  35251. return this;
  35252. }
  35253. var needExtras = this.numBoneInfluencers > 4;
  35254. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35255. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35256. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35257. var tempVector3 = BABYLON.Vector3.Zero();
  35258. var finalMatrix = new BABYLON.Matrix();
  35259. var tempMatrix = new BABYLON.Matrix();
  35260. var matWeightIdx = 0;
  35261. var inf;
  35262. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35263. var weight;
  35264. for (inf = 0; inf < 4; inf++) {
  35265. weight = matricesWeightsData[matWeightIdx + inf];
  35266. if (weight > 0) {
  35267. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35268. finalMatrix.addToSelf(tempMatrix);
  35269. }
  35270. }
  35271. if (needExtras) {
  35272. for (inf = 0; inf < 4; inf++) {
  35273. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35274. if (weight > 0) {
  35275. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35276. finalMatrix.addToSelf(tempMatrix);
  35277. }
  35278. }
  35279. }
  35280. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35281. tempVector3.toArray(positionsData, index);
  35282. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35283. tempVector3.toArray(normalsData, index);
  35284. finalMatrix.reset();
  35285. }
  35286. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35287. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35288. return this;
  35289. };
  35290. // Tools
  35291. /**
  35292. * 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
  35293. * @param meshes defines the list of meshes to scan
  35294. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35295. */
  35296. Mesh.MinMax = function (meshes) {
  35297. var minVector = null;
  35298. var maxVector = null;
  35299. meshes.forEach(function (mesh, index, array) {
  35300. var boundingInfo = mesh.getBoundingInfo();
  35301. var boundingBox = boundingInfo.boundingBox;
  35302. if (!minVector || !maxVector) {
  35303. minVector = boundingBox.minimumWorld;
  35304. maxVector = boundingBox.maximumWorld;
  35305. }
  35306. else {
  35307. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35308. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35309. }
  35310. });
  35311. if (!minVector || !maxVector) {
  35312. return {
  35313. min: BABYLON.Vector3.Zero(),
  35314. max: BABYLON.Vector3.Zero()
  35315. };
  35316. }
  35317. return {
  35318. min: minVector,
  35319. max: maxVector
  35320. };
  35321. };
  35322. /**
  35323. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35324. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35325. * @returns a vector3
  35326. */
  35327. Mesh.Center = function (meshesOrMinMaxVector) {
  35328. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35329. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35330. };
  35331. /**
  35332. * Merge the array of meshes into a single mesh for performance reasons.
  35333. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35334. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35335. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35336. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35337. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35338. * @returns a new mesh
  35339. */
  35340. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35341. if (disposeSource === void 0) { disposeSource = true; }
  35342. var index;
  35343. if (!allow32BitsIndices) {
  35344. var totalVertices = 0;
  35345. // Counting vertices
  35346. for (index = 0; index < meshes.length; index++) {
  35347. if (meshes[index]) {
  35348. totalVertices += meshes[index].getTotalVertices();
  35349. if (totalVertices > 65536) {
  35350. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35351. return null;
  35352. }
  35353. }
  35354. }
  35355. }
  35356. // Merge
  35357. var vertexData = null;
  35358. var otherVertexData;
  35359. var indiceArray = new Array();
  35360. var source = null;
  35361. for (index = 0; index < meshes.length; index++) {
  35362. if (meshes[index]) {
  35363. var wm = meshes[index].computeWorldMatrix(true);
  35364. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35365. otherVertexData.transform(wm);
  35366. if (vertexData) {
  35367. vertexData.merge(otherVertexData, allow32BitsIndices);
  35368. }
  35369. else {
  35370. vertexData = otherVertexData;
  35371. source = meshes[index];
  35372. }
  35373. if (subdivideWithSubMeshes) {
  35374. indiceArray.push(meshes[index].getTotalIndices());
  35375. }
  35376. }
  35377. }
  35378. source = source;
  35379. if (!meshSubclass) {
  35380. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35381. }
  35382. vertexData.applyToMesh(meshSubclass);
  35383. // Setting properties
  35384. meshSubclass.material = source.material;
  35385. meshSubclass.checkCollisions = source.checkCollisions;
  35386. // Cleaning
  35387. if (disposeSource) {
  35388. for (index = 0; index < meshes.length; index++) {
  35389. if (meshes[index]) {
  35390. meshes[index].dispose();
  35391. }
  35392. }
  35393. }
  35394. // Subdivide
  35395. if (subdivideWithSubMeshes) {
  35396. //-- removal of global submesh
  35397. meshSubclass.releaseSubMeshes();
  35398. index = 0;
  35399. var offset = 0;
  35400. //-- apply subdivision according to index table
  35401. while (index < indiceArray.length) {
  35402. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35403. offset += indiceArray[index];
  35404. index++;
  35405. }
  35406. }
  35407. return meshSubclass;
  35408. };
  35409. // Consts
  35410. /**
  35411. * Mesh side orientation : usually the external or front surface
  35412. */
  35413. Mesh.FRONTSIDE = 0;
  35414. /**
  35415. * Mesh side orientation : usually the internal or back surface
  35416. */
  35417. Mesh.BACKSIDE = 1;
  35418. /**
  35419. * Mesh side orientation : both internal and external or front and back surfaces
  35420. */
  35421. Mesh.DOUBLESIDE = 2;
  35422. /**
  35423. * Mesh side orientation : by default, `FRONTSIDE`
  35424. */
  35425. Mesh.DEFAULTSIDE = 0;
  35426. /**
  35427. * Mesh cap setting : no cap
  35428. */
  35429. Mesh.NO_CAP = 0;
  35430. /**
  35431. * Mesh cap setting : one cap at the beginning of the mesh
  35432. */
  35433. Mesh.CAP_START = 1;
  35434. /**
  35435. * Mesh cap setting : one cap at the end of the mesh
  35436. */
  35437. Mesh.CAP_END = 2;
  35438. /**
  35439. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35440. */
  35441. Mesh.CAP_ALL = 3;
  35442. return Mesh;
  35443. }(BABYLON.AbstractMesh));
  35444. BABYLON.Mesh = Mesh;
  35445. })(BABYLON || (BABYLON = {}));
  35446. //# sourceMappingURL=babylon.mesh.js.map
  35447. var BABYLON;
  35448. (function (BABYLON) {
  35449. /**
  35450. * Base class for submeshes
  35451. */
  35452. var BaseSubMesh = /** @class */ (function () {
  35453. function BaseSubMesh() {
  35454. }
  35455. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35456. /**
  35457. * Gets associated effect
  35458. */
  35459. get: function () {
  35460. return this._materialEffect;
  35461. },
  35462. enumerable: true,
  35463. configurable: true
  35464. });
  35465. /**
  35466. * Sets associated effect (effect used to render this submesh)
  35467. * @param effect defines the effect to associate with
  35468. * @param defines defines the set of defines used to compile this effect
  35469. */
  35470. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35471. if (defines === void 0) { defines = null; }
  35472. if (this._materialEffect === effect) {
  35473. if (!effect) {
  35474. this._materialDefines = null;
  35475. }
  35476. return;
  35477. }
  35478. this._materialDefines = defines;
  35479. this._materialEffect = effect;
  35480. };
  35481. return BaseSubMesh;
  35482. }());
  35483. BABYLON.BaseSubMesh = BaseSubMesh;
  35484. /**
  35485. * Defines a subdivision inside a mesh
  35486. */
  35487. var SubMesh = /** @class */ (function (_super) {
  35488. __extends(SubMesh, _super);
  35489. /**
  35490. * Creates a new submesh
  35491. * @param materialIndex defines the material index to use
  35492. * @param verticesStart defines vertex index start
  35493. * @param verticesCount defines vertices count
  35494. * @param indexStart defines index start
  35495. * @param indexCount defines indices count
  35496. * @param mesh defines the parent mesh
  35497. * @param renderingMesh defines an optional rendering mesh
  35498. * @param createBoundingBox defines if bounding box should be created for this submesh
  35499. */
  35500. function SubMesh(
  35501. /** the material index to use */
  35502. materialIndex,
  35503. /** vertex index start */
  35504. verticesStart,
  35505. /** vertices count */
  35506. verticesCount,
  35507. /** index start */
  35508. indexStart,
  35509. /** indices count */
  35510. indexCount, mesh, renderingMesh, createBoundingBox) {
  35511. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35512. var _this = _super.call(this) || this;
  35513. _this.materialIndex = materialIndex;
  35514. _this.verticesStart = verticesStart;
  35515. _this.verticesCount = verticesCount;
  35516. _this.indexStart = indexStart;
  35517. _this.indexCount = indexCount;
  35518. /** @hidden */
  35519. _this._renderId = 0;
  35520. _this._mesh = mesh;
  35521. _this._renderingMesh = renderingMesh || mesh;
  35522. mesh.subMeshes.push(_this);
  35523. _this._trianglePlanes = [];
  35524. _this._id = mesh.subMeshes.length - 1;
  35525. if (createBoundingBox) {
  35526. _this.refreshBoundingInfo();
  35527. mesh.computeWorldMatrix(true);
  35528. }
  35529. return _this;
  35530. }
  35531. /**
  35532. * Add a new submesh to a mesh
  35533. * @param materialIndex defines the material index to use
  35534. * @param verticesStart defines vertex index start
  35535. * @param verticesCount defines vertices count
  35536. * @param indexStart defines index start
  35537. * @param indexCount defines indices count
  35538. * @param mesh defines the parent mesh
  35539. * @param renderingMesh defines an optional rendering mesh
  35540. * @param createBoundingBox defines if bounding box should be created for this submesh
  35541. * @returns the new submesh
  35542. */
  35543. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35544. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35545. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35546. };
  35547. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35548. /**
  35549. * Returns true if this submesh covers the entire parent mesh
  35550. * @ignorenaming
  35551. */
  35552. get: function () {
  35553. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35554. },
  35555. enumerable: true,
  35556. configurable: true
  35557. });
  35558. /**
  35559. * Returns the submesh BoudingInfo object
  35560. * @returns current bounding info (or mesh's one if the submesh is global)
  35561. */
  35562. SubMesh.prototype.getBoundingInfo = function () {
  35563. if (this.IsGlobal) {
  35564. return this._mesh.getBoundingInfo();
  35565. }
  35566. return this._boundingInfo;
  35567. };
  35568. /**
  35569. * Sets the submesh BoundingInfo
  35570. * @param boundingInfo defines the new bounding info to use
  35571. * @returns the SubMesh
  35572. */
  35573. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35574. this._boundingInfo = boundingInfo;
  35575. return this;
  35576. };
  35577. /**
  35578. * Returns the mesh of the current submesh
  35579. * @return the parent mesh
  35580. */
  35581. SubMesh.prototype.getMesh = function () {
  35582. return this._mesh;
  35583. };
  35584. /**
  35585. * Returns the rendering mesh of the submesh
  35586. * @returns the rendering mesh (could be different from parent mesh)
  35587. */
  35588. SubMesh.prototype.getRenderingMesh = function () {
  35589. return this._renderingMesh;
  35590. };
  35591. /**
  35592. * Returns the submesh material
  35593. * @returns null or the current material
  35594. */
  35595. SubMesh.prototype.getMaterial = function () {
  35596. var rootMaterial = this._renderingMesh.material;
  35597. if (rootMaterial === null || rootMaterial === undefined) {
  35598. return this._mesh.getScene().defaultMaterial;
  35599. }
  35600. else if (rootMaterial.getSubMaterial) {
  35601. var multiMaterial = rootMaterial;
  35602. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35603. if (this._currentMaterial !== effectiveMaterial) {
  35604. this._currentMaterial = effectiveMaterial;
  35605. this._materialDefines = null;
  35606. }
  35607. return effectiveMaterial;
  35608. }
  35609. return rootMaterial;
  35610. };
  35611. // Methods
  35612. /**
  35613. * Sets a new updated BoundingInfo object to the submesh
  35614. * @returns the SubMesh
  35615. */
  35616. SubMesh.prototype.refreshBoundingInfo = function () {
  35617. this._lastColliderWorldVertices = null;
  35618. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35619. return this;
  35620. }
  35621. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35622. if (!data) {
  35623. this._boundingInfo = this._mesh.getBoundingInfo();
  35624. return this;
  35625. }
  35626. var indices = this._renderingMesh.getIndices();
  35627. var extend;
  35628. //is this the only submesh?
  35629. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35630. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35631. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35632. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35633. }
  35634. else {
  35635. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35636. }
  35637. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35638. return this;
  35639. };
  35640. /** @hidden */
  35641. SubMesh.prototype._checkCollision = function (collider) {
  35642. var boundingInfo = this.getBoundingInfo();
  35643. return boundingInfo._checkCollision(collider);
  35644. };
  35645. /**
  35646. * Updates the submesh BoundingInfo
  35647. * @param world defines the world matrix to use to update the bounding info
  35648. * @returns the submesh
  35649. */
  35650. SubMesh.prototype.updateBoundingInfo = function (world) {
  35651. var boundingInfo = this.getBoundingInfo();
  35652. if (!boundingInfo) {
  35653. this.refreshBoundingInfo();
  35654. boundingInfo = this.getBoundingInfo();
  35655. }
  35656. boundingInfo.update(world);
  35657. return this;
  35658. };
  35659. /**
  35660. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35661. * @param frustumPlanes defines the frustum planes
  35662. * @returns true if the submesh is intersecting with the frustum
  35663. */
  35664. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35665. var boundingInfo = this.getBoundingInfo();
  35666. if (!boundingInfo) {
  35667. return false;
  35668. }
  35669. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35670. };
  35671. /**
  35672. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35673. * @param frustumPlanes defines the frustum planes
  35674. * @returns true if the submesh is inside the frustum
  35675. */
  35676. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35677. var boundingInfo = this.getBoundingInfo();
  35678. if (!boundingInfo) {
  35679. return false;
  35680. }
  35681. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35682. };
  35683. /**
  35684. * Renders the submesh
  35685. * @param enableAlphaMode defines if alpha needs to be used
  35686. * @returns the submesh
  35687. */
  35688. SubMesh.prototype.render = function (enableAlphaMode) {
  35689. this._renderingMesh.render(this, enableAlphaMode);
  35690. return this;
  35691. };
  35692. /**
  35693. * @hidden
  35694. */
  35695. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35696. if (!this._linesIndexBuffer) {
  35697. var linesIndices = [];
  35698. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35699. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35700. }
  35701. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35702. this._linesIndexCount = linesIndices.length;
  35703. }
  35704. return this._linesIndexBuffer;
  35705. };
  35706. /**
  35707. * Checks if the submesh intersects with a ray
  35708. * @param ray defines the ray to test
  35709. * @returns true is the passed ray intersects the submesh bounding box
  35710. */
  35711. SubMesh.prototype.canIntersects = function (ray) {
  35712. var boundingInfo = this.getBoundingInfo();
  35713. if (!boundingInfo) {
  35714. return false;
  35715. }
  35716. return ray.intersectsBox(boundingInfo.boundingBox);
  35717. };
  35718. /**
  35719. * Intersects current submesh with a ray
  35720. * @param ray defines the ray to test
  35721. * @param positions defines mesh's positions array
  35722. * @param indices defines mesh's indices array
  35723. * @param fastCheck defines if only bounding info should be used
  35724. * @returns intersection info or null if no intersection
  35725. */
  35726. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35727. var material = this.getMaterial();
  35728. if (!material) {
  35729. return null;
  35730. }
  35731. switch (material.fillMode) {
  35732. case BABYLON.Material.PointListDrawMode:
  35733. case BABYLON.Material.LineListDrawMode:
  35734. case BABYLON.Material.LineLoopDrawMode:
  35735. case BABYLON.Material.LineStripDrawMode:
  35736. case BABYLON.Material.TriangleFanDrawMode:
  35737. case BABYLON.Material.TriangleStripDrawMode:
  35738. return null;
  35739. }
  35740. // LineMesh first as it's also a Mesh...
  35741. if (BABYLON.LinesMesh) {
  35742. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  35743. if (mesh instanceof BABYLON.LinesMesh) {
  35744. var linesMesh = mesh;
  35745. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  35746. }
  35747. }
  35748. return this._intersectTriangles(ray, positions, indices, fastCheck);
  35749. };
  35750. /** @hidden */
  35751. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  35752. var intersectInfo = null;
  35753. // Line test
  35754. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35755. var p0 = positions[indices[index]];
  35756. var p1 = positions[indices[index + 1]];
  35757. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  35758. if (length < 0) {
  35759. continue;
  35760. }
  35761. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35762. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35763. if (fastCheck) {
  35764. break;
  35765. }
  35766. }
  35767. }
  35768. return intersectInfo;
  35769. };
  35770. /** @hidden */
  35771. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  35772. var intersectInfo = null;
  35773. // Triangles test
  35774. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35775. var p0 = positions[indices[index]];
  35776. var p1 = positions[indices[index + 1]];
  35777. var p2 = positions[indices[index + 2]];
  35778. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35779. if (currentIntersectInfo) {
  35780. if (currentIntersectInfo.distance < 0) {
  35781. continue;
  35782. }
  35783. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35784. intersectInfo = currentIntersectInfo;
  35785. intersectInfo.faceId = index / 3;
  35786. if (fastCheck) {
  35787. break;
  35788. }
  35789. }
  35790. }
  35791. }
  35792. return intersectInfo;
  35793. };
  35794. /** @hidden */
  35795. SubMesh.prototype._rebuild = function () {
  35796. if (this._linesIndexBuffer) {
  35797. this._linesIndexBuffer = null;
  35798. }
  35799. };
  35800. // Clone
  35801. /**
  35802. * Creates a new submesh from the passed mesh
  35803. * @param newMesh defines the new hosting mesh
  35804. * @param newRenderingMesh defines an optional rendering mesh
  35805. * @returns the new submesh
  35806. */
  35807. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35808. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35809. if (!this.IsGlobal) {
  35810. var boundingInfo = this.getBoundingInfo();
  35811. if (!boundingInfo) {
  35812. return result;
  35813. }
  35814. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35815. }
  35816. return result;
  35817. };
  35818. // Dispose
  35819. /**
  35820. * Release associated resources
  35821. */
  35822. SubMesh.prototype.dispose = function () {
  35823. if (this._linesIndexBuffer) {
  35824. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35825. this._linesIndexBuffer = null;
  35826. }
  35827. // Remove from mesh
  35828. var index = this._mesh.subMeshes.indexOf(this);
  35829. this._mesh.subMeshes.splice(index, 1);
  35830. };
  35831. // Statics
  35832. /**
  35833. * Creates a new submesh from indices data
  35834. * @param materialIndex the index of the main mesh material
  35835. * @param startIndex the index where to start the copy in the mesh indices array
  35836. * @param indexCount the number of indices to copy then from the startIndex
  35837. * @param mesh the main mesh to create the submesh from
  35838. * @param renderingMesh the optional rendering mesh
  35839. * @returns a new submesh
  35840. */
  35841. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35842. var minVertexIndex = Number.MAX_VALUE;
  35843. var maxVertexIndex = -Number.MAX_VALUE;
  35844. renderingMesh = (renderingMesh || mesh);
  35845. var indices = renderingMesh.getIndices();
  35846. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35847. var vertexIndex = indices[index];
  35848. if (vertexIndex < minVertexIndex) {
  35849. minVertexIndex = vertexIndex;
  35850. }
  35851. if (vertexIndex > maxVertexIndex) {
  35852. maxVertexIndex = vertexIndex;
  35853. }
  35854. }
  35855. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35856. };
  35857. return SubMesh;
  35858. }(BaseSubMesh));
  35859. BABYLON.SubMesh = SubMesh;
  35860. })(BABYLON || (BABYLON = {}));
  35861. //# sourceMappingURL=babylon.subMesh.js.map
  35862. var __assign = (this && this.__assign) || function () {
  35863. __assign = Object.assign || function(t) {
  35864. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35865. s = arguments[i];
  35866. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35867. t[p] = s[p];
  35868. }
  35869. return t;
  35870. };
  35871. return __assign.apply(this, arguments);
  35872. };
  35873. var BABYLON;
  35874. (function (BABYLON) {
  35875. /**
  35876. * Manages the defines for the Material
  35877. */
  35878. var MaterialDefines = /** @class */ (function () {
  35879. function MaterialDefines() {
  35880. this._isDirty = true;
  35881. /** @hidden */
  35882. this._areLightsDirty = true;
  35883. /** @hidden */
  35884. this._areAttributesDirty = true;
  35885. /** @hidden */
  35886. this._areTexturesDirty = true;
  35887. /** @hidden */
  35888. this._areFresnelDirty = true;
  35889. /** @hidden */
  35890. this._areMiscDirty = true;
  35891. /** @hidden */
  35892. this._areImageProcessingDirty = true;
  35893. /** @hidden */
  35894. this._normals = false;
  35895. /** @hidden */
  35896. this._uvs = false;
  35897. /** @hidden */
  35898. this._needNormals = false;
  35899. /** @hidden */
  35900. this._needUVs = false;
  35901. }
  35902. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35903. /**
  35904. * Specifies if the material needs to be re-calculated
  35905. */
  35906. get: function () {
  35907. return this._isDirty;
  35908. },
  35909. enumerable: true,
  35910. configurable: true
  35911. });
  35912. /**
  35913. * Marks the material to indicate that it has been re-calculated
  35914. */
  35915. MaterialDefines.prototype.markAsProcessed = function () {
  35916. this._isDirty = false;
  35917. this._areAttributesDirty = false;
  35918. this._areTexturesDirty = false;
  35919. this._areFresnelDirty = false;
  35920. this._areLightsDirty = false;
  35921. this._areMiscDirty = false;
  35922. this._areImageProcessingDirty = false;
  35923. };
  35924. /**
  35925. * Marks the material to indicate that it needs to be re-calculated
  35926. */
  35927. MaterialDefines.prototype.markAsUnprocessed = function () {
  35928. this._isDirty = true;
  35929. };
  35930. /**
  35931. * Marks the material to indicate all of its defines need to be re-calculated
  35932. */
  35933. MaterialDefines.prototype.markAllAsDirty = function () {
  35934. this._areTexturesDirty = true;
  35935. this._areAttributesDirty = true;
  35936. this._areLightsDirty = true;
  35937. this._areFresnelDirty = true;
  35938. this._areMiscDirty = true;
  35939. this._areImageProcessingDirty = true;
  35940. this._isDirty = true;
  35941. };
  35942. /**
  35943. * Marks the material to indicate that image processing needs to be re-calculated
  35944. */
  35945. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35946. this._areImageProcessingDirty = true;
  35947. this._isDirty = true;
  35948. };
  35949. /**
  35950. * Marks the material to indicate the lights need to be re-calculated
  35951. */
  35952. MaterialDefines.prototype.markAsLightDirty = function () {
  35953. this._areLightsDirty = true;
  35954. this._isDirty = true;
  35955. };
  35956. /**
  35957. * Marks the attribute state as changed
  35958. */
  35959. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35960. this._areAttributesDirty = true;
  35961. this._isDirty = true;
  35962. };
  35963. /**
  35964. * Marks the texture state as changed
  35965. */
  35966. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35967. this._areTexturesDirty = true;
  35968. this._isDirty = true;
  35969. };
  35970. /**
  35971. * Marks the fresnel state as changed
  35972. */
  35973. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35974. this._areFresnelDirty = true;
  35975. this._isDirty = true;
  35976. };
  35977. /**
  35978. * Marks the misc state as changed
  35979. */
  35980. MaterialDefines.prototype.markAsMiscDirty = function () {
  35981. this._areMiscDirty = true;
  35982. this._isDirty = true;
  35983. };
  35984. /**
  35985. * Rebuilds the material defines
  35986. */
  35987. MaterialDefines.prototype.rebuild = function () {
  35988. if (this._keys) {
  35989. delete this._keys;
  35990. }
  35991. this._keys = [];
  35992. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35993. var key = _a[_i];
  35994. if (key[0] === "_") {
  35995. continue;
  35996. }
  35997. this._keys.push(key);
  35998. }
  35999. };
  36000. /**
  36001. * Specifies if two material defines are equal
  36002. * @param other - A material define instance to compare to
  36003. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36004. */
  36005. MaterialDefines.prototype.isEqual = function (other) {
  36006. if (this._keys.length !== other._keys.length) {
  36007. return false;
  36008. }
  36009. for (var index = 0; index < this._keys.length; index++) {
  36010. var prop = this._keys[index];
  36011. if (this[prop] !== other[prop]) {
  36012. return false;
  36013. }
  36014. }
  36015. return true;
  36016. };
  36017. /**
  36018. * Clones this instance's defines to another instance
  36019. * @param other - material defines to clone values to
  36020. */
  36021. MaterialDefines.prototype.cloneTo = function (other) {
  36022. if (this._keys.length !== other._keys.length) {
  36023. other._keys = this._keys.slice(0);
  36024. }
  36025. for (var index = 0; index < this._keys.length; index++) {
  36026. var prop = this._keys[index];
  36027. other[prop] = this[prop];
  36028. }
  36029. };
  36030. /**
  36031. * Resets the material define values
  36032. */
  36033. MaterialDefines.prototype.reset = function () {
  36034. for (var index = 0; index < this._keys.length; index++) {
  36035. var prop = this._keys[index];
  36036. var type = typeof this[prop];
  36037. switch (type) {
  36038. case "number":
  36039. this[prop] = 0;
  36040. break;
  36041. case "string":
  36042. this[prop] = "";
  36043. break;
  36044. default:
  36045. this[prop] = false;
  36046. break;
  36047. }
  36048. }
  36049. };
  36050. /**
  36051. * Converts the material define values to a string
  36052. * @returns - String of material define information
  36053. */
  36054. MaterialDefines.prototype.toString = function () {
  36055. var result = "";
  36056. for (var index = 0; index < this._keys.length; index++) {
  36057. var prop = this._keys[index];
  36058. var value = this[prop];
  36059. var type = typeof value;
  36060. switch (type) {
  36061. case "number":
  36062. case "string":
  36063. result += "#define " + prop + " " + value + "\n";
  36064. break;
  36065. default:
  36066. if (value) {
  36067. result += "#define " + prop + "\n";
  36068. }
  36069. break;
  36070. }
  36071. }
  36072. return result;
  36073. };
  36074. return MaterialDefines;
  36075. }());
  36076. BABYLON.MaterialDefines = MaterialDefines;
  36077. /**
  36078. * Base class for the main features of a material in Babylon.js
  36079. */
  36080. var Material = /** @class */ (function () {
  36081. /**
  36082. * Creates a material instance
  36083. * @param name defines the name of the material
  36084. * @param scene defines the scene to reference
  36085. * @param doNotAdd specifies if the material should be added to the scene
  36086. */
  36087. function Material(name, scene, doNotAdd) {
  36088. /**
  36089. * Specifies if the ready state should be checked on each call
  36090. */
  36091. this.checkReadyOnEveryCall = false;
  36092. /**
  36093. * Specifies if the ready state should be checked once
  36094. */
  36095. this.checkReadyOnlyOnce = false;
  36096. /**
  36097. * The state of the material
  36098. */
  36099. this.state = "";
  36100. /**
  36101. * The alpha value of the material
  36102. */
  36103. this._alpha = 1.0;
  36104. /**
  36105. * Specifies if back face culling is enabled
  36106. */
  36107. this._backFaceCulling = true;
  36108. /**
  36109. * Specifies if the material should be serialized
  36110. */
  36111. this.doNotSerialize = false;
  36112. /**
  36113. * Specifies if the effect should be stored on sub meshes
  36114. */
  36115. this.storeEffectOnSubMeshes = false;
  36116. /**
  36117. * An event triggered when the material is disposed
  36118. */
  36119. this.onDisposeObservable = new BABYLON.Observable();
  36120. /**
  36121. * Stores the value of the alpha mode
  36122. */
  36123. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36124. /**
  36125. * Stores the state of the need depth pre-pass value
  36126. */
  36127. this._needDepthPrePass = false;
  36128. /**
  36129. * Specifies if depth writing should be disabled
  36130. */
  36131. this.disableDepthWrite = false;
  36132. /**
  36133. * Specifies if depth writing should be forced
  36134. */
  36135. this.forceDepthWrite = false;
  36136. /**
  36137. * Specifies if there should be a separate pass for culling
  36138. */
  36139. this.separateCullingPass = false;
  36140. /**
  36141. * Stores the state specifing if fog should be enabled
  36142. */
  36143. this._fogEnabled = true;
  36144. /**
  36145. * Stores the size of points
  36146. */
  36147. this.pointSize = 1.0;
  36148. /**
  36149. * Stores the z offset value
  36150. */
  36151. this.zOffset = 0;
  36152. /**
  36153. * @hidden
  36154. * Specifies if the material was previously ready
  36155. */
  36156. this._wasPreviouslyReady = false;
  36157. /**
  36158. * Stores the fill mode state
  36159. */
  36160. this._fillMode = Material.TriangleFillMode;
  36161. this.name = name;
  36162. this.id = name || BABYLON.Tools.RandomId();
  36163. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36164. this.uniqueId = this._scene.getUniqueId();
  36165. if (this._scene.useRightHandedSystem) {
  36166. this.sideOrientation = Material.ClockWiseSideOrientation;
  36167. }
  36168. else {
  36169. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36170. }
  36171. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36172. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36173. if (!doNotAdd) {
  36174. this._scene.materials.push(this);
  36175. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  36176. }
  36177. }
  36178. Object.defineProperty(Material, "TriangleFillMode", {
  36179. /**
  36180. * Returns the triangle fill mode
  36181. */
  36182. get: function () {
  36183. return Material._TriangleFillMode;
  36184. },
  36185. enumerable: true,
  36186. configurable: true
  36187. });
  36188. Object.defineProperty(Material, "WireFrameFillMode", {
  36189. /**
  36190. * Returns the wireframe mode
  36191. */
  36192. get: function () {
  36193. return Material._WireFrameFillMode;
  36194. },
  36195. enumerable: true,
  36196. configurable: true
  36197. });
  36198. Object.defineProperty(Material, "PointFillMode", {
  36199. /**
  36200. * Returns the point fill mode
  36201. */
  36202. get: function () {
  36203. return Material._PointFillMode;
  36204. },
  36205. enumerable: true,
  36206. configurable: true
  36207. });
  36208. Object.defineProperty(Material, "PointListDrawMode", {
  36209. /**
  36210. * Returns the point list draw mode
  36211. */
  36212. get: function () {
  36213. return Material._PointListDrawMode;
  36214. },
  36215. enumerable: true,
  36216. configurable: true
  36217. });
  36218. Object.defineProperty(Material, "LineListDrawMode", {
  36219. /**
  36220. * Returns the line list draw mode
  36221. */
  36222. get: function () {
  36223. return Material._LineListDrawMode;
  36224. },
  36225. enumerable: true,
  36226. configurable: true
  36227. });
  36228. Object.defineProperty(Material, "LineLoopDrawMode", {
  36229. /**
  36230. * Returns the line loop draw mode
  36231. */
  36232. get: function () {
  36233. return Material._LineLoopDrawMode;
  36234. },
  36235. enumerable: true,
  36236. configurable: true
  36237. });
  36238. Object.defineProperty(Material, "LineStripDrawMode", {
  36239. /**
  36240. * Returns the line strip draw mode
  36241. */
  36242. get: function () {
  36243. return Material._LineStripDrawMode;
  36244. },
  36245. enumerable: true,
  36246. configurable: true
  36247. });
  36248. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36249. /**
  36250. * Returns the triangle strip draw mode
  36251. */
  36252. get: function () {
  36253. return Material._TriangleStripDrawMode;
  36254. },
  36255. enumerable: true,
  36256. configurable: true
  36257. });
  36258. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36259. /**
  36260. * Returns the triangle fan draw mode
  36261. */
  36262. get: function () {
  36263. return Material._TriangleFanDrawMode;
  36264. },
  36265. enumerable: true,
  36266. configurable: true
  36267. });
  36268. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36269. /**
  36270. * Returns the clock-wise side orientation
  36271. */
  36272. get: function () {
  36273. return Material._ClockWiseSideOrientation;
  36274. },
  36275. enumerable: true,
  36276. configurable: true
  36277. });
  36278. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36279. /**
  36280. * Returns the counter clock-wise side orientation
  36281. */
  36282. get: function () {
  36283. return Material._CounterClockWiseSideOrientation;
  36284. },
  36285. enumerable: true,
  36286. configurable: true
  36287. });
  36288. Object.defineProperty(Material.prototype, "alpha", {
  36289. /**
  36290. * Gets the alpha value of the material
  36291. */
  36292. get: function () {
  36293. return this._alpha;
  36294. },
  36295. /**
  36296. * Sets the alpha value of the material
  36297. */
  36298. set: function (value) {
  36299. if (this._alpha === value) {
  36300. return;
  36301. }
  36302. this._alpha = value;
  36303. this.markAsDirty(Material.MiscDirtyFlag);
  36304. },
  36305. enumerable: true,
  36306. configurable: true
  36307. });
  36308. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36309. /**
  36310. * Gets the back-face culling state
  36311. */
  36312. get: function () {
  36313. return this._backFaceCulling;
  36314. },
  36315. /**
  36316. * Sets the back-face culling state
  36317. */
  36318. set: function (value) {
  36319. if (this._backFaceCulling === value) {
  36320. return;
  36321. }
  36322. this._backFaceCulling = value;
  36323. this.markAsDirty(Material.TextureDirtyFlag);
  36324. },
  36325. enumerable: true,
  36326. configurable: true
  36327. });
  36328. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36329. /**
  36330. * Gets a boolean indicating that current material needs to register RTT
  36331. */
  36332. get: function () {
  36333. return false;
  36334. },
  36335. enumerable: true,
  36336. configurable: true
  36337. });
  36338. Object.defineProperty(Material.prototype, "onDispose", {
  36339. /**
  36340. * Called during a dispose event
  36341. */
  36342. set: function (callback) {
  36343. if (this._onDisposeObserver) {
  36344. this.onDisposeObservable.remove(this._onDisposeObserver);
  36345. }
  36346. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36347. },
  36348. enumerable: true,
  36349. configurable: true
  36350. });
  36351. Object.defineProperty(Material.prototype, "onBindObservable", {
  36352. /**
  36353. * An event triggered when the material is bound
  36354. */
  36355. get: function () {
  36356. if (!this._onBindObservable) {
  36357. this._onBindObservable = new BABYLON.Observable();
  36358. }
  36359. return this._onBindObservable;
  36360. },
  36361. enumerable: true,
  36362. configurable: true
  36363. });
  36364. Object.defineProperty(Material.prototype, "onBind", {
  36365. /**
  36366. * Called during a bind event
  36367. */
  36368. set: function (callback) {
  36369. if (this._onBindObserver) {
  36370. this.onBindObservable.remove(this._onBindObserver);
  36371. }
  36372. this._onBindObserver = this.onBindObservable.add(callback);
  36373. },
  36374. enumerable: true,
  36375. configurable: true
  36376. });
  36377. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36378. /**
  36379. * An event triggered when the material is unbound
  36380. */
  36381. get: function () {
  36382. if (!this._onUnBindObservable) {
  36383. this._onUnBindObservable = new BABYLON.Observable();
  36384. }
  36385. return this._onUnBindObservable;
  36386. },
  36387. enumerable: true,
  36388. configurable: true
  36389. });
  36390. Object.defineProperty(Material.prototype, "alphaMode", {
  36391. /**
  36392. * Gets the value of the alpha mode
  36393. */
  36394. get: function () {
  36395. return this._alphaMode;
  36396. },
  36397. /**
  36398. * Sets the value of the alpha mode.
  36399. *
  36400. * | Value | Type | Description |
  36401. * | --- | --- | --- |
  36402. * | 0 | ALPHA_DISABLE | |
  36403. * | 1 | ALPHA_ADD | |
  36404. * | 2 | ALPHA_COMBINE | |
  36405. * | 3 | ALPHA_SUBTRACT | |
  36406. * | 4 | ALPHA_MULTIPLY | |
  36407. * | 5 | ALPHA_MAXIMIZED | |
  36408. * | 6 | ALPHA_ONEONE | |
  36409. * | 7 | ALPHA_PREMULTIPLIED | |
  36410. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36411. * | 9 | ALPHA_INTERPOLATE | |
  36412. * | 10 | ALPHA_SCREENMODE | |
  36413. *
  36414. */
  36415. set: function (value) {
  36416. if (this._alphaMode === value) {
  36417. return;
  36418. }
  36419. this._alphaMode = value;
  36420. this.markAsDirty(Material.TextureDirtyFlag);
  36421. },
  36422. enumerable: true,
  36423. configurable: true
  36424. });
  36425. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36426. /**
  36427. * Gets the depth pre-pass value
  36428. */
  36429. get: function () {
  36430. return this._needDepthPrePass;
  36431. },
  36432. /**
  36433. * Sets the need depth pre-pass value
  36434. */
  36435. set: function (value) {
  36436. if (this._needDepthPrePass === value) {
  36437. return;
  36438. }
  36439. this._needDepthPrePass = value;
  36440. if (this._needDepthPrePass) {
  36441. this.checkReadyOnEveryCall = true;
  36442. }
  36443. },
  36444. enumerable: true,
  36445. configurable: true
  36446. });
  36447. Object.defineProperty(Material.prototype, "fogEnabled", {
  36448. /**
  36449. * Gets the value of the fog enabled state
  36450. */
  36451. get: function () {
  36452. return this._fogEnabled;
  36453. },
  36454. /**
  36455. * Sets the state for enabling fog
  36456. */
  36457. set: function (value) {
  36458. if (this._fogEnabled === value) {
  36459. return;
  36460. }
  36461. this._fogEnabled = value;
  36462. this.markAsDirty(Material.MiscDirtyFlag);
  36463. },
  36464. enumerable: true,
  36465. configurable: true
  36466. });
  36467. Object.defineProperty(Material.prototype, "wireframe", {
  36468. /**
  36469. * Gets a value specifying if wireframe mode is enabled
  36470. */
  36471. get: function () {
  36472. switch (this._fillMode) {
  36473. case Material.WireFrameFillMode:
  36474. case Material.LineListDrawMode:
  36475. case Material.LineLoopDrawMode:
  36476. case Material.LineStripDrawMode:
  36477. return true;
  36478. }
  36479. return this._scene.forceWireframe;
  36480. },
  36481. /**
  36482. * Sets the state of wireframe mode
  36483. */
  36484. set: function (value) {
  36485. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36486. },
  36487. enumerable: true,
  36488. configurable: true
  36489. });
  36490. Object.defineProperty(Material.prototype, "pointsCloud", {
  36491. /**
  36492. * Gets the value specifying if point clouds are enabled
  36493. */
  36494. get: function () {
  36495. switch (this._fillMode) {
  36496. case Material.PointFillMode:
  36497. case Material.PointListDrawMode:
  36498. return true;
  36499. }
  36500. return this._scene.forcePointsCloud;
  36501. },
  36502. /**
  36503. * Sets the state of point cloud mode
  36504. */
  36505. set: function (value) {
  36506. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36507. },
  36508. enumerable: true,
  36509. configurable: true
  36510. });
  36511. Object.defineProperty(Material.prototype, "fillMode", {
  36512. /**
  36513. * Gets the material fill mode
  36514. */
  36515. get: function () {
  36516. return this._fillMode;
  36517. },
  36518. /**
  36519. * Sets the material fill mode
  36520. */
  36521. set: function (value) {
  36522. if (this._fillMode === value) {
  36523. return;
  36524. }
  36525. this._fillMode = value;
  36526. this.markAsDirty(Material.MiscDirtyFlag);
  36527. },
  36528. enumerable: true,
  36529. configurable: true
  36530. });
  36531. /**
  36532. * Returns a string representation of the current material
  36533. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36534. * @returns a string with material information
  36535. */
  36536. Material.prototype.toString = function (fullDetails) {
  36537. var ret = "Name: " + this.name;
  36538. if (fullDetails) {
  36539. }
  36540. return ret;
  36541. };
  36542. /**
  36543. * Gets the class name of the material
  36544. * @returns a string with the class name of the material
  36545. */
  36546. Material.prototype.getClassName = function () {
  36547. return "Material";
  36548. };
  36549. Object.defineProperty(Material.prototype, "isFrozen", {
  36550. /**
  36551. * Specifies if updates for the material been locked
  36552. */
  36553. get: function () {
  36554. return this.checkReadyOnlyOnce;
  36555. },
  36556. enumerable: true,
  36557. configurable: true
  36558. });
  36559. /**
  36560. * Locks updates for the material
  36561. */
  36562. Material.prototype.freeze = function () {
  36563. this.checkReadyOnlyOnce = true;
  36564. };
  36565. /**
  36566. * Unlocks updates for the material
  36567. */
  36568. Material.prototype.unfreeze = function () {
  36569. this.checkReadyOnlyOnce = false;
  36570. };
  36571. /**
  36572. * Specifies if the material is ready to be used
  36573. * @param mesh defines the mesh to check
  36574. * @param useInstances specifies if instances should be used
  36575. * @returns a boolean indicating if the material is ready to be used
  36576. */
  36577. Material.prototype.isReady = function (mesh, useInstances) {
  36578. return true;
  36579. };
  36580. /**
  36581. * Specifies that the submesh is ready to be used
  36582. * @param mesh defines the mesh to check
  36583. * @param subMesh defines which submesh to check
  36584. * @param useInstances specifies that instances should be used
  36585. * @returns a boolean indicating that the submesh is ready or not
  36586. */
  36587. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36588. return false;
  36589. };
  36590. /**
  36591. * Returns the material effect
  36592. * @returns the effect associated with the material
  36593. */
  36594. Material.prototype.getEffect = function () {
  36595. return this._effect;
  36596. };
  36597. /**
  36598. * Returns the current scene
  36599. * @returns a Scene
  36600. */
  36601. Material.prototype.getScene = function () {
  36602. return this._scene;
  36603. };
  36604. /**
  36605. * Specifies if the material will require alpha blending
  36606. * @returns a boolean specifying if alpha blending is needed
  36607. */
  36608. Material.prototype.needAlphaBlending = function () {
  36609. return (this.alpha < 1.0);
  36610. };
  36611. /**
  36612. * Specifies if the mesh will require alpha blending
  36613. * @param mesh defines the mesh to check
  36614. * @returns a boolean specifying if alpha blending is needed for the mesh
  36615. */
  36616. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36617. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36618. };
  36619. /**
  36620. * Specifies if this material should be rendered in alpha test mode
  36621. * @returns a boolean specifying if an alpha test is needed.
  36622. */
  36623. Material.prototype.needAlphaTesting = function () {
  36624. return false;
  36625. };
  36626. /**
  36627. * Gets the texture used for the alpha test
  36628. * @returns the texture to use for alpha testing
  36629. */
  36630. Material.prototype.getAlphaTestTexture = function () {
  36631. return null;
  36632. };
  36633. /**
  36634. * Marks the material to indicate that it needs to be re-calculated
  36635. */
  36636. Material.prototype.markDirty = function () {
  36637. this._wasPreviouslyReady = false;
  36638. };
  36639. /** @hidden */
  36640. Material.prototype._preBind = function (effect, overrideOrientation) {
  36641. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36642. var engine = this._scene.getEngine();
  36643. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36644. var reverse = orientation === Material.ClockWiseSideOrientation;
  36645. engine.enableEffect(effect ? effect : this._effect);
  36646. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36647. return reverse;
  36648. };
  36649. /**
  36650. * Binds the material to the mesh
  36651. * @param world defines the world transformation matrix
  36652. * @param mesh defines the mesh to bind the material to
  36653. */
  36654. Material.prototype.bind = function (world, mesh) {
  36655. };
  36656. /**
  36657. * Binds the submesh to the material
  36658. * @param world defines the world transformation matrix
  36659. * @param mesh defines the mesh containing the submesh
  36660. * @param subMesh defines the submesh to bind the material to
  36661. */
  36662. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36663. };
  36664. /**
  36665. * Binds the world matrix to the material
  36666. * @param world defines the world transformation matrix
  36667. */
  36668. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36669. };
  36670. /**
  36671. * Binds the scene's uniform buffer to the effect.
  36672. * @param effect defines the effect to bind to the scene uniform buffer
  36673. * @param sceneUbo defines the uniform buffer storing scene data
  36674. */
  36675. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36676. sceneUbo.bindToEffect(effect, "Scene");
  36677. };
  36678. /**
  36679. * Binds the view matrix to the effect
  36680. * @param effect defines the effect to bind the view matrix to
  36681. */
  36682. Material.prototype.bindView = function (effect) {
  36683. if (!this._useUBO) {
  36684. effect.setMatrix("view", this.getScene().getViewMatrix());
  36685. }
  36686. else {
  36687. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36688. }
  36689. };
  36690. /**
  36691. * Binds the view projection matrix to the effect
  36692. * @param effect defines the effect to bind the view projection matrix to
  36693. */
  36694. Material.prototype.bindViewProjection = function (effect) {
  36695. if (!this._useUBO) {
  36696. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36697. }
  36698. else {
  36699. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36700. }
  36701. };
  36702. /**
  36703. * Specifies if material alpha testing should be turned on for the mesh
  36704. * @param mesh defines the mesh to check
  36705. */
  36706. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36707. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36708. };
  36709. /**
  36710. * Processes to execute after binding the material to a mesh
  36711. * @param mesh defines the rendered mesh
  36712. */
  36713. Material.prototype._afterBind = function (mesh) {
  36714. this._scene._cachedMaterial = this;
  36715. if (mesh) {
  36716. this._scene._cachedVisibility = mesh.visibility;
  36717. }
  36718. else {
  36719. this._scene._cachedVisibility = 1;
  36720. }
  36721. if (this._onBindObservable && mesh) {
  36722. this._onBindObservable.notifyObservers(mesh);
  36723. }
  36724. if (this.disableDepthWrite) {
  36725. var engine = this._scene.getEngine();
  36726. this._cachedDepthWriteState = engine.getDepthWrite();
  36727. engine.setDepthWrite(false);
  36728. }
  36729. };
  36730. /**
  36731. * Unbinds the material from the mesh
  36732. */
  36733. Material.prototype.unbind = function () {
  36734. if (this._onUnBindObservable) {
  36735. this._onUnBindObservable.notifyObservers(this);
  36736. }
  36737. if (this.disableDepthWrite) {
  36738. var engine = this._scene.getEngine();
  36739. engine.setDepthWrite(this._cachedDepthWriteState);
  36740. }
  36741. };
  36742. /**
  36743. * Gets the active textures from the material
  36744. * @returns an array of textures
  36745. */
  36746. Material.prototype.getActiveTextures = function () {
  36747. return [];
  36748. };
  36749. /**
  36750. * Specifies if the material uses a texture
  36751. * @param texture defines the texture to check against the material
  36752. * @returns a boolean specifying if the material uses the texture
  36753. */
  36754. Material.prototype.hasTexture = function (texture) {
  36755. return false;
  36756. };
  36757. /**
  36758. * Makes a duplicate of the material, and gives it a new name
  36759. * @param name defines the new name for the duplicated material
  36760. * @returns the cloned material
  36761. */
  36762. Material.prototype.clone = function (name) {
  36763. return null;
  36764. };
  36765. /**
  36766. * Gets the meshes bound to the material
  36767. * @returns an array of meshes bound to the material
  36768. */
  36769. Material.prototype.getBindedMeshes = function () {
  36770. var result = new Array();
  36771. for (var index = 0; index < this._scene.meshes.length; index++) {
  36772. var mesh = this._scene.meshes[index];
  36773. if (mesh.material === this) {
  36774. result.push(mesh);
  36775. }
  36776. }
  36777. return result;
  36778. };
  36779. /**
  36780. * Force shader compilation
  36781. * @param mesh defines the mesh associated with this material
  36782. * @param onCompiled defines a function to execute once the material is compiled
  36783. * @param options defines the options to configure the compilation
  36784. */
  36785. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36786. var _this = this;
  36787. var localOptions = __assign({ clipPlane: false }, options);
  36788. var subMesh = new BABYLON.BaseSubMesh();
  36789. var scene = this.getScene();
  36790. var checkReady = function () {
  36791. if (!_this._scene || !_this._scene.getEngine()) {
  36792. return;
  36793. }
  36794. if (subMesh._materialDefines) {
  36795. subMesh._materialDefines._renderId = -1;
  36796. }
  36797. var clipPlaneState = scene.clipPlane;
  36798. if (localOptions.clipPlane) {
  36799. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36800. }
  36801. if (_this.storeEffectOnSubMeshes) {
  36802. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36803. if (onCompiled) {
  36804. onCompiled(_this);
  36805. }
  36806. }
  36807. else {
  36808. setTimeout(checkReady, 16);
  36809. }
  36810. }
  36811. else {
  36812. if (_this.isReady(mesh)) {
  36813. if (onCompiled) {
  36814. onCompiled(_this);
  36815. }
  36816. }
  36817. else {
  36818. setTimeout(checkReady, 16);
  36819. }
  36820. }
  36821. if (localOptions.clipPlane) {
  36822. scene.clipPlane = clipPlaneState;
  36823. }
  36824. };
  36825. checkReady();
  36826. };
  36827. /**
  36828. * Force shader compilation
  36829. * @param mesh defines the mesh that will use this material
  36830. * @param options defines additional options for compiling the shaders
  36831. * @returns a promise that resolves when the compilation completes
  36832. */
  36833. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36834. var _this = this;
  36835. return new Promise(function (resolve) {
  36836. _this.forceCompilation(mesh, function () {
  36837. resolve();
  36838. }, options);
  36839. });
  36840. };
  36841. /**
  36842. * Marks a define in the material to indicate that it needs to be re-computed
  36843. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36844. */
  36845. Material.prototype.markAsDirty = function (flag) {
  36846. if (flag & Material.TextureDirtyFlag) {
  36847. this._markAllSubMeshesAsTexturesDirty();
  36848. }
  36849. if (flag & Material.LightDirtyFlag) {
  36850. this._markAllSubMeshesAsLightsDirty();
  36851. }
  36852. if (flag & Material.FresnelDirtyFlag) {
  36853. this._markAllSubMeshesAsFresnelDirty();
  36854. }
  36855. if (flag & Material.AttributesDirtyFlag) {
  36856. this._markAllSubMeshesAsAttributesDirty();
  36857. }
  36858. if (flag & Material.MiscDirtyFlag) {
  36859. this._markAllSubMeshesAsMiscDirty();
  36860. }
  36861. this.getScene().resetCachedMaterial();
  36862. };
  36863. /**
  36864. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36865. * @param func defines a function which checks material defines against the submeshes
  36866. */
  36867. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36868. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36869. var mesh = _a[_i];
  36870. if (!mesh.subMeshes) {
  36871. continue;
  36872. }
  36873. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36874. var subMesh = _c[_b];
  36875. if (subMesh.getMaterial() !== this) {
  36876. continue;
  36877. }
  36878. if (!subMesh._materialDefines) {
  36879. continue;
  36880. }
  36881. func(subMesh._materialDefines);
  36882. }
  36883. }
  36884. };
  36885. /**
  36886. * Indicates that image processing needs to be re-calculated for all submeshes
  36887. */
  36888. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36889. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36890. };
  36891. /**
  36892. * Indicates that textures need to be re-calculated for all submeshes
  36893. */
  36894. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36895. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36896. };
  36897. /**
  36898. * Indicates that fresnel needs to be re-calculated for all submeshes
  36899. */
  36900. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36901. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36902. };
  36903. /**
  36904. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36905. */
  36906. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36907. this._markAllSubMeshesAsDirty(function (defines) {
  36908. defines.markAsFresnelDirty();
  36909. defines.markAsMiscDirty();
  36910. });
  36911. };
  36912. /**
  36913. * Indicates that lights need to be re-calculated for all submeshes
  36914. */
  36915. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36916. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36917. };
  36918. /**
  36919. * Indicates that attributes need to be re-calculated for all submeshes
  36920. */
  36921. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36922. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36923. };
  36924. /**
  36925. * Indicates that misc needs to be re-calculated for all submeshes
  36926. */
  36927. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36928. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36929. };
  36930. /**
  36931. * Indicates that textures and misc need to be re-calculated for all submeshes
  36932. */
  36933. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36934. this._markAllSubMeshesAsDirty(function (defines) {
  36935. defines.markAsTexturesDirty();
  36936. defines.markAsMiscDirty();
  36937. });
  36938. };
  36939. /**
  36940. * Disposes the material
  36941. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36942. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36943. */
  36944. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36945. // Animations
  36946. this.getScene().stopAnimation(this);
  36947. this.getScene().freeProcessedMaterials();
  36948. // Remove from scene
  36949. var index = this._scene.materials.indexOf(this);
  36950. if (index >= 0) {
  36951. this._scene.materials.splice(index, 1);
  36952. }
  36953. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36954. // Remove from meshes
  36955. for (index = 0; index < this._scene.meshes.length; index++) {
  36956. var mesh = this._scene.meshes[index];
  36957. if (mesh.material === this) {
  36958. mesh.material = null;
  36959. if (mesh.geometry) {
  36960. var geometry = (mesh.geometry);
  36961. if (this.storeEffectOnSubMeshes) {
  36962. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36963. var subMesh = _a[_i];
  36964. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36965. if (forceDisposeEffect && subMesh._materialEffect) {
  36966. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36967. }
  36968. }
  36969. }
  36970. else {
  36971. geometry._releaseVertexArrayObject(this._effect);
  36972. }
  36973. }
  36974. }
  36975. }
  36976. this._uniformBuffer.dispose();
  36977. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36978. if (forceDisposeEffect && this._effect) {
  36979. if (!this.storeEffectOnSubMeshes) {
  36980. this._scene.getEngine()._releaseEffect(this._effect);
  36981. }
  36982. this._effect = null;
  36983. }
  36984. // Callback
  36985. this.onDisposeObservable.notifyObservers(this);
  36986. this.onDisposeObservable.clear();
  36987. if (this._onBindObservable) {
  36988. this._onBindObservable.clear();
  36989. }
  36990. if (this._onUnBindObservable) {
  36991. this._onUnBindObservable.clear();
  36992. }
  36993. };
  36994. /**
  36995. * Serializes this material
  36996. * @returns the serialized material object
  36997. */
  36998. Material.prototype.serialize = function () {
  36999. return BABYLON.SerializationHelper.Serialize(this);
  37000. };
  37001. /**
  37002. * Creates a MultiMaterial from parsed MultiMaterial data.
  37003. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37004. * @param scene defines the hosting scene
  37005. * @returns a new MultiMaterial
  37006. */
  37007. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37008. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37009. multiMaterial.id = parsedMultiMaterial.id;
  37010. if (BABYLON.Tags) {
  37011. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37012. }
  37013. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37014. var subMatId = parsedMultiMaterial.materials[matIndex];
  37015. if (subMatId) {
  37016. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37017. }
  37018. else {
  37019. multiMaterial.subMaterials.push(null);
  37020. }
  37021. }
  37022. return multiMaterial;
  37023. };
  37024. /**
  37025. * Creates a material from parsed material data
  37026. * @param parsedMaterial defines parsed material data
  37027. * @param scene defines the hosting scene
  37028. * @param rootUrl defines the root URL to use to load textures
  37029. * @returns a new material
  37030. */
  37031. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37032. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37033. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37034. }
  37035. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37036. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37037. if (!BABYLON.LegacyPBRMaterial) {
  37038. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37039. return;
  37040. }
  37041. }
  37042. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37043. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37044. };
  37045. // Triangle views
  37046. Material._TriangleFillMode = 0;
  37047. Material._WireFrameFillMode = 1;
  37048. Material._PointFillMode = 2;
  37049. // Draw modes
  37050. Material._PointListDrawMode = 3;
  37051. Material._LineListDrawMode = 4;
  37052. Material._LineLoopDrawMode = 5;
  37053. Material._LineStripDrawMode = 6;
  37054. Material._TriangleStripDrawMode = 7;
  37055. Material._TriangleFanDrawMode = 8;
  37056. /**
  37057. * Stores the clock-wise side orientation
  37058. */
  37059. Material._ClockWiseSideOrientation = 0;
  37060. /**
  37061. * Stores the counter clock-wise side orientation
  37062. */
  37063. Material._CounterClockWiseSideOrientation = 1;
  37064. /**
  37065. * The dirty texture flag value
  37066. */
  37067. Material.TextureDirtyFlag = 1;
  37068. /**
  37069. * The dirty light flag value
  37070. */
  37071. Material.LightDirtyFlag = 2;
  37072. /**
  37073. * The dirty fresnel flag value
  37074. */
  37075. Material.FresnelDirtyFlag = 4;
  37076. /**
  37077. * The dirty attribute flag value
  37078. */
  37079. Material.AttributesDirtyFlag = 8;
  37080. /**
  37081. * The dirty misc flag value
  37082. */
  37083. Material.MiscDirtyFlag = 16;
  37084. /**
  37085. * The all dirty flag value
  37086. */
  37087. Material.AllDirtyFlag = 31;
  37088. __decorate([
  37089. BABYLON.serialize()
  37090. ], Material.prototype, "id", void 0);
  37091. __decorate([
  37092. BABYLON.serialize()
  37093. ], Material.prototype, "uniqueId", void 0);
  37094. __decorate([
  37095. BABYLON.serialize()
  37096. ], Material.prototype, "name", void 0);
  37097. __decorate([
  37098. BABYLON.serialize()
  37099. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37100. __decorate([
  37101. BABYLON.serialize()
  37102. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37103. __decorate([
  37104. BABYLON.serialize()
  37105. ], Material.prototype, "state", void 0);
  37106. __decorate([
  37107. BABYLON.serialize("alpha")
  37108. ], Material.prototype, "_alpha", void 0);
  37109. __decorate([
  37110. BABYLON.serialize("backFaceCulling")
  37111. ], Material.prototype, "_backFaceCulling", void 0);
  37112. __decorate([
  37113. BABYLON.serialize()
  37114. ], Material.prototype, "sideOrientation", void 0);
  37115. __decorate([
  37116. BABYLON.serialize("alphaMode")
  37117. ], Material.prototype, "_alphaMode", void 0);
  37118. __decorate([
  37119. BABYLON.serialize()
  37120. ], Material.prototype, "_needDepthPrePass", void 0);
  37121. __decorate([
  37122. BABYLON.serialize()
  37123. ], Material.prototype, "disableDepthWrite", void 0);
  37124. __decorate([
  37125. BABYLON.serialize()
  37126. ], Material.prototype, "forceDepthWrite", void 0);
  37127. __decorate([
  37128. BABYLON.serialize()
  37129. ], Material.prototype, "separateCullingPass", void 0);
  37130. __decorate([
  37131. BABYLON.serialize("fogEnabled")
  37132. ], Material.prototype, "_fogEnabled", void 0);
  37133. __decorate([
  37134. BABYLON.serialize()
  37135. ], Material.prototype, "pointSize", void 0);
  37136. __decorate([
  37137. BABYLON.serialize()
  37138. ], Material.prototype, "zOffset", void 0);
  37139. __decorate([
  37140. BABYLON.serialize()
  37141. ], Material.prototype, "wireframe", null);
  37142. __decorate([
  37143. BABYLON.serialize()
  37144. ], Material.prototype, "pointsCloud", null);
  37145. __decorate([
  37146. BABYLON.serialize()
  37147. ], Material.prototype, "fillMode", null);
  37148. return Material;
  37149. }());
  37150. BABYLON.Material = Material;
  37151. })(BABYLON || (BABYLON = {}));
  37152. //# sourceMappingURL=babylon.material.js.map
  37153. var BABYLON;
  37154. (function (BABYLON) {
  37155. /**
  37156. * Uniform buffer objects.
  37157. *
  37158. * Handles blocks of uniform on the GPU.
  37159. *
  37160. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37161. *
  37162. * For more information, please refer to :
  37163. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37164. */
  37165. var UniformBuffer = /** @class */ (function () {
  37166. /**
  37167. * Instantiates a new Uniform buffer objects.
  37168. *
  37169. * Handles blocks of uniform on the GPU.
  37170. *
  37171. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37172. *
  37173. * For more information, please refer to :
  37174. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37175. * @param engine Define the engine the buffer is associated with
  37176. * @param data Define the data contained in the buffer
  37177. * @param dynamic Define if the buffer is updatable
  37178. */
  37179. function UniformBuffer(engine, data, dynamic) {
  37180. this._engine = engine;
  37181. this._noUBO = !engine.supportsUniformBuffers;
  37182. this._dynamic = dynamic;
  37183. this._data = data || [];
  37184. this._uniformLocations = {};
  37185. this._uniformSizes = {};
  37186. this._uniformLocationPointer = 0;
  37187. this._needSync = false;
  37188. if (this._noUBO) {
  37189. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37190. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37191. this.updateFloat = this._updateFloatForEffect;
  37192. this.updateFloat2 = this._updateFloat2ForEffect;
  37193. this.updateFloat3 = this._updateFloat3ForEffect;
  37194. this.updateFloat4 = this._updateFloat4ForEffect;
  37195. this.updateMatrix = this._updateMatrixForEffect;
  37196. this.updateVector3 = this._updateVector3ForEffect;
  37197. this.updateVector4 = this._updateVector4ForEffect;
  37198. this.updateColor3 = this._updateColor3ForEffect;
  37199. this.updateColor4 = this._updateColor4ForEffect;
  37200. }
  37201. else {
  37202. this._engine._uniformBuffers.push(this);
  37203. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37204. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37205. this.updateFloat = this._updateFloatForUniform;
  37206. this.updateFloat2 = this._updateFloat2ForUniform;
  37207. this.updateFloat3 = this._updateFloat3ForUniform;
  37208. this.updateFloat4 = this._updateFloat4ForUniform;
  37209. this.updateMatrix = this._updateMatrixForUniform;
  37210. this.updateVector3 = this._updateVector3ForUniform;
  37211. this.updateVector4 = this._updateVector4ForUniform;
  37212. this.updateColor3 = this._updateColor3ForUniform;
  37213. this.updateColor4 = this._updateColor4ForUniform;
  37214. }
  37215. }
  37216. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37217. /**
  37218. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37219. * or just falling back on setUniformXXX calls.
  37220. */
  37221. get: function () {
  37222. return !this._noUBO;
  37223. },
  37224. enumerable: true,
  37225. configurable: true
  37226. });
  37227. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37228. /**
  37229. * Indicates if the WebGL underlying uniform buffer is in sync
  37230. * with the javascript cache data.
  37231. */
  37232. get: function () {
  37233. return !this._needSync;
  37234. },
  37235. enumerable: true,
  37236. configurable: true
  37237. });
  37238. /**
  37239. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37240. * Also, a dynamic UniformBuffer will disable cache verification and always
  37241. * update the underlying WebGL uniform buffer to the GPU.
  37242. * @returns if Dynamic, otherwise false
  37243. */
  37244. UniformBuffer.prototype.isDynamic = function () {
  37245. return this._dynamic !== undefined;
  37246. };
  37247. /**
  37248. * The data cache on JS side.
  37249. * @returns the underlying data as a float array
  37250. */
  37251. UniformBuffer.prototype.getData = function () {
  37252. return this._bufferData;
  37253. };
  37254. /**
  37255. * The underlying WebGL Uniform buffer.
  37256. * @returns the webgl buffer
  37257. */
  37258. UniformBuffer.prototype.getBuffer = function () {
  37259. return this._buffer;
  37260. };
  37261. /**
  37262. * std140 layout specifies how to align data within an UBO structure.
  37263. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37264. * for specs.
  37265. */
  37266. UniformBuffer.prototype._fillAlignment = function (size) {
  37267. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37268. // and 4x4 matrices
  37269. // TODO : change if other types are used
  37270. var alignment;
  37271. if (size <= 2) {
  37272. alignment = size;
  37273. }
  37274. else {
  37275. alignment = 4;
  37276. }
  37277. if ((this._uniformLocationPointer % alignment) !== 0) {
  37278. var oldPointer = this._uniformLocationPointer;
  37279. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37280. var diff = this._uniformLocationPointer - oldPointer;
  37281. for (var i = 0; i < diff; i++) {
  37282. this._data.push(0);
  37283. }
  37284. }
  37285. };
  37286. /**
  37287. * Adds an uniform in the buffer.
  37288. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37289. * for the layout to be correct !
  37290. * @param name Name of the uniform, as used in the uniform block in the shader.
  37291. * @param size Data size, or data directly.
  37292. */
  37293. UniformBuffer.prototype.addUniform = function (name, size) {
  37294. if (this._noUBO) {
  37295. return;
  37296. }
  37297. if (this._uniformLocations[name] !== undefined) {
  37298. // Already existing uniform
  37299. return;
  37300. }
  37301. // This function must be called in the order of the shader layout !
  37302. // size can be the size of the uniform, or data directly
  37303. var data;
  37304. if (size instanceof Array) {
  37305. data = size;
  37306. size = data.length;
  37307. }
  37308. else {
  37309. size = size;
  37310. data = [];
  37311. // Fill with zeros
  37312. for (var i = 0; i < size; i++) {
  37313. data.push(0);
  37314. }
  37315. }
  37316. this._fillAlignment(size);
  37317. this._uniformSizes[name] = size;
  37318. this._uniformLocations[name] = this._uniformLocationPointer;
  37319. this._uniformLocationPointer += size;
  37320. for (var i = 0; i < size; i++) {
  37321. this._data.push(data[i]);
  37322. }
  37323. this._needSync = true;
  37324. };
  37325. /**
  37326. * Adds a Matrix 4x4 to the uniform buffer.
  37327. * @param name Name of the uniform, as used in the uniform block in the shader.
  37328. * @param mat A 4x4 matrix.
  37329. */
  37330. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37331. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37332. };
  37333. /**
  37334. * Adds a vec2 to the uniform buffer.
  37335. * @param name Name of the uniform, as used in the uniform block in the shader.
  37336. * @param x Define the x component value of the vec2
  37337. * @param y Define the y component value of the vec2
  37338. */
  37339. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37340. var temp = [x, y];
  37341. this.addUniform(name, temp);
  37342. };
  37343. /**
  37344. * Adds a vec3 to the uniform buffer.
  37345. * @param name Name of the uniform, as used in the uniform block in the shader.
  37346. * @param x Define the x component value of the vec3
  37347. * @param y Define the y component value of the vec3
  37348. * @param z Define the z component value of the vec3
  37349. */
  37350. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37351. var temp = [x, y, z];
  37352. this.addUniform(name, temp);
  37353. };
  37354. /**
  37355. * Adds a vec3 to the uniform buffer.
  37356. * @param name Name of the uniform, as used in the uniform block in the shader.
  37357. * @param color Define the vec3 from a Color
  37358. */
  37359. UniformBuffer.prototype.addColor3 = function (name, color) {
  37360. var temp = new Array();
  37361. color.toArray(temp);
  37362. this.addUniform(name, temp);
  37363. };
  37364. /**
  37365. * Adds a vec4 to the uniform buffer.
  37366. * @param name Name of the uniform, as used in the uniform block in the shader.
  37367. * @param color Define the rgb components from a Color
  37368. * @param alpha Define the a component of the vec4
  37369. */
  37370. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37371. var temp = new Array();
  37372. color.toArray(temp);
  37373. temp.push(alpha);
  37374. this.addUniform(name, temp);
  37375. };
  37376. /**
  37377. * Adds a vec3 to the uniform buffer.
  37378. * @param name Name of the uniform, as used in the uniform block in the shader.
  37379. * @param vector Define the vec3 components from a Vector
  37380. */
  37381. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37382. var temp = new Array();
  37383. vector.toArray(temp);
  37384. this.addUniform(name, temp);
  37385. };
  37386. /**
  37387. * Adds a Matrix 3x3 to the uniform buffer.
  37388. * @param name Name of the uniform, as used in the uniform block in the shader.
  37389. */
  37390. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37391. this.addUniform(name, 12);
  37392. };
  37393. /**
  37394. * Adds a Matrix 2x2 to the uniform buffer.
  37395. * @param name Name of the uniform, as used in the uniform block in the shader.
  37396. */
  37397. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37398. this.addUniform(name, 8);
  37399. };
  37400. /**
  37401. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37402. */
  37403. UniformBuffer.prototype.create = function () {
  37404. if (this._noUBO) {
  37405. return;
  37406. }
  37407. if (this._buffer) {
  37408. return; // nothing to do
  37409. }
  37410. // See spec, alignment must be filled as a vec4
  37411. this._fillAlignment(4);
  37412. this._bufferData = new Float32Array(this._data);
  37413. this._rebuild();
  37414. this._needSync = true;
  37415. };
  37416. /** @hidden */
  37417. UniformBuffer.prototype._rebuild = function () {
  37418. if (this._noUBO) {
  37419. return;
  37420. }
  37421. if (this._dynamic) {
  37422. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37423. }
  37424. else {
  37425. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37426. }
  37427. };
  37428. /**
  37429. * Updates the WebGL Uniform Buffer on the GPU.
  37430. * If the `dynamic` flag is set to true, no cache comparison is done.
  37431. * Otherwise, the buffer will be updated only if the cache differs.
  37432. */
  37433. UniformBuffer.prototype.update = function () {
  37434. if (!this._buffer) {
  37435. this.create();
  37436. return;
  37437. }
  37438. if (!this._dynamic && !this._needSync) {
  37439. return;
  37440. }
  37441. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37442. this._needSync = false;
  37443. };
  37444. /**
  37445. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37446. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37447. * @param data Define the flattened data
  37448. * @param size Define the size of the data.
  37449. */
  37450. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37451. var location = this._uniformLocations[uniformName];
  37452. if (location === undefined) {
  37453. if (this._buffer) {
  37454. // Cannot add an uniform if the buffer is already created
  37455. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37456. return;
  37457. }
  37458. this.addUniform(uniformName, size);
  37459. location = this._uniformLocations[uniformName];
  37460. }
  37461. if (!this._buffer) {
  37462. this.create();
  37463. }
  37464. if (!this._dynamic) {
  37465. // Cache for static uniform buffers
  37466. var changed = false;
  37467. for (var i = 0; i < size; i++) {
  37468. if (this._bufferData[location + i] !== data[i]) {
  37469. changed = true;
  37470. this._bufferData[location + i] = data[i];
  37471. }
  37472. }
  37473. this._needSync = this._needSync || changed;
  37474. }
  37475. else {
  37476. // No cache for dynamic
  37477. for (var i = 0; i < size; i++) {
  37478. this._bufferData[location + i] = data[i];
  37479. }
  37480. }
  37481. };
  37482. // Update methods
  37483. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37484. // To match std140, matrix must be realigned
  37485. for (var i = 0; i < 3; i++) {
  37486. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37487. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37488. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37489. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37490. }
  37491. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37492. };
  37493. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37494. this._currentEffect.setMatrix3x3(name, matrix);
  37495. };
  37496. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37497. this._currentEffect.setMatrix2x2(name, matrix);
  37498. };
  37499. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37500. // To match std140, matrix must be realigned
  37501. for (var i = 0; i < 2; i++) {
  37502. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37503. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37504. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37505. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37506. }
  37507. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37508. };
  37509. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37510. this._currentEffect.setFloat(name, x);
  37511. };
  37512. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37513. UniformBuffer._tempBuffer[0] = x;
  37514. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37515. };
  37516. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37517. if (suffix === void 0) { suffix = ""; }
  37518. this._currentEffect.setFloat2(name + suffix, x, y);
  37519. };
  37520. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37521. if (suffix === void 0) { suffix = ""; }
  37522. UniformBuffer._tempBuffer[0] = x;
  37523. UniformBuffer._tempBuffer[1] = y;
  37524. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37525. };
  37526. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37527. if (suffix === void 0) { suffix = ""; }
  37528. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37529. };
  37530. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37531. if (suffix === void 0) { suffix = ""; }
  37532. UniformBuffer._tempBuffer[0] = x;
  37533. UniformBuffer._tempBuffer[1] = y;
  37534. UniformBuffer._tempBuffer[2] = z;
  37535. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37536. };
  37537. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37538. if (suffix === void 0) { suffix = ""; }
  37539. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37540. };
  37541. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37542. if (suffix === void 0) { suffix = ""; }
  37543. UniformBuffer._tempBuffer[0] = x;
  37544. UniformBuffer._tempBuffer[1] = y;
  37545. UniformBuffer._tempBuffer[2] = z;
  37546. UniformBuffer._tempBuffer[3] = w;
  37547. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37548. };
  37549. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37550. this._currentEffect.setMatrix(name, mat);
  37551. };
  37552. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37553. this.updateUniform(name, mat.toArray(), 16);
  37554. };
  37555. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37556. this._currentEffect.setVector3(name, vector);
  37557. };
  37558. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37559. vector.toArray(UniformBuffer._tempBuffer);
  37560. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37561. };
  37562. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37563. this._currentEffect.setVector4(name, vector);
  37564. };
  37565. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37566. vector.toArray(UniformBuffer._tempBuffer);
  37567. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37568. };
  37569. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37570. if (suffix === void 0) { suffix = ""; }
  37571. this._currentEffect.setColor3(name + suffix, color);
  37572. };
  37573. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37574. if (suffix === void 0) { suffix = ""; }
  37575. color.toArray(UniformBuffer._tempBuffer);
  37576. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37577. };
  37578. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37579. if (suffix === void 0) { suffix = ""; }
  37580. this._currentEffect.setColor4(name + suffix, color, alpha);
  37581. };
  37582. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37583. if (suffix === void 0) { suffix = ""; }
  37584. color.toArray(UniformBuffer._tempBuffer);
  37585. UniformBuffer._tempBuffer[3] = alpha;
  37586. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37587. };
  37588. /**
  37589. * Sets a sampler uniform on the effect.
  37590. * @param name Define the name of the sampler.
  37591. * @param texture Define the texture to set in the sampler
  37592. */
  37593. UniformBuffer.prototype.setTexture = function (name, texture) {
  37594. this._currentEffect.setTexture(name, texture);
  37595. };
  37596. /**
  37597. * Directly updates the value of the uniform in the cache AND on the GPU.
  37598. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37599. * @param data Define the flattened data
  37600. */
  37601. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37602. this.updateUniform(uniformName, data, data.length);
  37603. this.update();
  37604. };
  37605. /**
  37606. * Binds this uniform buffer to an effect.
  37607. * @param effect Define the effect to bind the buffer to
  37608. * @param name Name of the uniform block in the shader.
  37609. */
  37610. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37611. this._currentEffect = effect;
  37612. if (this._noUBO || !this._buffer) {
  37613. return;
  37614. }
  37615. effect.bindUniformBuffer(this._buffer, name);
  37616. };
  37617. /**
  37618. * Disposes the uniform buffer.
  37619. */
  37620. UniformBuffer.prototype.dispose = function () {
  37621. if (this._noUBO) {
  37622. return;
  37623. }
  37624. var index = this._engine._uniformBuffers.indexOf(this);
  37625. if (index !== -1) {
  37626. this._engine._uniformBuffers.splice(index, 1);
  37627. }
  37628. if (!this._buffer) {
  37629. return;
  37630. }
  37631. if (this._engine._releaseBuffer(this._buffer)) {
  37632. this._buffer = null;
  37633. }
  37634. };
  37635. // Pool for avoiding memory leaks
  37636. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37637. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37638. return UniformBuffer;
  37639. }());
  37640. BABYLON.UniformBuffer = UniformBuffer;
  37641. })(BABYLON || (BABYLON = {}));
  37642. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37643. var BABYLON;
  37644. (function (BABYLON) {
  37645. /**
  37646. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37647. */
  37648. var VertexData = /** @class */ (function () {
  37649. function VertexData() {
  37650. }
  37651. /**
  37652. * Uses the passed data array to set the set the values for the specified kind of data
  37653. * @param data a linear array of floating numbers
  37654. * @param kind the type of data that is being set, eg positions, colors etc
  37655. */
  37656. VertexData.prototype.set = function (data, kind) {
  37657. switch (kind) {
  37658. case BABYLON.VertexBuffer.PositionKind:
  37659. this.positions = data;
  37660. break;
  37661. case BABYLON.VertexBuffer.NormalKind:
  37662. this.normals = data;
  37663. break;
  37664. case BABYLON.VertexBuffer.TangentKind:
  37665. this.tangents = data;
  37666. break;
  37667. case BABYLON.VertexBuffer.UVKind:
  37668. this.uvs = data;
  37669. break;
  37670. case BABYLON.VertexBuffer.UV2Kind:
  37671. this.uvs2 = data;
  37672. break;
  37673. case BABYLON.VertexBuffer.UV3Kind:
  37674. this.uvs3 = data;
  37675. break;
  37676. case BABYLON.VertexBuffer.UV4Kind:
  37677. this.uvs4 = data;
  37678. break;
  37679. case BABYLON.VertexBuffer.UV5Kind:
  37680. this.uvs5 = data;
  37681. break;
  37682. case BABYLON.VertexBuffer.UV6Kind:
  37683. this.uvs6 = data;
  37684. break;
  37685. case BABYLON.VertexBuffer.ColorKind:
  37686. this.colors = data;
  37687. break;
  37688. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37689. this.matricesIndices = data;
  37690. break;
  37691. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37692. this.matricesWeights = data;
  37693. break;
  37694. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37695. this.matricesIndicesExtra = data;
  37696. break;
  37697. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37698. this.matricesWeightsExtra = data;
  37699. break;
  37700. }
  37701. };
  37702. /**
  37703. * Associates the vertexData to the passed Mesh.
  37704. * Sets it as updatable or not (default `false`)
  37705. * @param mesh the mesh the vertexData is applied to
  37706. * @param updatable when used and having the value true allows new data to update the vertexData
  37707. * @returns the VertexData
  37708. */
  37709. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37710. this._applyTo(mesh, updatable);
  37711. return this;
  37712. };
  37713. /**
  37714. * Associates the vertexData to the passed Geometry.
  37715. * Sets it as updatable or not (default `false`)
  37716. * @param geometry the geometry the vertexData is applied to
  37717. * @param updatable when used and having the value true allows new data to update the vertexData
  37718. * @returns VertexData
  37719. */
  37720. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37721. this._applyTo(geometry, updatable);
  37722. return this;
  37723. };
  37724. /**
  37725. * Updates the associated mesh
  37726. * @param mesh the mesh to be updated
  37727. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37728. * @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
  37729. * @returns VertexData
  37730. */
  37731. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37732. this._update(mesh);
  37733. return this;
  37734. };
  37735. /**
  37736. * Updates the associated geometry
  37737. * @param geometry the geometry to be updated
  37738. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37739. * @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
  37740. * @returns VertexData.
  37741. */
  37742. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37743. this._update(geometry);
  37744. return this;
  37745. };
  37746. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37747. if (updatable === void 0) { updatable = false; }
  37748. if (this.positions) {
  37749. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37750. }
  37751. if (this.normals) {
  37752. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37753. }
  37754. if (this.tangents) {
  37755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37756. }
  37757. if (this.uvs) {
  37758. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37759. }
  37760. if (this.uvs2) {
  37761. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37762. }
  37763. if (this.uvs3) {
  37764. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37765. }
  37766. if (this.uvs4) {
  37767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37768. }
  37769. if (this.uvs5) {
  37770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37771. }
  37772. if (this.uvs6) {
  37773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37774. }
  37775. if (this.colors) {
  37776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37777. }
  37778. if (this.matricesIndices) {
  37779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37780. }
  37781. if (this.matricesWeights) {
  37782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37783. }
  37784. if (this.matricesIndicesExtra) {
  37785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37786. }
  37787. if (this.matricesWeightsExtra) {
  37788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37789. }
  37790. if (this.indices) {
  37791. meshOrGeometry.setIndices(this.indices, null, updatable);
  37792. }
  37793. else {
  37794. meshOrGeometry.setIndices([], null);
  37795. }
  37796. return this;
  37797. };
  37798. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37799. if (this.positions) {
  37800. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37801. }
  37802. if (this.normals) {
  37803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37804. }
  37805. if (this.tangents) {
  37806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37807. }
  37808. if (this.uvs) {
  37809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37810. }
  37811. if (this.uvs2) {
  37812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37813. }
  37814. if (this.uvs3) {
  37815. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37816. }
  37817. if (this.uvs4) {
  37818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37819. }
  37820. if (this.uvs5) {
  37821. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37822. }
  37823. if (this.uvs6) {
  37824. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37825. }
  37826. if (this.colors) {
  37827. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37828. }
  37829. if (this.matricesIndices) {
  37830. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37831. }
  37832. if (this.matricesWeights) {
  37833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37834. }
  37835. if (this.matricesIndicesExtra) {
  37836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37837. }
  37838. if (this.matricesWeightsExtra) {
  37839. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37840. }
  37841. if (this.indices) {
  37842. meshOrGeometry.setIndices(this.indices, null);
  37843. }
  37844. return this;
  37845. };
  37846. /**
  37847. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37848. * @param matrix the transforming matrix
  37849. * @returns the VertexData
  37850. */
  37851. VertexData.prototype.transform = function (matrix) {
  37852. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37853. var transformed = BABYLON.Vector3.Zero();
  37854. var index;
  37855. if (this.positions) {
  37856. var position = BABYLON.Vector3.Zero();
  37857. for (index = 0; index < this.positions.length; index += 3) {
  37858. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37859. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37860. this.positions[index] = transformed.x;
  37861. this.positions[index + 1] = transformed.y;
  37862. this.positions[index + 2] = transformed.z;
  37863. }
  37864. }
  37865. if (this.normals) {
  37866. var normal = BABYLON.Vector3.Zero();
  37867. for (index = 0; index < this.normals.length; index += 3) {
  37868. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37869. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37870. this.normals[index] = transformed.x;
  37871. this.normals[index + 1] = transformed.y;
  37872. this.normals[index + 2] = transformed.z;
  37873. }
  37874. }
  37875. if (this.tangents) {
  37876. var tangent = BABYLON.Vector4.Zero();
  37877. var tangentTransformed = BABYLON.Vector4.Zero();
  37878. for (index = 0; index < this.tangents.length; index += 4) {
  37879. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37880. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37881. this.tangents[index] = tangentTransformed.x;
  37882. this.tangents[index + 1] = tangentTransformed.y;
  37883. this.tangents[index + 2] = tangentTransformed.z;
  37884. this.tangents[index + 3] = tangentTransformed.w;
  37885. }
  37886. }
  37887. if (flip && this.indices) {
  37888. for (index = 0; index < this.indices.length; index += 3) {
  37889. var tmp = this.indices[index + 1];
  37890. this.indices[index + 1] = this.indices[index + 2];
  37891. this.indices[index + 2] = tmp;
  37892. }
  37893. }
  37894. return this;
  37895. };
  37896. /**
  37897. * Merges the passed VertexData into the current one
  37898. * @param other the VertexData to be merged into the current one
  37899. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37900. * @returns the modified VertexData
  37901. */
  37902. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37903. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37904. this._validate();
  37905. other._validate();
  37906. if (!this.normals !== !other.normals ||
  37907. !this.tangents !== !other.tangents ||
  37908. !this.uvs !== !other.uvs ||
  37909. !this.uvs2 !== !other.uvs2 ||
  37910. !this.uvs3 !== !other.uvs3 ||
  37911. !this.uvs4 !== !other.uvs4 ||
  37912. !this.uvs5 !== !other.uvs5 ||
  37913. !this.uvs6 !== !other.uvs6 ||
  37914. !this.colors !== !other.colors ||
  37915. !this.matricesIndices !== !other.matricesIndices ||
  37916. !this.matricesWeights !== !other.matricesWeights ||
  37917. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37918. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37919. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37920. }
  37921. if (other.indices) {
  37922. if (!this.indices) {
  37923. this.indices = [];
  37924. }
  37925. var offset = this.positions ? this.positions.length / 3 : 0;
  37926. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37927. if (isSrcTypedArray) {
  37928. var len = this.indices.length + other.indices.length;
  37929. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37930. temp.set(this.indices);
  37931. var decal = this.indices.length;
  37932. for (var index = 0; index < other.indices.length; index++) {
  37933. temp[decal + index] = other.indices[index] + offset;
  37934. }
  37935. this.indices = temp;
  37936. }
  37937. else {
  37938. for (var index = 0; index < other.indices.length; index++) {
  37939. this.indices.push(other.indices[index] + offset);
  37940. }
  37941. }
  37942. }
  37943. this.positions = this._mergeElement(this.positions, other.positions);
  37944. this.normals = this._mergeElement(this.normals, other.normals);
  37945. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37946. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37947. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37948. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37949. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37950. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37951. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37952. this.colors = this._mergeElement(this.colors, other.colors);
  37953. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37954. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37955. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37956. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37957. return this;
  37958. };
  37959. VertexData.prototype._mergeElement = function (source, other) {
  37960. if (!source) {
  37961. return other;
  37962. }
  37963. if (!other) {
  37964. return source;
  37965. }
  37966. var len = other.length + source.length;
  37967. var isSrcTypedArray = source instanceof Float32Array;
  37968. var isOthTypedArray = other instanceof Float32Array;
  37969. // use non-loop method when the source is Float32Array
  37970. if (isSrcTypedArray) {
  37971. var ret32 = new Float32Array(len);
  37972. ret32.set(source);
  37973. ret32.set(other, source.length);
  37974. return ret32;
  37975. // source is number[], when other is also use concat
  37976. }
  37977. else if (!isOthTypedArray) {
  37978. return source.concat(other);
  37979. // source is a number[], but other is a Float32Array, loop required
  37980. }
  37981. else {
  37982. var ret = source.slice(0); // copy source to a separate array
  37983. for (var i = 0, len = other.length; i < len; i++) {
  37984. ret.push(other[i]);
  37985. }
  37986. return ret;
  37987. }
  37988. };
  37989. VertexData.prototype._validate = function () {
  37990. if (!this.positions) {
  37991. throw new Error("Positions are required");
  37992. }
  37993. var getElementCount = function (kind, values) {
  37994. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37995. if ((values.length % stride) !== 0) {
  37996. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37997. }
  37998. return values.length / stride;
  37999. };
  38000. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38001. var validateElementCount = function (kind, values) {
  38002. var elementCount = getElementCount(kind, values);
  38003. if (elementCount !== positionsElementCount) {
  38004. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38005. }
  38006. };
  38007. if (this.normals) {
  38008. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38009. }
  38010. if (this.tangents) {
  38011. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38012. }
  38013. if (this.uvs) {
  38014. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38015. }
  38016. if (this.uvs2) {
  38017. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38018. }
  38019. if (this.uvs3) {
  38020. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38021. }
  38022. if (this.uvs4) {
  38023. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38024. }
  38025. if (this.uvs5) {
  38026. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38027. }
  38028. if (this.uvs6) {
  38029. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38030. }
  38031. if (this.colors) {
  38032. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38033. }
  38034. if (this.matricesIndices) {
  38035. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38036. }
  38037. if (this.matricesWeights) {
  38038. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  38039. }
  38040. if (this.matricesIndicesExtra) {
  38041. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  38042. }
  38043. if (this.matricesWeightsExtra) {
  38044. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  38045. }
  38046. };
  38047. /**
  38048. * Serializes the VertexData
  38049. * @returns a serialized object
  38050. */
  38051. VertexData.prototype.serialize = function () {
  38052. var serializationObject = this.serialize();
  38053. if (this.positions) {
  38054. serializationObject.positions = this.positions;
  38055. }
  38056. if (this.normals) {
  38057. serializationObject.normals = this.normals;
  38058. }
  38059. if (this.tangents) {
  38060. serializationObject.tangents = this.tangents;
  38061. }
  38062. if (this.uvs) {
  38063. serializationObject.uvs = this.uvs;
  38064. }
  38065. if (this.uvs2) {
  38066. serializationObject.uvs2 = this.uvs2;
  38067. }
  38068. if (this.uvs3) {
  38069. serializationObject.uvs3 = this.uvs3;
  38070. }
  38071. if (this.uvs4) {
  38072. serializationObject.uvs4 = this.uvs4;
  38073. }
  38074. if (this.uvs5) {
  38075. serializationObject.uvs5 = this.uvs5;
  38076. }
  38077. if (this.uvs6) {
  38078. serializationObject.uvs6 = this.uvs6;
  38079. }
  38080. if (this.colors) {
  38081. serializationObject.colors = this.colors;
  38082. }
  38083. if (this.matricesIndices) {
  38084. serializationObject.matricesIndices = this.matricesIndices;
  38085. serializationObject.matricesIndices._isExpanded = true;
  38086. }
  38087. if (this.matricesWeights) {
  38088. serializationObject.matricesWeights = this.matricesWeights;
  38089. }
  38090. if (this.matricesIndicesExtra) {
  38091. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38092. serializationObject.matricesIndicesExtra._isExpanded = true;
  38093. }
  38094. if (this.matricesWeightsExtra) {
  38095. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38096. }
  38097. serializationObject.indices = this.indices;
  38098. return serializationObject;
  38099. };
  38100. // Statics
  38101. /**
  38102. * Extracts the vertexData from a mesh
  38103. * @param mesh the mesh from which to extract the VertexData
  38104. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  38105. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38106. * @returns the object VertexData associated to the passed mesh
  38107. */
  38108. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  38109. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  38110. };
  38111. /**
  38112. * Extracts the vertexData from the geometry
  38113. * @param geometry the geometry from which to extract the VertexData
  38114. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38115. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38116. * @returns the object VertexData associated to the passed mesh
  38117. */
  38118. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38119. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38120. };
  38121. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38122. var result = new VertexData();
  38123. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38124. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38125. }
  38126. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38127. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38128. }
  38129. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38130. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38131. }
  38132. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38133. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38134. }
  38135. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38136. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38137. }
  38138. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38139. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38140. }
  38141. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38142. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38143. }
  38144. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38145. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38146. }
  38147. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38148. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38149. }
  38150. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38151. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38152. }
  38153. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38154. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38155. }
  38156. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38157. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38158. }
  38159. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38160. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38161. }
  38162. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38163. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38164. }
  38165. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38166. return result;
  38167. };
  38168. /**
  38169. * Creates the VertexData for a Ribbon
  38170. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38171. * * pathArray array of paths, each of which an array of successive Vector3
  38172. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38173. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38174. * * 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
  38175. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38176. * * 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)
  38177. * * 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)
  38178. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38179. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38180. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38181. * @returns the VertexData of the ribbon
  38182. */
  38183. VertexData.CreateRibbon = function (options) {
  38184. var pathArray = options.pathArray;
  38185. var closeArray = options.closeArray || false;
  38186. var closePath = options.closePath || false;
  38187. var invertUV = options.invertUV || false;
  38188. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38189. var offset = options.offset || defaultOffset;
  38190. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38191. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38192. var customUV = options.uvs;
  38193. var customColors = options.colors;
  38194. var positions = [];
  38195. var indices = [];
  38196. var normals = [];
  38197. var uvs = [];
  38198. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38199. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38200. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38201. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38202. var minlg; // minimal length among all paths from pathArray
  38203. var lg = []; // array of path lengths : nb of vertex per path
  38204. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38205. var p; // path iterator
  38206. var i; // point iterator
  38207. var j; // point iterator
  38208. // if single path in pathArray
  38209. if (pathArray.length < 2) {
  38210. var ar1 = [];
  38211. var ar2 = [];
  38212. for (i = 0; i < pathArray[0].length - offset; i++) {
  38213. ar1.push(pathArray[0][i]);
  38214. ar2.push(pathArray[0][i + offset]);
  38215. }
  38216. pathArray = [ar1, ar2];
  38217. }
  38218. // positions and horizontal distances (u)
  38219. var idc = 0;
  38220. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38221. var path;
  38222. var l;
  38223. minlg = pathArray[0].length;
  38224. var vectlg;
  38225. var dist;
  38226. for (p = 0; p < pathArray.length; p++) {
  38227. uTotalDistance[p] = 0;
  38228. us[p] = [0];
  38229. path = pathArray[p];
  38230. l = path.length;
  38231. minlg = (minlg < l) ? minlg : l;
  38232. j = 0;
  38233. while (j < l) {
  38234. positions.push(path[j].x, path[j].y, path[j].z);
  38235. if (j > 0) {
  38236. vectlg = path[j].subtract(path[j - 1]).length();
  38237. dist = vectlg + uTotalDistance[p];
  38238. us[p].push(dist);
  38239. uTotalDistance[p] = dist;
  38240. }
  38241. j++;
  38242. }
  38243. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38244. j--;
  38245. positions.push(path[0].x, path[0].y, path[0].z);
  38246. vectlg = path[j].subtract(path[0]).length();
  38247. dist = vectlg + uTotalDistance[p];
  38248. us[p].push(dist);
  38249. uTotalDistance[p] = dist;
  38250. }
  38251. lg[p] = l + closePathCorr;
  38252. idx[p] = idc;
  38253. idc += (l + closePathCorr);
  38254. }
  38255. // vertical distances (v)
  38256. var path1;
  38257. var path2;
  38258. var vertex1 = null;
  38259. var vertex2 = null;
  38260. for (i = 0; i < minlg + closePathCorr; i++) {
  38261. vTotalDistance[i] = 0;
  38262. vs[i] = [0];
  38263. for (p = 0; p < pathArray.length - 1; p++) {
  38264. path1 = pathArray[p];
  38265. path2 = pathArray[p + 1];
  38266. if (i === minlg) { // closePath
  38267. vertex1 = path1[0];
  38268. vertex2 = path2[0];
  38269. }
  38270. else {
  38271. vertex1 = path1[i];
  38272. vertex2 = path2[i];
  38273. }
  38274. vectlg = vertex2.subtract(vertex1).length();
  38275. dist = vectlg + vTotalDistance[i];
  38276. vs[i].push(dist);
  38277. vTotalDistance[i] = dist;
  38278. }
  38279. if (closeArray && vertex2 && vertex1) {
  38280. path1 = pathArray[p];
  38281. path2 = pathArray[0];
  38282. if (i === minlg) { // closePath
  38283. vertex2 = path2[0];
  38284. }
  38285. vectlg = vertex2.subtract(vertex1).length();
  38286. dist = vectlg + vTotalDistance[i];
  38287. vTotalDistance[i] = dist;
  38288. }
  38289. }
  38290. // uvs
  38291. var u;
  38292. var v;
  38293. if (customUV) {
  38294. for (p = 0; p < customUV.length; p++) {
  38295. uvs.push(customUV[p].x, customUV[p].y);
  38296. }
  38297. }
  38298. else {
  38299. for (p = 0; p < pathArray.length; p++) {
  38300. for (i = 0; i < minlg + closePathCorr; i++) {
  38301. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38302. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38303. if (invertUV) {
  38304. uvs.push(v, u);
  38305. }
  38306. else {
  38307. uvs.push(u, v);
  38308. }
  38309. }
  38310. }
  38311. }
  38312. // indices
  38313. p = 0; // path index
  38314. var pi = 0; // positions array index
  38315. var l1 = lg[p] - 1; // path1 length
  38316. var l2 = lg[p + 1] - 1; // path2 length
  38317. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38318. var shft = idx[1] - idx[0]; // shift
  38319. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38320. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38321. // 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
  38322. indices.push(pi, pi + shft, pi + 1);
  38323. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38324. pi += 1;
  38325. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38326. p++;
  38327. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38328. shft = idx[0] - idx[p];
  38329. l1 = lg[p] - 1;
  38330. l2 = lg[0] - 1;
  38331. }
  38332. else {
  38333. shft = idx[p + 1] - idx[p];
  38334. l1 = lg[p] - 1;
  38335. l2 = lg[p + 1] - 1;
  38336. }
  38337. pi = idx[p];
  38338. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38339. }
  38340. }
  38341. // normals
  38342. VertexData.ComputeNormals(positions, indices, normals);
  38343. if (closePath) { // update both the first and last vertex normals to their average value
  38344. var indexFirst = 0;
  38345. var indexLast = 0;
  38346. for (p = 0; p < pathArray.length; p++) {
  38347. indexFirst = idx[p] * 3;
  38348. if (p + 1 < pathArray.length) {
  38349. indexLast = (idx[p + 1] - 1) * 3;
  38350. }
  38351. else {
  38352. indexLast = normals.length - 3;
  38353. }
  38354. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38355. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38356. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38357. normals[indexLast] = normals[indexFirst];
  38358. normals[indexLast + 1] = normals[indexFirst + 1];
  38359. normals[indexLast + 2] = normals[indexFirst + 2];
  38360. }
  38361. }
  38362. // sides
  38363. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38364. // Colors
  38365. var colors = null;
  38366. if (customColors) {
  38367. colors = new Float32Array(customColors.length * 4);
  38368. for (var c = 0; c < customColors.length; c++) {
  38369. colors[c * 4] = customColors[c].r;
  38370. colors[c * 4 + 1] = customColors[c].g;
  38371. colors[c * 4 + 2] = customColors[c].b;
  38372. colors[c * 4 + 3] = customColors[c].a;
  38373. }
  38374. }
  38375. // Result
  38376. var vertexData = new VertexData();
  38377. var positions32 = new Float32Array(positions);
  38378. var normals32 = new Float32Array(normals);
  38379. var uvs32 = new Float32Array(uvs);
  38380. vertexData.indices = indices;
  38381. vertexData.positions = positions32;
  38382. vertexData.normals = normals32;
  38383. vertexData.uvs = uvs32;
  38384. if (colors) {
  38385. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38386. }
  38387. if (closePath) {
  38388. vertexData._idx = idx;
  38389. }
  38390. return vertexData;
  38391. };
  38392. /**
  38393. * Creates the VertexData for a box
  38394. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38395. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38396. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38397. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38398. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38399. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38400. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38401. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38402. * * 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)
  38403. * * 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)
  38404. * @returns the VertexData of the box
  38405. */
  38406. VertexData.CreateBox = function (options) {
  38407. var normalsSource = [
  38408. new BABYLON.Vector3(0, 0, 1),
  38409. new BABYLON.Vector3(0, 0, -1),
  38410. new BABYLON.Vector3(1, 0, 0),
  38411. new BABYLON.Vector3(-1, 0, 0),
  38412. new BABYLON.Vector3(0, 1, 0),
  38413. new BABYLON.Vector3(0, -1, 0)
  38414. ];
  38415. var indices = [];
  38416. var positions = [];
  38417. var normals = [];
  38418. var uvs = [];
  38419. var width = options.width || options.size || 1;
  38420. var height = options.height || options.size || 1;
  38421. var depth = options.depth || options.size || 1;
  38422. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38423. var faceUV = options.faceUV || new Array(6);
  38424. var faceColors = options.faceColors;
  38425. var colors = [];
  38426. // default face colors and UV if undefined
  38427. for (var f = 0; f < 6; f++) {
  38428. if (faceUV[f] === undefined) {
  38429. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38430. }
  38431. if (faceColors && faceColors[f] === undefined) {
  38432. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38433. }
  38434. }
  38435. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38436. // Create each face in turn.
  38437. for (var index = 0; index < normalsSource.length; index++) {
  38438. var normal = normalsSource[index];
  38439. // Get two vectors perpendicular to the face normal and to each other.
  38440. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38441. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38442. // Six indices (two triangles) per face.
  38443. var verticesLength = positions.length / 3;
  38444. indices.push(verticesLength);
  38445. indices.push(verticesLength + 1);
  38446. indices.push(verticesLength + 2);
  38447. indices.push(verticesLength);
  38448. indices.push(verticesLength + 2);
  38449. indices.push(verticesLength + 3);
  38450. // Four vertices per face.
  38451. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38452. positions.push(vertex.x, vertex.y, vertex.z);
  38453. normals.push(normal.x, normal.y, normal.z);
  38454. uvs.push(faceUV[index].z, faceUV[index].w);
  38455. if (faceColors) {
  38456. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38457. }
  38458. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38459. positions.push(vertex.x, vertex.y, vertex.z);
  38460. normals.push(normal.x, normal.y, normal.z);
  38461. uvs.push(faceUV[index].x, faceUV[index].w);
  38462. if (faceColors) {
  38463. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38464. }
  38465. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38466. positions.push(vertex.x, vertex.y, vertex.z);
  38467. normals.push(normal.x, normal.y, normal.z);
  38468. uvs.push(faceUV[index].x, faceUV[index].y);
  38469. if (faceColors) {
  38470. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38471. }
  38472. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38473. positions.push(vertex.x, vertex.y, vertex.z);
  38474. normals.push(normal.x, normal.y, normal.z);
  38475. uvs.push(faceUV[index].z, faceUV[index].y);
  38476. if (faceColors) {
  38477. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38478. }
  38479. }
  38480. // sides
  38481. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38482. // Result
  38483. var vertexData = new VertexData();
  38484. vertexData.indices = indices;
  38485. vertexData.positions = positions;
  38486. vertexData.normals = normals;
  38487. vertexData.uvs = uvs;
  38488. if (faceColors) {
  38489. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38490. vertexData.colors = totalColors;
  38491. }
  38492. return vertexData;
  38493. };
  38494. /**
  38495. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38496. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38497. * * segments sets the number of horizontal strips optional, default 32
  38498. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38499. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38500. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38501. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38502. * * 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
  38503. * * 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
  38504. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38505. * * 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)
  38506. * * 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)
  38507. * @returns the VertexData of the ellipsoid
  38508. */
  38509. VertexData.CreateSphere = function (options) {
  38510. var segments = options.segments || 32;
  38511. var diameterX = options.diameterX || options.diameter || 1;
  38512. var diameterY = options.diameterY || options.diameter || 1;
  38513. var diameterZ = options.diameterZ || options.diameter || 1;
  38514. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38515. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38516. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38517. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38518. var totalZRotationSteps = 2 + segments;
  38519. var totalYRotationSteps = 2 * totalZRotationSteps;
  38520. var indices = [];
  38521. var positions = [];
  38522. var normals = [];
  38523. var uvs = [];
  38524. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38525. var normalizedZ = zRotationStep / totalZRotationSteps;
  38526. var angleZ = normalizedZ * Math.PI * slice;
  38527. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38528. var normalizedY = yRotationStep / totalYRotationSteps;
  38529. var angleY = normalizedY * Math.PI * 2 * arc;
  38530. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38531. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38532. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38533. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38534. var vertex = complete.multiply(radius);
  38535. var normal = complete.divide(radius).normalize();
  38536. positions.push(vertex.x, vertex.y, vertex.z);
  38537. normals.push(normal.x, normal.y, normal.z);
  38538. uvs.push(normalizedY, normalizedZ);
  38539. }
  38540. if (zRotationStep > 0) {
  38541. var verticesCount = positions.length / 3;
  38542. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38543. indices.push((firstIndex));
  38544. indices.push((firstIndex + 1));
  38545. indices.push(firstIndex + totalYRotationSteps + 1);
  38546. indices.push((firstIndex + totalYRotationSteps + 1));
  38547. indices.push((firstIndex + 1));
  38548. indices.push((firstIndex + totalYRotationSteps + 2));
  38549. }
  38550. }
  38551. }
  38552. // Sides
  38553. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38554. // Result
  38555. var vertexData = new VertexData();
  38556. vertexData.indices = indices;
  38557. vertexData.positions = positions;
  38558. vertexData.normals = normals;
  38559. vertexData.uvs = uvs;
  38560. return vertexData;
  38561. };
  38562. /**
  38563. * Creates the VertexData for a cylinder, cone or prism
  38564. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38565. * * height sets the height (y direction) of the cylinder, optional, default 2
  38566. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38567. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38568. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38569. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38570. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38571. * * 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
  38572. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38573. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38574. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38575. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38576. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38577. * * 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)
  38578. * * 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)
  38579. * @returns the VertexData of the cylinder, cone or prism
  38580. */
  38581. VertexData.CreateCylinder = function (options) {
  38582. var height = options.height || 2;
  38583. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38584. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38585. var tessellation = options.tessellation || 24;
  38586. var subdivisions = options.subdivisions || 1;
  38587. var hasRings = options.hasRings ? true : false;
  38588. var enclose = options.enclose ? true : false;
  38589. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38590. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38591. var faceUV = options.faceUV || new Array(3);
  38592. var faceColors = options.faceColors;
  38593. // default face colors and UV if undefined
  38594. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38595. var ringNb = (hasRings) ? subdivisions : 1;
  38596. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38597. var f;
  38598. for (f = 0; f < surfaceNb; f++) {
  38599. if (faceColors && faceColors[f] === undefined) {
  38600. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38601. }
  38602. }
  38603. for (f = 0; f < surfaceNb; f++) {
  38604. if (faceUV && faceUV[f] === undefined) {
  38605. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38606. }
  38607. }
  38608. var indices = new Array();
  38609. var positions = new Array();
  38610. var normals = new Array();
  38611. var uvs = new Array();
  38612. var colors = new Array();
  38613. var angle_step = Math.PI * 2 * arc / tessellation;
  38614. var angle;
  38615. var h;
  38616. var radius;
  38617. var tan = (diameterBottom - diameterTop) / 2 / height;
  38618. var ringVertex = BABYLON.Vector3.Zero();
  38619. var ringNormal = BABYLON.Vector3.Zero();
  38620. var ringFirstVertex = BABYLON.Vector3.Zero();
  38621. var ringFirstNormal = BABYLON.Vector3.Zero();
  38622. var quadNormal = BABYLON.Vector3.Zero();
  38623. var Y = BABYLON.Axis.Y;
  38624. // positions, normals, uvs
  38625. var i;
  38626. var j;
  38627. var r;
  38628. var ringIdx = 1;
  38629. var s = 1; // surface index
  38630. var cs = 0;
  38631. var v = 0;
  38632. for (i = 0; i <= subdivisions; i++) {
  38633. h = i / subdivisions;
  38634. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38635. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38636. for (r = 0; r < ringIdx; r++) {
  38637. if (hasRings) {
  38638. s += r;
  38639. }
  38640. if (enclose) {
  38641. s += 2 * r;
  38642. }
  38643. for (j = 0; j <= tessellation; j++) {
  38644. angle = j * angle_step;
  38645. // position
  38646. ringVertex.x = Math.cos(-angle) * radius;
  38647. ringVertex.y = -height / 2 + h * height;
  38648. ringVertex.z = Math.sin(-angle) * radius;
  38649. // normal
  38650. if (diameterTop === 0 && i === subdivisions) {
  38651. // if no top cap, reuse former normals
  38652. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38653. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38654. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38655. }
  38656. else {
  38657. ringNormal.x = ringVertex.x;
  38658. ringNormal.z = ringVertex.z;
  38659. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38660. ringNormal.normalize();
  38661. }
  38662. // keep first ring vertex values for enclose
  38663. if (j === 0) {
  38664. ringFirstVertex.copyFrom(ringVertex);
  38665. ringFirstNormal.copyFrom(ringNormal);
  38666. }
  38667. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38668. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38669. if (hasRings) {
  38670. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38671. }
  38672. else {
  38673. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38674. }
  38675. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38676. if (faceColors) {
  38677. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38678. }
  38679. }
  38680. // if enclose, add four vertices and their dedicated normals
  38681. if (arc !== 1 && enclose) {
  38682. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38683. positions.push(0, ringVertex.y, 0);
  38684. positions.push(0, ringVertex.y, 0);
  38685. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38686. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38687. quadNormal.normalize();
  38688. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38689. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38690. quadNormal.normalize();
  38691. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38692. if (hasRings) {
  38693. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38694. }
  38695. else {
  38696. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38697. }
  38698. uvs.push(faceUV[s + 1].x, v);
  38699. uvs.push(faceUV[s + 1].z, v);
  38700. if (hasRings) {
  38701. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38702. }
  38703. else {
  38704. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38705. }
  38706. uvs.push(faceUV[s + 2].x, v);
  38707. uvs.push(faceUV[s + 2].z, v);
  38708. if (faceColors) {
  38709. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38710. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38711. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38712. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38713. }
  38714. }
  38715. if (cs !== s) {
  38716. cs = s;
  38717. }
  38718. }
  38719. }
  38720. // indices
  38721. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38722. var s;
  38723. i = 0;
  38724. for (s = 0; s < subdivisions; s++) {
  38725. var i0 = 0;
  38726. var i1 = 0;
  38727. var i2 = 0;
  38728. var i3 = 0;
  38729. for (j = 0; j < tessellation; j++) {
  38730. i0 = i * (e + 1) + j;
  38731. i1 = (i + 1) * (e + 1) + j;
  38732. i2 = i * (e + 1) + (j + 1);
  38733. i3 = (i + 1) * (e + 1) + (j + 1);
  38734. indices.push(i0, i1, i2);
  38735. indices.push(i3, i2, i1);
  38736. }
  38737. if (arc !== 1 && enclose) { // if enclose, add two quads
  38738. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38739. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38740. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38741. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38742. }
  38743. i = (hasRings) ? (i + 2) : (i + 1);
  38744. }
  38745. // Caps
  38746. var createCylinderCap = function (isTop) {
  38747. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38748. if (radius === 0) {
  38749. return;
  38750. }
  38751. // Cap positions, normals & uvs
  38752. var angle;
  38753. var circleVector;
  38754. var i;
  38755. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38756. var c = null;
  38757. if (faceColors) {
  38758. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38759. }
  38760. // cap center
  38761. var vbase = positions.length / 3;
  38762. var offset = isTop ? height / 2 : -height / 2;
  38763. var center = new BABYLON.Vector3(0, offset, 0);
  38764. positions.push(center.x, center.y, center.z);
  38765. normals.push(0, isTop ? 1 : -1, 0);
  38766. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38767. if (c) {
  38768. colors.push(c.r, c.g, c.b, c.a);
  38769. }
  38770. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38771. for (i = 0; i <= tessellation; i++) {
  38772. angle = Math.PI * 2 * i * arc / tessellation;
  38773. var cos = Math.cos(-angle);
  38774. var sin = Math.sin(-angle);
  38775. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38776. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38777. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38778. normals.push(0, isTop ? 1 : -1, 0);
  38779. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38780. if (c) {
  38781. colors.push(c.r, c.g, c.b, c.a);
  38782. }
  38783. }
  38784. // Cap indices
  38785. for (i = 0; i < tessellation; i++) {
  38786. if (!isTop) {
  38787. indices.push(vbase);
  38788. indices.push(vbase + (i + 1));
  38789. indices.push(vbase + (i + 2));
  38790. }
  38791. else {
  38792. indices.push(vbase);
  38793. indices.push(vbase + (i + 2));
  38794. indices.push(vbase + (i + 1));
  38795. }
  38796. }
  38797. };
  38798. // add caps to geometry
  38799. createCylinderCap(false);
  38800. createCylinderCap(true);
  38801. // Sides
  38802. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38803. var vertexData = new VertexData();
  38804. vertexData.indices = indices;
  38805. vertexData.positions = positions;
  38806. vertexData.normals = normals;
  38807. vertexData.uvs = uvs;
  38808. if (faceColors) {
  38809. vertexData.colors = colors;
  38810. }
  38811. return vertexData;
  38812. };
  38813. /**
  38814. * Creates the VertexData for a torus
  38815. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38816. * * diameter the diameter of the torus, optional default 1
  38817. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38818. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38819. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38820. * * 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)
  38821. * * 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)
  38822. * @returns the VertexData of the torus
  38823. */
  38824. VertexData.CreateTorus = function (options) {
  38825. var indices = [];
  38826. var positions = [];
  38827. var normals = [];
  38828. var uvs = [];
  38829. var diameter = options.diameter || 1;
  38830. var thickness = options.thickness || 0.5;
  38831. var tessellation = options.tessellation || 16;
  38832. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38833. var stride = tessellation + 1;
  38834. for (var i = 0; i <= tessellation; i++) {
  38835. var u = i / tessellation;
  38836. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38837. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38838. for (var j = 0; j <= tessellation; j++) {
  38839. var v = 1 - j / tessellation;
  38840. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38841. var dx = Math.cos(innerAngle);
  38842. var dy = Math.sin(innerAngle);
  38843. // Create a vertex.
  38844. var normal = new BABYLON.Vector3(dx, dy, 0);
  38845. var position = normal.scale(thickness / 2);
  38846. var textureCoordinate = new BABYLON.Vector2(u, v);
  38847. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38848. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38849. positions.push(position.x, position.y, position.z);
  38850. normals.push(normal.x, normal.y, normal.z);
  38851. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38852. // And create indices for two triangles.
  38853. var nextI = (i + 1) % stride;
  38854. var nextJ = (j + 1) % stride;
  38855. indices.push(i * stride + j);
  38856. indices.push(i * stride + nextJ);
  38857. indices.push(nextI * stride + j);
  38858. indices.push(i * stride + nextJ);
  38859. indices.push(nextI * stride + nextJ);
  38860. indices.push(nextI * stride + j);
  38861. }
  38862. }
  38863. // Sides
  38864. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38865. // Result
  38866. var vertexData = new VertexData();
  38867. vertexData.indices = indices;
  38868. vertexData.positions = positions;
  38869. vertexData.normals = normals;
  38870. vertexData.uvs = uvs;
  38871. return vertexData;
  38872. };
  38873. /**
  38874. * Creates the VertexData of the LineSystem
  38875. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38876. * - lines an array of lines, each line being an array of successive Vector3
  38877. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38878. * @returns the VertexData of the LineSystem
  38879. */
  38880. VertexData.CreateLineSystem = function (options) {
  38881. var indices = [];
  38882. var positions = [];
  38883. var lines = options.lines;
  38884. var colors = options.colors;
  38885. var vertexColors = [];
  38886. var idx = 0;
  38887. for (var l = 0; l < lines.length; l++) {
  38888. var points = lines[l];
  38889. for (var index = 0; index < points.length; index++) {
  38890. positions.push(points[index].x, points[index].y, points[index].z);
  38891. if (colors) {
  38892. var color = colors[l];
  38893. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38894. }
  38895. if (index > 0) {
  38896. indices.push(idx - 1);
  38897. indices.push(idx);
  38898. }
  38899. idx++;
  38900. }
  38901. }
  38902. var vertexData = new VertexData();
  38903. vertexData.indices = indices;
  38904. vertexData.positions = positions;
  38905. if (colors) {
  38906. vertexData.colors = vertexColors;
  38907. }
  38908. return vertexData;
  38909. };
  38910. /**
  38911. * Create the VertexData for a DashedLines
  38912. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38913. * - points an array successive Vector3
  38914. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38915. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38916. * - dashNb the intended total number of dashes, optional, default 200
  38917. * @returns the VertexData for the DashedLines
  38918. */
  38919. VertexData.CreateDashedLines = function (options) {
  38920. var dashSize = options.dashSize || 3;
  38921. var gapSize = options.gapSize || 1;
  38922. var dashNb = options.dashNb || 200;
  38923. var points = options.points;
  38924. var positions = new Array();
  38925. var indices = new Array();
  38926. var curvect = BABYLON.Vector3.Zero();
  38927. var lg = 0;
  38928. var nb = 0;
  38929. var shft = 0;
  38930. var dashshft = 0;
  38931. var curshft = 0;
  38932. var idx = 0;
  38933. var i = 0;
  38934. for (i = 0; i < points.length - 1; i++) {
  38935. points[i + 1].subtractToRef(points[i], curvect);
  38936. lg += curvect.length();
  38937. }
  38938. shft = lg / dashNb;
  38939. dashshft = dashSize * shft / (dashSize + gapSize);
  38940. for (i = 0; i < points.length - 1; i++) {
  38941. points[i + 1].subtractToRef(points[i], curvect);
  38942. nb = Math.floor(curvect.length() / shft);
  38943. curvect.normalize();
  38944. for (var j = 0; j < nb; j++) {
  38945. curshft = shft * j;
  38946. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38947. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38948. indices.push(idx, idx + 1);
  38949. idx += 2;
  38950. }
  38951. }
  38952. // Result
  38953. var vertexData = new VertexData();
  38954. vertexData.positions = positions;
  38955. vertexData.indices = indices;
  38956. return vertexData;
  38957. };
  38958. /**
  38959. * Creates the VertexData for a Ground
  38960. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38961. * - width the width (x direction) of the ground, optional, default 1
  38962. * - height the height (z direction) of the ground, optional, default 1
  38963. * - subdivisions the number of subdivisions per side, optional, default 1
  38964. * @returns the VertexData of the Ground
  38965. */
  38966. VertexData.CreateGround = function (options) {
  38967. var indices = [];
  38968. var positions = [];
  38969. var normals = [];
  38970. var uvs = [];
  38971. var row, col;
  38972. var width = options.width || 1;
  38973. var height = options.height || 1;
  38974. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38975. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38976. for (row = 0; row <= subdivisionsY; row++) {
  38977. for (col = 0; col <= subdivisionsX; col++) {
  38978. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38979. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38980. positions.push(position.x, position.y, position.z);
  38981. normals.push(normal.x, normal.y, normal.z);
  38982. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38983. }
  38984. }
  38985. for (row = 0; row < subdivisionsY; row++) {
  38986. for (col = 0; col < subdivisionsX; col++) {
  38987. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38988. indices.push(col + 1 + row * (subdivisionsX + 1));
  38989. indices.push(col + row * (subdivisionsX + 1));
  38990. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38991. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38992. indices.push(col + row * (subdivisionsX + 1));
  38993. }
  38994. }
  38995. // Result
  38996. var vertexData = new VertexData();
  38997. vertexData.indices = indices;
  38998. vertexData.positions = positions;
  38999. vertexData.normals = normals;
  39000. vertexData.uvs = uvs;
  39001. return vertexData;
  39002. };
  39003. /**
  39004. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39005. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39006. * * xmin the ground minimum X coordinate, optional, default -1
  39007. * * zmin the ground minimum Z coordinate, optional, default -1
  39008. * * xmax the ground maximum X coordinate, optional, default 1
  39009. * * zmax the ground maximum Z coordinate, optional, default 1
  39010. * * 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}
  39011. * * 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}
  39012. * @returns the VertexData of the TiledGround
  39013. */
  39014. VertexData.CreateTiledGround = function (options) {
  39015. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39016. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39017. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39018. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39019. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39020. var precision = options.precision || { w: 1, h: 1 };
  39021. var indices = new Array();
  39022. var positions = new Array();
  39023. var normals = new Array();
  39024. var uvs = new Array();
  39025. var row, col, tileRow, tileCol;
  39026. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39027. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39028. precision.w = (precision.w < 1) ? 1 : precision.w;
  39029. precision.h = (precision.h < 1) ? 1 : precision.h;
  39030. var tileSize = {
  39031. 'w': (xmax - xmin) / subdivisions.w,
  39032. 'h': (zmax - zmin) / subdivisions.h
  39033. };
  39034. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39035. // Indices
  39036. var base = positions.length / 3;
  39037. var rowLength = precision.w + 1;
  39038. for (row = 0; row < precision.h; row++) {
  39039. for (col = 0; col < precision.w; col++) {
  39040. var square = [
  39041. base + col + row * rowLength,
  39042. base + (col + 1) + row * rowLength,
  39043. base + (col + 1) + (row + 1) * rowLength,
  39044. base + col + (row + 1) * rowLength
  39045. ];
  39046. indices.push(square[1]);
  39047. indices.push(square[2]);
  39048. indices.push(square[3]);
  39049. indices.push(square[0]);
  39050. indices.push(square[1]);
  39051. indices.push(square[3]);
  39052. }
  39053. }
  39054. // Position, normals and uvs
  39055. var position = BABYLON.Vector3.Zero();
  39056. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39057. for (row = 0; row <= precision.h; row++) {
  39058. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39059. for (col = 0; col <= precision.w; col++) {
  39060. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39061. position.y = 0;
  39062. positions.push(position.x, position.y, position.z);
  39063. normals.push(normal.x, normal.y, normal.z);
  39064. uvs.push(col / precision.w, row / precision.h);
  39065. }
  39066. }
  39067. }
  39068. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39069. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39070. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39071. }
  39072. }
  39073. // Result
  39074. var vertexData = new VertexData();
  39075. vertexData.indices = indices;
  39076. vertexData.positions = positions;
  39077. vertexData.normals = normals;
  39078. vertexData.uvs = uvs;
  39079. return vertexData;
  39080. };
  39081. /**
  39082. * Creates the VertexData of the Ground designed from a heightmap
  39083. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  39084. * * width the width (x direction) of the ground
  39085. * * height the height (z direction) of the ground
  39086. * * subdivisions the number of subdivisions per side
  39087. * * minHeight the minimum altitude on the ground, optional, default 0
  39088. * * maxHeight the maximum altitude on the ground, optional default 1
  39089. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  39090. * * buffer the array holding the image color data
  39091. * * bufferWidth the width of image
  39092. * * bufferHeight the height of image
  39093. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  39094. * @returns the VertexData of the Ground designed from a heightmap
  39095. */
  39096. VertexData.CreateGroundFromHeightMap = function (options) {
  39097. var indices = [];
  39098. var positions = [];
  39099. var normals = [];
  39100. var uvs = [];
  39101. var row, col;
  39102. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39103. var alphaFilter = options.alphaFilter || 0.0;
  39104. // Vertices
  39105. for (row = 0; row <= options.subdivisions; row++) {
  39106. for (col = 0; col <= options.subdivisions; col++) {
  39107. 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));
  39108. // Compute height
  39109. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39110. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39111. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39112. var r = options.buffer[pos] / 255.0;
  39113. var g = options.buffer[pos + 1] / 255.0;
  39114. var b = options.buffer[pos + 2] / 255.0;
  39115. var a = options.buffer[pos + 3] / 255.0;
  39116. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39117. // If our alpha channel is not within our filter then we will assign a 'special' height
  39118. // Then when building the indices, we will ignore any vertex that is using the special height
  39119. if (a >= alphaFilter) {
  39120. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39121. }
  39122. else {
  39123. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39124. }
  39125. // Add vertex
  39126. positions.push(position.x, position.y, position.z);
  39127. normals.push(0, 0, 0);
  39128. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39129. }
  39130. }
  39131. // Indices
  39132. for (row = 0; row < options.subdivisions; row++) {
  39133. for (col = 0; col < options.subdivisions; col++) {
  39134. // Calculate Indices
  39135. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39136. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39137. var idx3 = (col + row * (options.subdivisions + 1));
  39138. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39139. // Check that all indices are visible (based on our special height)
  39140. // Only display the vertex if all Indices are visible
  39141. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39142. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39143. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39144. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39145. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39146. indices.push(idx1);
  39147. indices.push(idx2);
  39148. indices.push(idx3);
  39149. }
  39150. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39151. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39152. indices.push(idx4);
  39153. indices.push(idx1);
  39154. indices.push(idx3);
  39155. }
  39156. }
  39157. }
  39158. // Normals
  39159. VertexData.ComputeNormals(positions, indices, normals);
  39160. // Result
  39161. var vertexData = new VertexData();
  39162. vertexData.indices = indices;
  39163. vertexData.positions = positions;
  39164. vertexData.normals = normals;
  39165. vertexData.uvs = uvs;
  39166. return vertexData;
  39167. };
  39168. /**
  39169. * Creates the VertexData for a Plane
  39170. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39171. * * size sets the width and height of the plane to the value of size, optional default 1
  39172. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39173. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39174. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39175. * * 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)
  39176. * * 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)
  39177. * @returns the VertexData of the box
  39178. */
  39179. VertexData.CreatePlane = function (options) {
  39180. var indices = [];
  39181. var positions = [];
  39182. var normals = [];
  39183. var uvs = [];
  39184. var width = options.width || options.size || 1;
  39185. var height = options.height || options.size || 1;
  39186. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39187. // Vertices
  39188. var halfWidth = width / 2.0;
  39189. var halfHeight = height / 2.0;
  39190. positions.push(-halfWidth, -halfHeight, 0);
  39191. normals.push(0, 0, -1.0);
  39192. uvs.push(0.0, 0.0);
  39193. positions.push(halfWidth, -halfHeight, 0);
  39194. normals.push(0, 0, -1.0);
  39195. uvs.push(1.0, 0.0);
  39196. positions.push(halfWidth, halfHeight, 0);
  39197. normals.push(0, 0, -1.0);
  39198. uvs.push(1.0, 1.0);
  39199. positions.push(-halfWidth, halfHeight, 0);
  39200. normals.push(0, 0, -1.0);
  39201. uvs.push(0.0, 1.0);
  39202. // Indices
  39203. indices.push(0);
  39204. indices.push(1);
  39205. indices.push(2);
  39206. indices.push(0);
  39207. indices.push(2);
  39208. indices.push(3);
  39209. // Sides
  39210. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39211. // Result
  39212. var vertexData = new VertexData();
  39213. vertexData.indices = indices;
  39214. vertexData.positions = positions;
  39215. vertexData.normals = normals;
  39216. vertexData.uvs = uvs;
  39217. return vertexData;
  39218. };
  39219. /**
  39220. * Creates the VertexData of the Disc or regular Polygon
  39221. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39222. * * radius the radius of the disc, optional default 0.5
  39223. * * tessellation the number of polygon sides, optional, default 64
  39224. * * 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
  39225. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39226. * * 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)
  39227. * * 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)
  39228. * @returns the VertexData of the box
  39229. */
  39230. VertexData.CreateDisc = function (options) {
  39231. var positions = new Array();
  39232. var indices = new Array();
  39233. var normals = new Array();
  39234. var uvs = new Array();
  39235. var radius = options.radius || 0.5;
  39236. var tessellation = options.tessellation || 64;
  39237. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39238. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39239. // positions and uvs
  39240. positions.push(0, 0, 0); // disc center first
  39241. uvs.push(0.5, 0.5);
  39242. var theta = Math.PI * 2 * arc;
  39243. var step = theta / tessellation;
  39244. for (var a = 0; a < theta; a += step) {
  39245. var x = Math.cos(a);
  39246. var y = Math.sin(a);
  39247. var u = (x + 1) / 2;
  39248. var v = (1 - y) / 2;
  39249. positions.push(radius * x, radius * y, 0);
  39250. uvs.push(u, v);
  39251. }
  39252. if (arc === 1) {
  39253. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39254. uvs.push(uvs[2], uvs[3]);
  39255. }
  39256. //indices
  39257. var vertexNb = positions.length / 3;
  39258. for (var i = 1; i < vertexNb - 1; i++) {
  39259. indices.push(i + 1, 0, i);
  39260. }
  39261. // result
  39262. VertexData.ComputeNormals(positions, indices, normals);
  39263. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39264. var vertexData = new VertexData();
  39265. vertexData.indices = indices;
  39266. vertexData.positions = positions;
  39267. vertexData.normals = normals;
  39268. vertexData.uvs = uvs;
  39269. return vertexData;
  39270. };
  39271. /**
  39272. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39273. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39274. * @param polygon a mesh built from polygonTriangulation.build()
  39275. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39276. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39277. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39278. * @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)
  39279. * @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)
  39280. * @returns the VertexData of the Polygon
  39281. */
  39282. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39283. var faceUV = fUV || new Array(3);
  39284. var faceColors = fColors;
  39285. var colors = [];
  39286. // default face colors and UV if undefined
  39287. for (var f = 0; f < 3; f++) {
  39288. if (faceUV[f] === undefined) {
  39289. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39290. }
  39291. if (faceColors && faceColors[f] === undefined) {
  39292. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39293. }
  39294. }
  39295. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39296. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39297. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39298. var indices = polygon.getIndices();
  39299. // set face colours and textures
  39300. var idx = 0;
  39301. var face = 0;
  39302. for (var index = 0; index < normals.length; index += 3) {
  39303. //Edge Face no. 1
  39304. if (Math.abs(normals[index + 1]) < 0.001) {
  39305. face = 1;
  39306. }
  39307. //Top Face no. 0
  39308. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39309. face = 0;
  39310. }
  39311. //Bottom Face no. 2
  39312. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39313. face = 2;
  39314. }
  39315. idx = index / 3;
  39316. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39317. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39318. if (faceColors) {
  39319. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39320. }
  39321. }
  39322. // sides
  39323. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39324. // Result
  39325. var vertexData = new VertexData();
  39326. vertexData.indices = indices;
  39327. vertexData.positions = positions;
  39328. vertexData.normals = normals;
  39329. vertexData.uvs = uvs;
  39330. if (faceColors) {
  39331. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39332. vertexData.colors = totalColors;
  39333. }
  39334. return vertexData;
  39335. };
  39336. /**
  39337. * Creates the VertexData of the IcoSphere
  39338. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39339. * * radius the radius of the IcoSphere, optional default 1
  39340. * * radiusX allows stretching in the x direction, optional, default radius
  39341. * * radiusY allows stretching in the y direction, optional, default radius
  39342. * * radiusZ allows stretching in the z direction, optional, default radius
  39343. * * flat when true creates a flat shaded mesh, optional, default true
  39344. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39345. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39346. * * 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)
  39347. * * 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)
  39348. * @returns the VertexData of the IcoSphere
  39349. */
  39350. VertexData.CreateIcoSphere = function (options) {
  39351. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39352. var radius = options.radius || 1;
  39353. var flat = (options.flat === undefined) ? true : options.flat;
  39354. var subdivisions = options.subdivisions || 4;
  39355. var radiusX = options.radiusX || radius;
  39356. var radiusY = options.radiusY || radius;
  39357. var radiusZ = options.radiusZ || radius;
  39358. var t = (1 + Math.sqrt(5)) / 2;
  39359. // 12 vertex x,y,z
  39360. var ico_vertices = [
  39361. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39362. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39363. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39364. ];
  39365. // index of 3 vertex makes a face of icopshere
  39366. var ico_indices = [
  39367. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39368. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39369. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39370. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39371. ];
  39372. // vertex for uv have aliased position, not for UV
  39373. var vertices_unalias_id = [
  39374. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39375. // vertex alias
  39376. 0,
  39377. 2,
  39378. 3,
  39379. 3,
  39380. 3,
  39381. 4,
  39382. 7,
  39383. 8,
  39384. 9,
  39385. 9,
  39386. 10,
  39387. 11 // 23: B + 12
  39388. ];
  39389. // uv as integer step (not pixels !)
  39390. var ico_vertexuv = [
  39391. 5, 1, 3, 1, 6, 4, 0, 0,
  39392. 5, 3, 4, 2, 2, 2, 4, 0,
  39393. 2, 0, 1, 1, 6, 0, 6, 2,
  39394. // vertex alias (for same vertex on different faces)
  39395. 0, 4,
  39396. 3, 3,
  39397. 4, 4,
  39398. 3, 1,
  39399. 4, 2,
  39400. 4, 4,
  39401. 0, 2,
  39402. 1, 1,
  39403. 2, 2,
  39404. 3, 3,
  39405. 1, 3,
  39406. 2, 4 // 23: B + 12
  39407. ];
  39408. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39409. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39410. // First island of uv mapping
  39411. // v = 4h 3+ 2
  39412. // v = 3h 9+ 4
  39413. // v = 2h 9+ 5 B
  39414. // v = 1h 9 1 0
  39415. // v = 0h 3 8 7 A
  39416. // u = 0 1 2 3 4 5 6 *a
  39417. // Second island of uv mapping
  39418. // v = 4h 0+ B+ 4+
  39419. // v = 3h A+ 2+
  39420. // v = 2h 7+ 6 3+
  39421. // v = 1h 8+ 3+
  39422. // v = 0h
  39423. // u = 0 1 2 3 4 5 6 *a
  39424. // Face layout on texture UV mapping
  39425. // ============
  39426. // \ 4 /\ 16 / ======
  39427. // \ / \ / /\ 11 /
  39428. // \/ 7 \/ / \ /
  39429. // ======= / 10 \/
  39430. // /\ 17 /\ =======
  39431. // / \ / \ \ 15 /\
  39432. // / 8 \/ 12 \ \ / \
  39433. // ============ \/ 6 \
  39434. // \ 18 /\ ============
  39435. // \ / \ \ 5 /\ 0 /
  39436. // \/ 13 \ \ / \ /
  39437. // ======= \/ 1 \/
  39438. // =============
  39439. // /\ 19 /\ 2 /\
  39440. // / \ / \ / \
  39441. // / 14 \/ 9 \/ 3 \
  39442. // ===================
  39443. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39444. var ustep = 138 / 1024;
  39445. var vstep = 239 / 1024;
  39446. var uoffset = 60 / 1024;
  39447. var voffset = 26 / 1024;
  39448. // Second island should have margin, not to touch the first island
  39449. // avoid any borderline artefact in pixel rounding
  39450. var island_u_offset = -40 / 1024;
  39451. var island_v_offset = +20 / 1024;
  39452. // face is either island 0 or 1 :
  39453. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39454. var island = [
  39455. 0, 0, 0, 0, 1,
  39456. 0, 0, 1, 1, 0,
  39457. 0, 0, 1, 1, 0,
  39458. 0, 1, 1, 1, 0 // 15 - 19
  39459. ];
  39460. var indices = new Array();
  39461. var positions = new Array();
  39462. var normals = new Array();
  39463. var uvs = new Array();
  39464. var current_indice = 0;
  39465. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39466. var face_vertex_pos = new Array(3);
  39467. var face_vertex_uv = new Array(3);
  39468. var v012;
  39469. for (v012 = 0; v012 < 3; v012++) {
  39470. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39471. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39472. }
  39473. // create all with normals
  39474. for (var face = 0; face < 20; face++) {
  39475. // 3 vertex per face
  39476. for (v012 = 0; v012 < 3; v012++) {
  39477. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39478. var v_id = ico_indices[3 * face + v012];
  39479. // vertex have 3D position (x,y,z)
  39480. 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]);
  39481. // Normalize to get normal, then scale to radius
  39482. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39483. // uv Coordinates from vertex ID
  39484. 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);
  39485. }
  39486. // Subdivide the face (interpolate pos, norm, uv)
  39487. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39488. // - norm is linear interpolation of vertex corner normal
  39489. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39490. // - uv is linear interpolation
  39491. //
  39492. // Topology is as below for sub-divide by 2
  39493. // vertex shown as v0,v1,v2
  39494. // interp index is i1 to progress in range [v0,v1[
  39495. // interp index is i2 to progress in range [v0,v2[
  39496. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39497. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39498. //
  39499. //
  39500. // i2 v2
  39501. // ^ ^
  39502. // / / \
  39503. // / / \
  39504. // / / \
  39505. // / / (0,1) \
  39506. // / #---------\
  39507. // / / \ (0,0)'/ \
  39508. // / / \ / \
  39509. // / / \ / \
  39510. // / / (0,0) \ / (1,0) \
  39511. // / #---------#---------\
  39512. // v0 v1
  39513. //
  39514. // --------------------> i1
  39515. //
  39516. // interp of (i1,i2):
  39517. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39518. // along i1 : lerp(x0,x1, i1/(S-i2))
  39519. //
  39520. // centroid of triangle is needed to get help normal computation
  39521. // (c1,c2) are used for centroid location
  39522. var interp_vertex = function (i1, i2, c1, c2) {
  39523. // vertex is interpolated from
  39524. // - face_vertex_pos[0..2]
  39525. // - face_vertex_uv[0..2]
  39526. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39527. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39528. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39529. pos_interp.normalize();
  39530. var vertex_normal;
  39531. if (flat) {
  39532. // in flat mode, recalculate normal as face centroid normal
  39533. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39534. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39535. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39536. }
  39537. else {
  39538. // in smooth mode, recalculate normal from each single vertex position
  39539. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39540. }
  39541. // Vertex normal need correction due to X,Y,Z radius scaling
  39542. vertex_normal.x /= radiusX;
  39543. vertex_normal.y /= radiusY;
  39544. vertex_normal.z /= radiusZ;
  39545. vertex_normal.normalize();
  39546. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39547. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39548. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39549. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39550. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39551. uvs.push(uv_interp.x, uv_interp.y);
  39552. // push each vertex has member of a face
  39553. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39554. indices.push(current_indice);
  39555. current_indice++;
  39556. };
  39557. for (var i2 = 0; i2 < subdivisions; i2++) {
  39558. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39559. // face : (i1,i2) for /\ :
  39560. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39561. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39562. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39563. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39564. if (i1 + i2 + 1 < subdivisions) {
  39565. // face : (i1,i2)' for \/ :
  39566. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39567. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39568. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39569. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39570. }
  39571. }
  39572. }
  39573. }
  39574. // Sides
  39575. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39576. // Result
  39577. var vertexData = new VertexData();
  39578. vertexData.indices = indices;
  39579. vertexData.positions = positions;
  39580. vertexData.normals = normals;
  39581. vertexData.uvs = uvs;
  39582. return vertexData;
  39583. };
  39584. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39585. /**
  39586. * Creates the VertexData for a Polyhedron
  39587. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39588. * * type provided types are:
  39589. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39590. * * 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)
  39591. * * size the size of the IcoSphere, optional default 1
  39592. * * sizeX allows stretching in the x direction, optional, default size
  39593. * * sizeY allows stretching in the y direction, optional, default size
  39594. * * sizeZ allows stretching in the z direction, optional, default size
  39595. * * 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
  39596. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39597. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39598. * * flat when true creates a flat shaded mesh, optional, default true
  39599. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39600. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39601. * * 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)
  39602. * * 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)
  39603. * @returns the VertexData of the Polyhedron
  39604. */
  39605. VertexData.CreatePolyhedron = function (options) {
  39606. // provided polyhedron types :
  39607. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39608. // 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)
  39609. var polyhedra = [];
  39610. 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]] };
  39611. 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]] };
  39612. polyhedra[2] = {
  39613. 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]],
  39614. 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]]
  39615. };
  39616. polyhedra[3] = {
  39617. 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]],
  39618. 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]]
  39619. };
  39620. polyhedra[4] = {
  39621. 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]],
  39622. 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]]
  39623. };
  39624. 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]] };
  39625. 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]] };
  39626. 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]] };
  39627. 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]] };
  39628. 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]] };
  39629. 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]] };
  39630. 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]] };
  39631. 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]] };
  39632. 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]] };
  39633. polyhedra[14] = {
  39634. 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]],
  39635. 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]]
  39636. };
  39637. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39638. var size = options.size;
  39639. var sizeX = options.sizeX || size || 1;
  39640. var sizeY = options.sizeY || size || 1;
  39641. var sizeZ = options.sizeZ || size || 1;
  39642. var data = options.custom || polyhedra[type];
  39643. var nbfaces = data.face.length;
  39644. var faceUV = options.faceUV || new Array(nbfaces);
  39645. var faceColors = options.faceColors;
  39646. var flat = (options.flat === undefined) ? true : options.flat;
  39647. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39648. var positions = new Array();
  39649. var indices = new Array();
  39650. var normals = new Array();
  39651. var uvs = new Array();
  39652. var colors = new Array();
  39653. var index = 0;
  39654. var faceIdx = 0; // face cursor in the array "indexes"
  39655. var indexes = new Array();
  39656. var i = 0;
  39657. var f = 0;
  39658. var u, v, ang, x, y, tmp;
  39659. // default face colors and UV if undefined
  39660. if (flat) {
  39661. for (f = 0; f < nbfaces; f++) {
  39662. if (faceColors && faceColors[f] === undefined) {
  39663. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39664. }
  39665. if (faceUV && faceUV[f] === undefined) {
  39666. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39667. }
  39668. }
  39669. }
  39670. if (!flat) {
  39671. for (i = 0; i < data.vertex.length; i++) {
  39672. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39673. uvs.push(0, 0);
  39674. }
  39675. for (f = 0; f < nbfaces; f++) {
  39676. for (i = 0; i < data.face[f].length - 2; i++) {
  39677. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39678. }
  39679. }
  39680. }
  39681. else {
  39682. for (f = 0; f < nbfaces; f++) {
  39683. var fl = data.face[f].length; // number of vertices of the current face
  39684. ang = 2 * Math.PI / fl;
  39685. x = 0.5 * Math.tan(ang / 2);
  39686. y = 0.5;
  39687. // positions, uvs, colors
  39688. for (i = 0; i < fl; i++) {
  39689. // positions
  39690. 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);
  39691. indexes.push(index);
  39692. index++;
  39693. // uvs
  39694. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39695. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39696. uvs.push(u, v);
  39697. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39698. y = x * Math.sin(ang) + y * Math.cos(ang);
  39699. x = tmp;
  39700. // colors
  39701. if (faceColors) {
  39702. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39703. }
  39704. }
  39705. // indices from indexes
  39706. for (i = 0; i < fl - 2; i++) {
  39707. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39708. }
  39709. faceIdx += fl;
  39710. }
  39711. }
  39712. VertexData.ComputeNormals(positions, indices, normals);
  39713. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39714. var vertexData = new VertexData();
  39715. vertexData.positions = positions;
  39716. vertexData.indices = indices;
  39717. vertexData.normals = normals;
  39718. vertexData.uvs = uvs;
  39719. if (faceColors && flat) {
  39720. vertexData.colors = colors;
  39721. }
  39722. return vertexData;
  39723. };
  39724. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39725. /**
  39726. * Creates the VertexData for a TorusKnot
  39727. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39728. * * radius the radius of the torus knot, optional, default 2
  39729. * * tube the thickness of the tube, optional, default 0.5
  39730. * * radialSegments the number of sides on each tube segments, optional, default 32
  39731. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39732. * * p the number of windings around the z axis, optional, default 2
  39733. * * q the number of windings around the x axis, optional, default 3
  39734. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39735. * * 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)
  39736. * * 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)
  39737. * @returns the VertexData of the Torus Knot
  39738. */
  39739. VertexData.CreateTorusKnot = function (options) {
  39740. var indices = new Array();
  39741. var positions = new Array();
  39742. var normals = new Array();
  39743. var uvs = new Array();
  39744. var radius = options.radius || 2;
  39745. var tube = options.tube || 0.5;
  39746. var radialSegments = options.radialSegments || 32;
  39747. var tubularSegments = options.tubularSegments || 32;
  39748. var p = options.p || 2;
  39749. var q = options.q || 3;
  39750. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39751. // Helper
  39752. var getPos = function (angle) {
  39753. var cu = Math.cos(angle);
  39754. var su = Math.sin(angle);
  39755. var quOverP = q / p * angle;
  39756. var cs = Math.cos(quOverP);
  39757. var tx = radius * (2 + cs) * 0.5 * cu;
  39758. var ty = radius * (2 + cs) * su * 0.5;
  39759. var tz = radius * Math.sin(quOverP) * 0.5;
  39760. return new BABYLON.Vector3(tx, ty, tz);
  39761. };
  39762. // Vertices
  39763. var i;
  39764. var j;
  39765. for (i = 0; i <= radialSegments; i++) {
  39766. var modI = i % radialSegments;
  39767. var u = modI / radialSegments * 2 * p * Math.PI;
  39768. var p1 = getPos(u);
  39769. var p2 = getPos(u + 0.01);
  39770. var tang = p2.subtract(p1);
  39771. var n = p2.add(p1);
  39772. var bitan = BABYLON.Vector3.Cross(tang, n);
  39773. n = BABYLON.Vector3.Cross(bitan, tang);
  39774. bitan.normalize();
  39775. n.normalize();
  39776. for (j = 0; j < tubularSegments; j++) {
  39777. var modJ = j % tubularSegments;
  39778. var v = modJ / tubularSegments * 2 * Math.PI;
  39779. var cx = -tube * Math.cos(v);
  39780. var cy = tube * Math.sin(v);
  39781. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39782. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39783. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39784. uvs.push(i / radialSegments);
  39785. uvs.push(j / tubularSegments);
  39786. }
  39787. }
  39788. for (i = 0; i < radialSegments; i++) {
  39789. for (j = 0; j < tubularSegments; j++) {
  39790. var jNext = (j + 1) % tubularSegments;
  39791. var a = i * tubularSegments + j;
  39792. var b = (i + 1) * tubularSegments + j;
  39793. var c = (i + 1) * tubularSegments + jNext;
  39794. var d = i * tubularSegments + jNext;
  39795. indices.push(d);
  39796. indices.push(b);
  39797. indices.push(a);
  39798. indices.push(d);
  39799. indices.push(c);
  39800. indices.push(b);
  39801. }
  39802. }
  39803. // Normals
  39804. VertexData.ComputeNormals(positions, indices, normals);
  39805. // Sides
  39806. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39807. // Result
  39808. var vertexData = new VertexData();
  39809. vertexData.indices = indices;
  39810. vertexData.positions = positions;
  39811. vertexData.normals = normals;
  39812. vertexData.uvs = uvs;
  39813. return vertexData;
  39814. };
  39815. // Tools
  39816. /**
  39817. * Compute normals for given positions and indices
  39818. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39819. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39820. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39821. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39822. * * facetNormals : optional array of facet normals (vector3)
  39823. * * facetPositions : optional array of facet positions (vector3)
  39824. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39825. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39826. * * bInfo : optional bounding info, required for facetPartitioning computation
  39827. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39828. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39829. * * useRightHandedSystem: optional boolean to for right handed system computation
  39830. * * depthSort : optional boolean to enable the facet depth sort computation
  39831. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39832. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39833. */
  39834. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39835. // temporary scalar variables
  39836. var index = 0; // facet index
  39837. var p1p2x = 0.0; // p1p2 vector x coordinate
  39838. var p1p2y = 0.0; // p1p2 vector y coordinate
  39839. var p1p2z = 0.0; // p1p2 vector z coordinate
  39840. var p3p2x = 0.0; // p3p2 vector x coordinate
  39841. var p3p2y = 0.0; // p3p2 vector y coordinate
  39842. var p3p2z = 0.0; // p3p2 vector z coordinate
  39843. var faceNormalx = 0.0; // facet normal x coordinate
  39844. var faceNormaly = 0.0; // facet normal y coordinate
  39845. var faceNormalz = 0.0; // facet normal z coordinate
  39846. var length = 0.0; // facet normal length before normalization
  39847. var v1x = 0; // vector1 x index in the positions array
  39848. var v1y = 0; // vector1 y index in the positions array
  39849. var v1z = 0; // vector1 z index in the positions array
  39850. var v2x = 0; // vector2 x index in the positions array
  39851. var v2y = 0; // vector2 y index in the positions array
  39852. var v2z = 0; // vector2 z index in the positions array
  39853. var v3x = 0; // vector3 x index in the positions array
  39854. var v3y = 0; // vector3 y index in the positions array
  39855. var v3z = 0; // vector3 z index in the positions array
  39856. var computeFacetNormals = false;
  39857. var computeFacetPositions = false;
  39858. var computeFacetPartitioning = false;
  39859. var computeDepthSort = false;
  39860. var faceNormalSign = 1;
  39861. var ratio = 0;
  39862. var distanceTo = null;
  39863. if (options) {
  39864. computeFacetNormals = (options.facetNormals) ? true : false;
  39865. computeFacetPositions = (options.facetPositions) ? true : false;
  39866. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39867. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39868. ratio = options.ratio || 0;
  39869. computeDepthSort = (options.depthSort) ? true : false;
  39870. distanceTo = (options.distanceTo);
  39871. if (computeDepthSort) {
  39872. if (distanceTo === undefined) {
  39873. distanceTo = BABYLON.Vector3.Zero();
  39874. }
  39875. var depthSortedFacets = options.depthSortedFacets;
  39876. }
  39877. }
  39878. // facetPartitioning reinit if needed
  39879. var xSubRatio = 0;
  39880. var ySubRatio = 0;
  39881. var zSubRatio = 0;
  39882. var subSq = 0;
  39883. if (computeFacetPartitioning && options && options.bbSize) {
  39884. var ox = 0; // X partitioning index for facet position
  39885. var oy = 0; // Y partinioning index for facet position
  39886. var oz = 0; // Z partinioning index for facet position
  39887. var b1x = 0; // X partitioning index for facet v1 vertex
  39888. var b1y = 0; // Y partitioning index for facet v1 vertex
  39889. var b1z = 0; // z partitioning index for facet v1 vertex
  39890. var b2x = 0; // X partitioning index for facet v2 vertex
  39891. var b2y = 0; // Y partitioning index for facet v2 vertex
  39892. var b2z = 0; // Z partitioning index for facet v2 vertex
  39893. var b3x = 0; // X partitioning index for facet v3 vertex
  39894. var b3y = 0; // Y partitioning index for facet v3 vertex
  39895. var b3z = 0; // Z partitioning index for facet v3 vertex
  39896. var block_idx_o = 0; // facet barycenter block index
  39897. var block_idx_v1 = 0; // v1 vertex block index
  39898. var block_idx_v2 = 0; // v2 vertex block index
  39899. var block_idx_v3 = 0; // v3 vertex block index
  39900. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39901. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39902. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39903. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39904. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39905. subSq = options.subDiv.max * options.subDiv.max;
  39906. options.facetPartitioning.length = 0;
  39907. }
  39908. // reset the normals
  39909. for (index = 0; index < positions.length; index++) {
  39910. normals[index] = 0.0;
  39911. }
  39912. // Loop : 1 indice triplet = 1 facet
  39913. var nbFaces = (indices.length / 3) | 0;
  39914. for (index = 0; index < nbFaces; index++) {
  39915. // get the indexes of the coordinates of each vertex of the facet
  39916. v1x = indices[index * 3] * 3;
  39917. v1y = v1x + 1;
  39918. v1z = v1x + 2;
  39919. v2x = indices[index * 3 + 1] * 3;
  39920. v2y = v2x + 1;
  39921. v2z = v2x + 2;
  39922. v3x = indices[index * 3 + 2] * 3;
  39923. v3y = v3x + 1;
  39924. v3z = v3x + 2;
  39925. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39926. p1p2y = positions[v1y] - positions[v2y];
  39927. p1p2z = positions[v1z] - positions[v2z];
  39928. p3p2x = positions[v3x] - positions[v2x];
  39929. p3p2y = positions[v3y] - positions[v2y];
  39930. p3p2z = positions[v3z] - positions[v2z];
  39931. // compute the face normal with the cross product
  39932. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39933. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39934. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39935. // normalize this normal and store it in the array facetData
  39936. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39937. length = (length === 0) ? 1.0 : length;
  39938. faceNormalx /= length;
  39939. faceNormaly /= length;
  39940. faceNormalz /= length;
  39941. if (computeFacetNormals && options) {
  39942. options.facetNormals[index].x = faceNormalx;
  39943. options.facetNormals[index].y = faceNormaly;
  39944. options.facetNormals[index].z = faceNormalz;
  39945. }
  39946. if (computeFacetPositions && options) {
  39947. // compute and the facet barycenter coordinates in the array facetPositions
  39948. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39949. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39950. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39951. }
  39952. if (computeFacetPartitioning && options) {
  39953. // store the facet indexes in arrays in the main facetPartitioning array :
  39954. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39955. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39956. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39957. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39958. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39959. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39960. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39961. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39962. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39963. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39964. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39965. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39966. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39967. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39968. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39969. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39970. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39971. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39972. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39973. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39974. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39975. // push each facet index in each block containing the vertex
  39976. options.facetPartitioning[block_idx_v1].push(index);
  39977. if (block_idx_v2 != block_idx_v1) {
  39978. options.facetPartitioning[block_idx_v2].push(index);
  39979. }
  39980. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39981. options.facetPartitioning[block_idx_v3].push(index);
  39982. }
  39983. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39984. options.facetPartitioning[block_idx_o].push(index);
  39985. }
  39986. }
  39987. if (computeDepthSort && options && options.facetPositions) {
  39988. var dsf = depthSortedFacets[index];
  39989. dsf.ind = index * 3;
  39990. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39991. }
  39992. // compute the normals anyway
  39993. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39994. normals[v1y] += faceNormaly;
  39995. normals[v1z] += faceNormalz;
  39996. normals[v2x] += faceNormalx;
  39997. normals[v2y] += faceNormaly;
  39998. normals[v2z] += faceNormalz;
  39999. normals[v3x] += faceNormalx;
  40000. normals[v3y] += faceNormaly;
  40001. normals[v3z] += faceNormalz;
  40002. }
  40003. // last normalization of each normal
  40004. for (index = 0; index < normals.length / 3; index++) {
  40005. faceNormalx = normals[index * 3];
  40006. faceNormaly = normals[index * 3 + 1];
  40007. faceNormalz = normals[index * 3 + 2];
  40008. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40009. length = (length === 0) ? 1.0 : length;
  40010. faceNormalx /= length;
  40011. faceNormaly /= length;
  40012. faceNormalz /= length;
  40013. normals[index * 3] = faceNormalx;
  40014. normals[index * 3 + 1] = faceNormaly;
  40015. normals[index * 3 + 2] = faceNormalz;
  40016. }
  40017. };
  40018. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40019. var li = indices.length;
  40020. var ln = normals.length;
  40021. var i;
  40022. var n;
  40023. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40024. switch (sideOrientation) {
  40025. case BABYLON.Mesh.FRONTSIDE:
  40026. // nothing changed
  40027. break;
  40028. case BABYLON.Mesh.BACKSIDE:
  40029. var tmp;
  40030. // indices
  40031. for (i = 0; i < li; i += 3) {
  40032. tmp = indices[i];
  40033. indices[i] = indices[i + 2];
  40034. indices[i + 2] = tmp;
  40035. }
  40036. // normals
  40037. for (n = 0; n < ln; n++) {
  40038. normals[n] = -normals[n];
  40039. }
  40040. break;
  40041. case BABYLON.Mesh.DOUBLESIDE:
  40042. // positions
  40043. var lp = positions.length;
  40044. var l = lp / 3;
  40045. for (var p = 0; p < lp; p++) {
  40046. positions[lp + p] = positions[p];
  40047. }
  40048. // indices
  40049. for (i = 0; i < li; i += 3) {
  40050. indices[i + li] = indices[i + 2] + l;
  40051. indices[i + 1 + li] = indices[i + 1] + l;
  40052. indices[i + 2 + li] = indices[i] + l;
  40053. }
  40054. // normals
  40055. for (n = 0; n < ln; n++) {
  40056. normals[ln + n] = -normals[n];
  40057. }
  40058. // uvs
  40059. var lu = uvs.length;
  40060. var u = 0;
  40061. for (u = 0; u < lu; u++) {
  40062. uvs[u + lu] = uvs[u];
  40063. }
  40064. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40065. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40066. u = 0;
  40067. for (i = 0; i < lu / 2; i++) {
  40068. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  40069. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  40070. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  40071. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  40072. u += 2;
  40073. }
  40074. break;
  40075. }
  40076. };
  40077. /**
  40078. * Applies VertexData created from the imported parameters to the geometry
  40079. * @param parsedVertexData the parsed data from an imported file
  40080. * @param geometry the geometry to apply the VertexData to
  40081. */
  40082. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40083. var vertexData = new VertexData();
  40084. // positions
  40085. var positions = parsedVertexData.positions;
  40086. if (positions) {
  40087. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40088. }
  40089. // normals
  40090. var normals = parsedVertexData.normals;
  40091. if (normals) {
  40092. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40093. }
  40094. // tangents
  40095. var tangents = parsedVertexData.tangents;
  40096. if (tangents) {
  40097. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40098. }
  40099. // uvs
  40100. var uvs = parsedVertexData.uvs;
  40101. if (uvs) {
  40102. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40103. }
  40104. // uv2s
  40105. var uv2s = parsedVertexData.uv2s;
  40106. if (uv2s) {
  40107. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40108. }
  40109. // uv3s
  40110. var uv3s = parsedVertexData.uv3s;
  40111. if (uv3s) {
  40112. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40113. }
  40114. // uv4s
  40115. var uv4s = parsedVertexData.uv4s;
  40116. if (uv4s) {
  40117. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40118. }
  40119. // uv5s
  40120. var uv5s = parsedVertexData.uv5s;
  40121. if (uv5s) {
  40122. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40123. }
  40124. // uv6s
  40125. var uv6s = parsedVertexData.uv6s;
  40126. if (uv6s) {
  40127. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40128. }
  40129. // colors
  40130. var colors = parsedVertexData.colors;
  40131. if (colors) {
  40132. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40133. }
  40134. // matricesIndices
  40135. var matricesIndices = parsedVertexData.matricesIndices;
  40136. if (matricesIndices) {
  40137. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40138. }
  40139. // matricesWeights
  40140. var matricesWeights = parsedVertexData.matricesWeights;
  40141. if (matricesWeights) {
  40142. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40143. }
  40144. // indices
  40145. var indices = parsedVertexData.indices;
  40146. if (indices) {
  40147. vertexData.indices = indices;
  40148. }
  40149. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40150. };
  40151. return VertexData;
  40152. }());
  40153. BABYLON.VertexData = VertexData;
  40154. })(BABYLON || (BABYLON = {}));
  40155. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40156. var BABYLON;
  40157. (function (BABYLON) {
  40158. /**
  40159. * Class used to store geometry data (vertex buffers + index buffer)
  40160. */
  40161. var Geometry = /** @class */ (function () {
  40162. /**
  40163. * Creates a new geometry
  40164. * @param id defines the unique ID
  40165. * @param scene defines the hosting scene
  40166. * @param vertexData defines the VertexData used to get geometry data
  40167. * @param updatable defines if geometry must be updatable (false by default)
  40168. * @param mesh defines the mesh that will be associated with the geometry
  40169. */
  40170. function Geometry(id, scene, vertexData, updatable, mesh) {
  40171. if (updatable === void 0) { updatable = false; }
  40172. if (mesh === void 0) { mesh = null; }
  40173. /**
  40174. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40175. */
  40176. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40177. this._totalVertices = 0;
  40178. this._isDisposed = false;
  40179. this._indexBufferIsUpdatable = false;
  40180. this.id = id;
  40181. this._engine = scene.getEngine();
  40182. this._meshes = [];
  40183. this._scene = scene;
  40184. //Init vertex buffer cache
  40185. this._vertexBuffers = {};
  40186. this._indices = [];
  40187. this._updatable = updatable;
  40188. // vertexData
  40189. if (vertexData) {
  40190. this.setAllVerticesData(vertexData, updatable);
  40191. }
  40192. else {
  40193. this._totalVertices = 0;
  40194. this._indices = [];
  40195. }
  40196. if (this._engine.getCaps().vertexArrayObject) {
  40197. this._vertexArrayObjects = {};
  40198. }
  40199. // applyToMesh
  40200. if (mesh) {
  40201. if (mesh.getClassName() === "LinesMesh") {
  40202. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40203. this._updateExtend();
  40204. }
  40205. this.applyToMesh(mesh);
  40206. mesh.computeWorldMatrix(true);
  40207. }
  40208. }
  40209. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40210. /**
  40211. * 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
  40212. */
  40213. get: function () {
  40214. return this._boundingBias;
  40215. },
  40216. /**
  40217. * 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
  40218. */
  40219. set: function (value) {
  40220. if (this._boundingBias) {
  40221. if (this._boundingBias.equals(value)) {
  40222. return;
  40223. }
  40224. this._boundingBias.copyFrom(value);
  40225. }
  40226. else {
  40227. this._boundingBias = value.clone();
  40228. }
  40229. this._updateBoundingInfo(true, null);
  40230. },
  40231. enumerable: true,
  40232. configurable: true
  40233. });
  40234. /**
  40235. * Static function used to attach a new empty geometry to a mesh
  40236. * @param mesh defines the mesh to attach the geometry to
  40237. * @returns the new Geometry
  40238. */
  40239. Geometry.CreateGeometryForMesh = function (mesh) {
  40240. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40241. geometry.applyToMesh(mesh);
  40242. return geometry;
  40243. };
  40244. Object.defineProperty(Geometry.prototype, "extend", {
  40245. /**
  40246. * Gets the current extend of the geometry
  40247. */
  40248. get: function () {
  40249. return this._extend;
  40250. },
  40251. enumerable: true,
  40252. configurable: true
  40253. });
  40254. /**
  40255. * Gets the hosting scene
  40256. * @returns the hosting Scene
  40257. */
  40258. Geometry.prototype.getScene = function () {
  40259. return this._scene;
  40260. };
  40261. /**
  40262. * Gets the hosting engine
  40263. * @returns the hosting Engine
  40264. */
  40265. Geometry.prototype.getEngine = function () {
  40266. return this._engine;
  40267. };
  40268. /**
  40269. * Defines if the geometry is ready to use
  40270. * @returns true if the geometry is ready to be used
  40271. */
  40272. Geometry.prototype.isReady = function () {
  40273. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40274. };
  40275. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40276. /**
  40277. * Gets a value indicating that the geometry should not be serialized
  40278. */
  40279. get: function () {
  40280. for (var index = 0; index < this._meshes.length; index++) {
  40281. if (!this._meshes[index].doNotSerialize) {
  40282. return false;
  40283. }
  40284. }
  40285. return true;
  40286. },
  40287. enumerable: true,
  40288. configurable: true
  40289. });
  40290. /** @hidden */
  40291. Geometry.prototype._rebuild = function () {
  40292. if (this._vertexArrayObjects) {
  40293. this._vertexArrayObjects = {};
  40294. }
  40295. // Index buffer
  40296. if (this._meshes.length !== 0 && this._indices) {
  40297. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40298. }
  40299. // Vertex buffers
  40300. for (var key in this._vertexBuffers) {
  40301. var vertexBuffer = this._vertexBuffers[key];
  40302. vertexBuffer._rebuild();
  40303. }
  40304. };
  40305. /**
  40306. * Affects all geometry data in one call
  40307. * @param vertexData defines the geometry data
  40308. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40309. */
  40310. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40311. vertexData.applyToGeometry(this, updatable);
  40312. this.notifyUpdate();
  40313. };
  40314. /**
  40315. * Set specific vertex data
  40316. * @param kind defines the data kind (Position, normal, etc...)
  40317. * @param data defines the vertex data to use
  40318. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40319. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40320. */
  40321. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40322. if (updatable === void 0) { updatable = false; }
  40323. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40324. this.setVerticesBuffer(buffer);
  40325. };
  40326. /**
  40327. * Removes a specific vertex data
  40328. * @param kind defines the data kind (Position, normal, etc...)
  40329. */
  40330. Geometry.prototype.removeVerticesData = function (kind) {
  40331. if (this._vertexBuffers[kind]) {
  40332. this._vertexBuffers[kind].dispose();
  40333. delete this._vertexBuffers[kind];
  40334. }
  40335. };
  40336. /**
  40337. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40338. * @param buffer defines the vertex buffer to use
  40339. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40340. */
  40341. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40342. if (totalVertices === void 0) { totalVertices = null; }
  40343. var kind = buffer.getKind();
  40344. if (this._vertexBuffers[kind]) {
  40345. this._vertexBuffers[kind].dispose();
  40346. }
  40347. this._vertexBuffers[kind] = buffer;
  40348. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40349. var data = buffer.getData();
  40350. if (totalVertices != null) {
  40351. this._totalVertices = totalVertices;
  40352. }
  40353. else {
  40354. if (data != null) {
  40355. this._totalVertices = data.length / (buffer.byteStride / 4);
  40356. }
  40357. }
  40358. this._updateExtend(data);
  40359. this._resetPointsArrayCache();
  40360. var meshes = this._meshes;
  40361. var numOfMeshes = meshes.length;
  40362. for (var index = 0; index < numOfMeshes; index++) {
  40363. var mesh = meshes[index];
  40364. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40365. mesh._createGlobalSubMesh(false);
  40366. mesh.computeWorldMatrix(true);
  40367. }
  40368. }
  40369. this.notifyUpdate(kind);
  40370. if (this._vertexArrayObjects) {
  40371. this._disposeVertexArrayObjects();
  40372. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40373. }
  40374. };
  40375. /**
  40376. * Update a specific vertex buffer
  40377. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40378. * It will do nothing if the buffer is not updatable
  40379. * @param kind defines the data kind (Position, normal, etc...)
  40380. * @param data defines the data to use
  40381. * @param offset defines the offset in the target buffer where to store the data
  40382. * @param useBytes set to true if the offset is in bytes
  40383. */
  40384. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40385. if (useBytes === void 0) { useBytes = false; }
  40386. var vertexBuffer = this.getVertexBuffer(kind);
  40387. if (!vertexBuffer) {
  40388. return;
  40389. }
  40390. vertexBuffer.updateDirectly(data, offset, useBytes);
  40391. this.notifyUpdate(kind);
  40392. };
  40393. /**
  40394. * Update a specific vertex buffer
  40395. * This function will create a new buffer if the current one is not updatable
  40396. * @param kind defines the data kind (Position, normal, etc...)
  40397. * @param data defines the data to use
  40398. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40399. */
  40400. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40401. if (updateExtends === void 0) { updateExtends = false; }
  40402. var vertexBuffer = this.getVertexBuffer(kind);
  40403. if (!vertexBuffer) {
  40404. return;
  40405. }
  40406. vertexBuffer.update(data);
  40407. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40408. this._updateBoundingInfo(updateExtends, data);
  40409. }
  40410. this.notifyUpdate(kind);
  40411. };
  40412. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40413. if (updateExtends) {
  40414. this._updateExtend(data);
  40415. }
  40416. var meshes = this._meshes;
  40417. var numOfMeshes = meshes.length;
  40418. this._resetPointsArrayCache();
  40419. for (var index = 0; index < numOfMeshes; index++) {
  40420. var mesh = meshes[index];
  40421. if (updateExtends) {
  40422. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40423. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40424. var subMesh = mesh.subMeshes[subIndex];
  40425. subMesh.refreshBoundingInfo();
  40426. }
  40427. }
  40428. }
  40429. };
  40430. /** @hidden */
  40431. Geometry.prototype._bind = function (effect, indexToBind) {
  40432. if (!effect) {
  40433. return;
  40434. }
  40435. if (indexToBind === undefined) {
  40436. indexToBind = this._indexBuffer;
  40437. }
  40438. var vbs = this.getVertexBuffers();
  40439. if (!vbs) {
  40440. return;
  40441. }
  40442. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40443. this._engine.bindBuffers(vbs, indexToBind, effect);
  40444. return;
  40445. }
  40446. // Using VAO
  40447. if (!this._vertexArrayObjects[effect.key]) {
  40448. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40449. }
  40450. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40451. };
  40452. /**
  40453. * Gets total number of vertices
  40454. * @returns the total number of vertices
  40455. */
  40456. Geometry.prototype.getTotalVertices = function () {
  40457. if (!this.isReady()) {
  40458. return 0;
  40459. }
  40460. return this._totalVertices;
  40461. };
  40462. /**
  40463. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40464. * @param kind defines the data kind (Position, normal, etc...)
  40465. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40466. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40467. * @returns a float array containing vertex data
  40468. */
  40469. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40470. var vertexBuffer = this.getVertexBuffer(kind);
  40471. if (!vertexBuffer) {
  40472. return null;
  40473. }
  40474. var data = vertexBuffer.getData();
  40475. if (!data) {
  40476. return null;
  40477. }
  40478. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40479. var count = this._totalVertices * vertexBuffer.getSize();
  40480. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40481. var copy_1 = new Array(count);
  40482. vertexBuffer.forEach(count, function (value, index) {
  40483. copy_1[index] = value;
  40484. });
  40485. return copy_1;
  40486. }
  40487. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40488. if (data instanceof Array) {
  40489. var offset = vertexBuffer.byteOffset / 4;
  40490. return BABYLON.Tools.Slice(data, offset, offset + count);
  40491. }
  40492. else if (data instanceof ArrayBuffer) {
  40493. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40494. }
  40495. else {
  40496. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40497. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40498. var result = new Float32Array(count);
  40499. var source = new Float32Array(data.buffer, offset, count);
  40500. result.set(source);
  40501. return result;
  40502. }
  40503. return new Float32Array(data.buffer, offset, count);
  40504. }
  40505. }
  40506. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40507. return BABYLON.Tools.Slice(data);
  40508. }
  40509. return data;
  40510. };
  40511. /**
  40512. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40513. * @param kind defines the data kind (Position, normal, etc...)
  40514. * @returns true if the vertex buffer with the specified kind is updatable
  40515. */
  40516. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40517. var vb = this._vertexBuffers[kind];
  40518. if (!vb) {
  40519. return false;
  40520. }
  40521. return vb.isUpdatable();
  40522. };
  40523. /**
  40524. * Gets a specific vertex buffer
  40525. * @param kind defines the data kind (Position, normal, etc...)
  40526. * @returns a VertexBuffer
  40527. */
  40528. Geometry.prototype.getVertexBuffer = function (kind) {
  40529. if (!this.isReady()) {
  40530. return null;
  40531. }
  40532. return this._vertexBuffers[kind];
  40533. };
  40534. /**
  40535. * Returns all vertex buffers
  40536. * @return an object holding all vertex buffers indexed by kind
  40537. */
  40538. Geometry.prototype.getVertexBuffers = function () {
  40539. if (!this.isReady()) {
  40540. return null;
  40541. }
  40542. return this._vertexBuffers;
  40543. };
  40544. /**
  40545. * Gets a boolean indicating if specific vertex buffer is present
  40546. * @param kind defines the data kind (Position, normal, etc...)
  40547. * @returns true if data is present
  40548. */
  40549. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40550. if (!this._vertexBuffers) {
  40551. if (this._delayInfo) {
  40552. return this._delayInfo.indexOf(kind) !== -1;
  40553. }
  40554. return false;
  40555. }
  40556. return this._vertexBuffers[kind] !== undefined;
  40557. };
  40558. /**
  40559. * Gets a list of all attached data kinds (Position, normal, etc...)
  40560. * @returns a list of string containing all kinds
  40561. */
  40562. Geometry.prototype.getVerticesDataKinds = function () {
  40563. var result = [];
  40564. var kind;
  40565. if (!this._vertexBuffers && this._delayInfo) {
  40566. for (kind in this._delayInfo) {
  40567. result.push(kind);
  40568. }
  40569. }
  40570. else {
  40571. for (kind in this._vertexBuffers) {
  40572. result.push(kind);
  40573. }
  40574. }
  40575. return result;
  40576. };
  40577. /**
  40578. * Update index buffer
  40579. * @param indices defines the indices to store in the index buffer
  40580. * @param offset defines the offset in the target buffer where to store the data
  40581. */
  40582. Geometry.prototype.updateIndices = function (indices, offset) {
  40583. if (!this._indexBuffer) {
  40584. return;
  40585. }
  40586. if (!this._indexBufferIsUpdatable) {
  40587. this.setIndices(indices, null, true);
  40588. }
  40589. else {
  40590. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40591. }
  40592. };
  40593. /**
  40594. * Creates a new index buffer
  40595. * @param indices defines the indices to store in the index buffer
  40596. * @param totalVertices defines the total number of vertices (could be null)
  40597. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40598. */
  40599. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40600. if (totalVertices === void 0) { totalVertices = null; }
  40601. if (updatable === void 0) { updatable = false; }
  40602. if (this._indexBuffer) {
  40603. this._engine._releaseBuffer(this._indexBuffer);
  40604. }
  40605. this._disposeVertexArrayObjects();
  40606. this._indices = indices;
  40607. this._indexBufferIsUpdatable = updatable;
  40608. if (this._meshes.length !== 0 && this._indices) {
  40609. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40610. }
  40611. if (totalVertices != undefined) { // including null and undefined
  40612. this._totalVertices = totalVertices;
  40613. }
  40614. var meshes = this._meshes;
  40615. var numOfMeshes = meshes.length;
  40616. for (var index = 0; index < numOfMeshes; index++) {
  40617. meshes[index]._createGlobalSubMesh(true);
  40618. }
  40619. this.notifyUpdate();
  40620. };
  40621. /**
  40622. * Return the total number of indices
  40623. * @returns the total number of indices
  40624. */
  40625. Geometry.prototype.getTotalIndices = function () {
  40626. if (!this.isReady()) {
  40627. return 0;
  40628. }
  40629. return this._indices.length;
  40630. };
  40631. /**
  40632. * Gets the index buffer array
  40633. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40634. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40635. * @returns the index buffer array
  40636. */
  40637. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40638. if (!this.isReady()) {
  40639. return null;
  40640. }
  40641. var orig = this._indices;
  40642. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40643. return orig;
  40644. }
  40645. else {
  40646. var len = orig.length;
  40647. var copy = [];
  40648. for (var i = 0; i < len; i++) {
  40649. copy.push(orig[i]);
  40650. }
  40651. return copy;
  40652. }
  40653. };
  40654. /**
  40655. * Gets the index buffer
  40656. * @return the index buffer
  40657. */
  40658. Geometry.prototype.getIndexBuffer = function () {
  40659. if (!this.isReady()) {
  40660. return null;
  40661. }
  40662. return this._indexBuffer;
  40663. };
  40664. /** @hidden */
  40665. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40666. if (effect === void 0) { effect = null; }
  40667. if (!effect || !this._vertexArrayObjects) {
  40668. return;
  40669. }
  40670. if (this._vertexArrayObjects[effect.key]) {
  40671. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40672. delete this._vertexArrayObjects[effect.key];
  40673. }
  40674. };
  40675. /**
  40676. * Release the associated resources for a specific mesh
  40677. * @param mesh defines the source mesh
  40678. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40679. */
  40680. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40681. var meshes = this._meshes;
  40682. var index = meshes.indexOf(mesh);
  40683. if (index === -1) {
  40684. return;
  40685. }
  40686. meshes.splice(index, 1);
  40687. mesh._geometry = null;
  40688. if (meshes.length === 0 && shouldDispose) {
  40689. this.dispose();
  40690. }
  40691. };
  40692. /**
  40693. * Apply current geometry to a given mesh
  40694. * @param mesh defines the mesh to apply geometry to
  40695. */
  40696. Geometry.prototype.applyToMesh = function (mesh) {
  40697. if (mesh._geometry === this) {
  40698. return;
  40699. }
  40700. var previousGeometry = mesh._geometry;
  40701. if (previousGeometry) {
  40702. previousGeometry.releaseForMesh(mesh);
  40703. }
  40704. var meshes = this._meshes;
  40705. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40706. mesh._geometry = this;
  40707. this._scene.pushGeometry(this);
  40708. meshes.push(mesh);
  40709. if (this.isReady()) {
  40710. this._applyToMesh(mesh);
  40711. }
  40712. else {
  40713. mesh._boundingInfo = this._boundingInfo;
  40714. }
  40715. };
  40716. Geometry.prototype._updateExtend = function (data) {
  40717. if (data === void 0) { data = null; }
  40718. if (!data) {
  40719. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40720. }
  40721. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40722. };
  40723. Geometry.prototype._applyToMesh = function (mesh) {
  40724. var numOfMeshes = this._meshes.length;
  40725. // vertexBuffers
  40726. for (var kind in this._vertexBuffers) {
  40727. if (numOfMeshes === 1) {
  40728. this._vertexBuffers[kind].create();
  40729. }
  40730. var buffer = this._vertexBuffers[kind].getBuffer();
  40731. if (buffer) {
  40732. buffer.references = numOfMeshes;
  40733. }
  40734. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40735. if (!this._extend) {
  40736. this._updateExtend();
  40737. }
  40738. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40739. mesh._createGlobalSubMesh(false);
  40740. //bounding info was just created again, world matrix should be applied again.
  40741. mesh._updateBoundingInfo();
  40742. }
  40743. }
  40744. // indexBuffer
  40745. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40746. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40747. }
  40748. if (this._indexBuffer) {
  40749. this._indexBuffer.references = numOfMeshes;
  40750. }
  40751. };
  40752. Geometry.prototype.notifyUpdate = function (kind) {
  40753. if (this.onGeometryUpdated) {
  40754. this.onGeometryUpdated(this, kind);
  40755. }
  40756. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40757. var mesh = _a[_i];
  40758. mesh._markSubMeshesAsAttributesDirty();
  40759. }
  40760. };
  40761. /**
  40762. * Load the geometry if it was flagged as delay loaded
  40763. * @param scene defines the hosting scene
  40764. * @param onLoaded defines a callback called when the geometry is loaded
  40765. */
  40766. Geometry.prototype.load = function (scene, onLoaded) {
  40767. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40768. return;
  40769. }
  40770. if (this.isReady()) {
  40771. if (onLoaded) {
  40772. onLoaded();
  40773. }
  40774. return;
  40775. }
  40776. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40777. this._queueLoad(scene, onLoaded);
  40778. };
  40779. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40780. var _this = this;
  40781. if (!this.delayLoadingFile) {
  40782. return;
  40783. }
  40784. scene._addPendingData(this);
  40785. scene._loadFile(this.delayLoadingFile, function (data) {
  40786. if (!_this._delayLoadingFunction) {
  40787. return;
  40788. }
  40789. _this._delayLoadingFunction(JSON.parse(data), _this);
  40790. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40791. _this._delayInfo = [];
  40792. scene._removePendingData(_this);
  40793. var meshes = _this._meshes;
  40794. var numOfMeshes = meshes.length;
  40795. for (var index = 0; index < numOfMeshes; index++) {
  40796. _this._applyToMesh(meshes[index]);
  40797. }
  40798. if (onLoaded) {
  40799. onLoaded();
  40800. }
  40801. }, undefined, true);
  40802. };
  40803. /**
  40804. * Invert the geometry to move from a right handed system to a left handed one.
  40805. */
  40806. Geometry.prototype.toLeftHanded = function () {
  40807. // Flip faces
  40808. var tIndices = this.getIndices(false);
  40809. if (tIndices != null && tIndices.length > 0) {
  40810. for (var i = 0; i < tIndices.length; i += 3) {
  40811. var tTemp = tIndices[i + 0];
  40812. tIndices[i + 0] = tIndices[i + 2];
  40813. tIndices[i + 2] = tTemp;
  40814. }
  40815. this.setIndices(tIndices);
  40816. }
  40817. // Negate position.z
  40818. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40819. if (tPositions != null && tPositions.length > 0) {
  40820. for (var i = 0; i < tPositions.length; i += 3) {
  40821. tPositions[i + 2] = -tPositions[i + 2];
  40822. }
  40823. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40824. }
  40825. // Negate normal.z
  40826. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40827. if (tNormals != null && tNormals.length > 0) {
  40828. for (var i = 0; i < tNormals.length; i += 3) {
  40829. tNormals[i + 2] = -tNormals[i + 2];
  40830. }
  40831. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40832. }
  40833. };
  40834. // Cache
  40835. /** @hidden */
  40836. Geometry.prototype._resetPointsArrayCache = function () {
  40837. this._positions = null;
  40838. };
  40839. /** @hidden */
  40840. Geometry.prototype._generatePointsArray = function () {
  40841. if (this._positions) {
  40842. return true;
  40843. }
  40844. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40845. if (!data || data.length === 0) {
  40846. return false;
  40847. }
  40848. this._positions = [];
  40849. for (var index = 0; index < data.length; index += 3) {
  40850. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40851. }
  40852. return true;
  40853. };
  40854. /**
  40855. * Gets a value indicating if the geometry is disposed
  40856. * @returns true if the geometry was disposed
  40857. */
  40858. Geometry.prototype.isDisposed = function () {
  40859. return this._isDisposed;
  40860. };
  40861. Geometry.prototype._disposeVertexArrayObjects = function () {
  40862. if (this._vertexArrayObjects) {
  40863. for (var kind in this._vertexArrayObjects) {
  40864. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40865. }
  40866. this._vertexArrayObjects = {};
  40867. }
  40868. };
  40869. /**
  40870. * Free all associated resources
  40871. */
  40872. Geometry.prototype.dispose = function () {
  40873. var meshes = this._meshes;
  40874. var numOfMeshes = meshes.length;
  40875. var index;
  40876. for (index = 0; index < numOfMeshes; index++) {
  40877. this.releaseForMesh(meshes[index]);
  40878. }
  40879. this._meshes = [];
  40880. this._disposeVertexArrayObjects();
  40881. for (var kind in this._vertexBuffers) {
  40882. this._vertexBuffers[kind].dispose();
  40883. }
  40884. this._vertexBuffers = {};
  40885. this._totalVertices = 0;
  40886. if (this._indexBuffer) {
  40887. this._engine._releaseBuffer(this._indexBuffer);
  40888. }
  40889. this._indexBuffer = null;
  40890. this._indices = [];
  40891. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40892. this.delayLoadingFile = null;
  40893. this._delayLoadingFunction = null;
  40894. this._delayInfo = [];
  40895. this._boundingInfo = null;
  40896. this._scene.removeGeometry(this);
  40897. this._isDisposed = true;
  40898. };
  40899. /**
  40900. * Clone the current geometry into a new geometry
  40901. * @param id defines the unique ID of the new geometry
  40902. * @returns a new geometry object
  40903. */
  40904. Geometry.prototype.copy = function (id) {
  40905. var vertexData = new BABYLON.VertexData();
  40906. vertexData.indices = [];
  40907. var indices = this.getIndices();
  40908. if (indices) {
  40909. for (var index = 0; index < indices.length; index++) {
  40910. vertexData.indices.push(indices[index]);
  40911. }
  40912. }
  40913. var updatable = false;
  40914. var stopChecking = false;
  40915. var kind;
  40916. for (kind in this._vertexBuffers) {
  40917. // using slice() to make a copy of the array and not just reference it
  40918. var data = this.getVerticesData(kind);
  40919. if (data instanceof Float32Array) {
  40920. vertexData.set(new Float32Array(data), kind);
  40921. }
  40922. else {
  40923. vertexData.set(data.slice(0), kind);
  40924. }
  40925. if (!stopChecking) {
  40926. var vb = this.getVertexBuffer(kind);
  40927. if (vb) {
  40928. updatable = vb.isUpdatable();
  40929. stopChecking = !updatable;
  40930. }
  40931. }
  40932. }
  40933. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40934. geometry.delayLoadState = this.delayLoadState;
  40935. geometry.delayLoadingFile = this.delayLoadingFile;
  40936. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40937. for (kind in this._delayInfo) {
  40938. geometry._delayInfo = geometry._delayInfo || [];
  40939. geometry._delayInfo.push(kind);
  40940. }
  40941. // Bounding info
  40942. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40943. return geometry;
  40944. };
  40945. /**
  40946. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40947. * @return a JSON representation of the current geometry data (without the vertices data)
  40948. */
  40949. Geometry.prototype.serialize = function () {
  40950. var serializationObject = {};
  40951. serializationObject.id = this.id;
  40952. serializationObject.updatable = this._updatable;
  40953. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40954. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40955. }
  40956. return serializationObject;
  40957. };
  40958. Geometry.prototype.toNumberArray = function (origin) {
  40959. if (Array.isArray(origin)) {
  40960. return origin;
  40961. }
  40962. else {
  40963. return Array.prototype.slice.call(origin);
  40964. }
  40965. };
  40966. /**
  40967. * Serialize all vertices data into a JSON oject
  40968. * @returns a JSON representation of the current geometry data
  40969. */
  40970. Geometry.prototype.serializeVerticeData = function () {
  40971. var serializationObject = this.serialize();
  40972. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40973. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40974. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40975. serializationObject.positions._updatable = true;
  40976. }
  40977. }
  40978. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40979. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40980. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40981. serializationObject.normals._updatable = true;
  40982. }
  40983. }
  40984. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40985. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40986. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40987. serializationObject.tangets._updatable = true;
  40988. }
  40989. }
  40990. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40991. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40992. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40993. serializationObject.uvs._updatable = true;
  40994. }
  40995. }
  40996. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40997. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40998. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40999. serializationObject.uv2s._updatable = true;
  41000. }
  41001. }
  41002. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41003. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41004. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41005. serializationObject.uv3s._updatable = true;
  41006. }
  41007. }
  41008. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41009. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41010. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41011. serializationObject.uv4s._updatable = true;
  41012. }
  41013. }
  41014. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41015. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41016. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41017. serializationObject.uv5s._updatable = true;
  41018. }
  41019. }
  41020. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41021. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41022. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41023. serializationObject.uv6s._updatable = true;
  41024. }
  41025. }
  41026. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41027. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  41028. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  41029. serializationObject.colors._updatable = true;
  41030. }
  41031. }
  41032. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41033. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  41034. serializationObject.matricesIndices._isExpanded = true;
  41035. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41036. serializationObject.matricesIndices._updatable = true;
  41037. }
  41038. }
  41039. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41040. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  41041. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41042. serializationObject.matricesWeights._updatable = true;
  41043. }
  41044. }
  41045. serializationObject.indices = this.toNumberArray(this.getIndices());
  41046. return serializationObject;
  41047. };
  41048. // Statics
  41049. /**
  41050. * Extracts a clone of a mesh geometry
  41051. * @param mesh defines the source mesh
  41052. * @param id defines the unique ID of the new geometry object
  41053. * @returns the new geometry object
  41054. */
  41055. Geometry.ExtractFromMesh = function (mesh, id) {
  41056. var geometry = mesh._geometry;
  41057. if (!geometry) {
  41058. return null;
  41059. }
  41060. return geometry.copy(id);
  41061. };
  41062. /**
  41063. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41064. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41065. * Be aware Math.random() could cause collisions, but:
  41066. * "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"
  41067. * @returns a string containing a new GUID
  41068. */
  41069. Geometry.RandomId = function () {
  41070. return BABYLON.Tools.RandomId();
  41071. };
  41072. /** @hidden */
  41073. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  41074. var scene = mesh.getScene();
  41075. // Geometry
  41076. var geometryId = parsedGeometry.geometryId;
  41077. if (geometryId) {
  41078. var geometry = scene.getGeometryByID(geometryId);
  41079. if (geometry) {
  41080. geometry.applyToMesh(mesh);
  41081. }
  41082. }
  41083. else if (parsedGeometry instanceof ArrayBuffer) {
  41084. var binaryInfo = mesh._binaryInfo;
  41085. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41086. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41087. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41088. }
  41089. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41090. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41091. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41092. }
  41093. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  41094. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  41095. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  41096. }
  41097. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41098. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41099. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41100. }
  41101. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41102. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41103. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41104. }
  41105. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41106. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41107. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41108. }
  41109. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41110. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41111. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41112. }
  41113. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41114. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41115. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41116. }
  41117. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41118. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41119. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41120. }
  41121. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41122. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41123. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41124. }
  41125. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41126. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41127. var floatIndices = [];
  41128. for (var i = 0; i < matricesIndicesData.length; i++) {
  41129. var index = matricesIndicesData[i];
  41130. floatIndices.push(index & 0x000000FF);
  41131. floatIndices.push((index & 0x0000FF00) >> 8);
  41132. floatIndices.push((index & 0x00FF0000) >> 16);
  41133. floatIndices.push(index >> 24);
  41134. }
  41135. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41136. }
  41137. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41138. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41139. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41140. }
  41141. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41142. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41143. mesh.setIndices(indicesData, null);
  41144. }
  41145. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41146. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41147. mesh.subMeshes = [];
  41148. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41149. var materialIndex = subMeshesData[(i * 5) + 0];
  41150. var verticesStart = subMeshesData[(i * 5) + 1];
  41151. var verticesCount = subMeshesData[(i * 5) + 2];
  41152. var indexStart = subMeshesData[(i * 5) + 3];
  41153. var indexCount = subMeshesData[(i * 5) + 4];
  41154. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41155. }
  41156. }
  41157. }
  41158. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41159. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41160. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41161. if (parsedGeometry.tangents) {
  41162. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41163. }
  41164. if (parsedGeometry.uvs) {
  41165. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41166. }
  41167. if (parsedGeometry.uvs2) {
  41168. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41169. }
  41170. if (parsedGeometry.uvs3) {
  41171. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41172. }
  41173. if (parsedGeometry.uvs4) {
  41174. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41175. }
  41176. if (parsedGeometry.uvs5) {
  41177. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41178. }
  41179. if (parsedGeometry.uvs6) {
  41180. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41181. }
  41182. if (parsedGeometry.colors) {
  41183. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41184. }
  41185. if (parsedGeometry.matricesIndices) {
  41186. if (!parsedGeometry.matricesIndices._isExpanded) {
  41187. var floatIndices = [];
  41188. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41189. var matricesIndex = parsedGeometry.matricesIndices[i];
  41190. floatIndices.push(matricesIndex & 0x000000FF);
  41191. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41192. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41193. floatIndices.push(matricesIndex >> 24);
  41194. }
  41195. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41196. }
  41197. else {
  41198. delete parsedGeometry.matricesIndices._isExpanded;
  41199. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41200. }
  41201. }
  41202. if (parsedGeometry.matricesIndicesExtra) {
  41203. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41204. var floatIndices = [];
  41205. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41206. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41207. floatIndices.push(matricesIndex & 0x000000FF);
  41208. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41209. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41210. floatIndices.push(matricesIndex >> 24);
  41211. }
  41212. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41213. }
  41214. else {
  41215. delete parsedGeometry.matricesIndices._isExpanded;
  41216. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41217. }
  41218. }
  41219. if (parsedGeometry.matricesWeights) {
  41220. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41221. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41222. }
  41223. if (parsedGeometry.matricesWeightsExtra) {
  41224. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41225. }
  41226. mesh.setIndices(parsedGeometry.indices, null);
  41227. }
  41228. // SubMeshes
  41229. if (parsedGeometry.subMeshes) {
  41230. mesh.subMeshes = [];
  41231. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41232. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41233. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41234. }
  41235. }
  41236. // Flat shading
  41237. if (mesh._shouldGenerateFlatShading) {
  41238. mesh.convertToFlatShadedMesh();
  41239. delete mesh._shouldGenerateFlatShading;
  41240. }
  41241. // Update
  41242. mesh.computeWorldMatrix(true);
  41243. scene.onMeshImportedObservable.notifyObservers(mesh);
  41244. };
  41245. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41246. var epsilon = 1e-3;
  41247. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41248. return;
  41249. }
  41250. var noInfluenceBoneIndex = 0.0;
  41251. if (parsedGeometry.skeletonId > -1) {
  41252. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41253. if (!skeleton) {
  41254. return;
  41255. }
  41256. noInfluenceBoneIndex = skeleton.bones.length;
  41257. }
  41258. else {
  41259. return;
  41260. }
  41261. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41262. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41263. var matricesWeights = parsedGeometry.matricesWeights;
  41264. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41265. var influencers = parsedGeometry.numBoneInfluencer;
  41266. var size = matricesWeights.length;
  41267. for (var i = 0; i < size; i += 4) {
  41268. var weight = 0.0;
  41269. var firstZeroWeight = -1;
  41270. for (var j = 0; j < 4; j++) {
  41271. var w = matricesWeights[i + j];
  41272. weight += w;
  41273. if (w < epsilon && firstZeroWeight < 0) {
  41274. firstZeroWeight = j;
  41275. }
  41276. }
  41277. if (matricesWeightsExtra) {
  41278. for (var j = 0; j < 4; j++) {
  41279. var w = matricesWeightsExtra[i + j];
  41280. weight += w;
  41281. if (w < epsilon && firstZeroWeight < 0) {
  41282. firstZeroWeight = j + 4;
  41283. }
  41284. }
  41285. }
  41286. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41287. firstZeroWeight = influencers - 1;
  41288. }
  41289. if (weight > epsilon) {
  41290. var mweight = 1.0 / weight;
  41291. for (var j = 0; j < 4; j++) {
  41292. matricesWeights[i + j] *= mweight;
  41293. }
  41294. if (matricesWeightsExtra) {
  41295. for (var j = 0; j < 4; j++) {
  41296. matricesWeightsExtra[i + j] *= mweight;
  41297. }
  41298. }
  41299. }
  41300. else {
  41301. if (firstZeroWeight >= 4) {
  41302. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41303. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41304. }
  41305. else {
  41306. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41307. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41308. }
  41309. }
  41310. }
  41311. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41312. if (parsedGeometry.matricesWeightsExtra) {
  41313. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41314. }
  41315. };
  41316. /**
  41317. * Create a new geometry from persisted data (Using .babylon file format)
  41318. * @param parsedVertexData defines the persisted data
  41319. * @param scene defines the hosting scene
  41320. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41321. * @returns the new geometry object
  41322. */
  41323. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41324. if (scene.getGeometryByID(parsedVertexData.id)) {
  41325. return null; // null since geometry could be something else than a box...
  41326. }
  41327. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41328. if (BABYLON.Tags) {
  41329. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41330. }
  41331. if (parsedVertexData.delayLoadingFile) {
  41332. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41333. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41334. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41335. geometry._delayInfo = [];
  41336. if (parsedVertexData.hasUVs) {
  41337. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41338. }
  41339. if (parsedVertexData.hasUVs2) {
  41340. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41341. }
  41342. if (parsedVertexData.hasUVs3) {
  41343. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41344. }
  41345. if (parsedVertexData.hasUVs4) {
  41346. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41347. }
  41348. if (parsedVertexData.hasUVs5) {
  41349. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41350. }
  41351. if (parsedVertexData.hasUVs6) {
  41352. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41353. }
  41354. if (parsedVertexData.hasColors) {
  41355. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41356. }
  41357. if (parsedVertexData.hasMatricesIndices) {
  41358. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41359. }
  41360. if (parsedVertexData.hasMatricesWeights) {
  41361. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41362. }
  41363. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41364. }
  41365. else {
  41366. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41367. }
  41368. scene.pushGeometry(geometry, true);
  41369. return geometry;
  41370. };
  41371. return Geometry;
  41372. }());
  41373. BABYLON.Geometry = Geometry;
  41374. // Primitives
  41375. /// Abstract class
  41376. /**
  41377. * Abstract class used to provide common services for all typed geometries
  41378. * @hidden
  41379. */
  41380. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41381. __extends(_PrimitiveGeometry, _super);
  41382. /**
  41383. * Creates a new typed geometry
  41384. * @param id defines the unique ID of the geometry
  41385. * @param scene defines the hosting scene
  41386. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41387. * @param mesh defines the hosting mesh (can be null)
  41388. */
  41389. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41390. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41391. if (mesh === void 0) { mesh = null; }
  41392. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41393. _this._canBeRegenerated = _canBeRegenerated;
  41394. _this._beingRegenerated = true;
  41395. _this.regenerate();
  41396. _this._beingRegenerated = false;
  41397. return _this;
  41398. }
  41399. /**
  41400. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41401. * @returns true if the geometry can be regenerated
  41402. */
  41403. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41404. return this._canBeRegenerated;
  41405. };
  41406. /**
  41407. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41408. */
  41409. _PrimitiveGeometry.prototype.regenerate = function () {
  41410. if (!this._canBeRegenerated) {
  41411. return;
  41412. }
  41413. this._beingRegenerated = true;
  41414. this.setAllVerticesData(this._regenerateVertexData(), false);
  41415. this._beingRegenerated = false;
  41416. };
  41417. /**
  41418. * Clone the geometry
  41419. * @param id defines the unique ID of the new geometry
  41420. * @returns the new geometry
  41421. */
  41422. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41423. return _super.prototype.copy.call(this, id);
  41424. };
  41425. // overrides
  41426. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41427. if (!this._beingRegenerated) {
  41428. return;
  41429. }
  41430. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41431. };
  41432. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41433. if (!this._beingRegenerated) {
  41434. return;
  41435. }
  41436. _super.prototype.setVerticesData.call(this, kind, data, false);
  41437. };
  41438. // to override
  41439. /** @hidden */
  41440. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41441. throw new Error("Abstract method");
  41442. };
  41443. _PrimitiveGeometry.prototype.copy = function (id) {
  41444. throw new Error("Must be overriden in sub-classes.");
  41445. };
  41446. _PrimitiveGeometry.prototype.serialize = function () {
  41447. var serializationObject = _super.prototype.serialize.call(this);
  41448. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41449. return serializationObject;
  41450. };
  41451. return _PrimitiveGeometry;
  41452. }(Geometry));
  41453. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41454. /**
  41455. * Creates a ribbon geometry
  41456. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41457. */
  41458. var RibbonGeometry = /** @class */ (function (_super) {
  41459. __extends(RibbonGeometry, _super);
  41460. /**
  41461. * Creates a ribbon geometry
  41462. * @param id defines the unique ID of the geometry
  41463. * @param scene defines the hosting scene
  41464. * @param pathArray defines the array of paths to use
  41465. * @param closeArray defines if the last path and the first path must be joined
  41466. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41467. * @param offset defines the offset between points
  41468. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41469. * @param mesh defines the hosting mesh (can be null)
  41470. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41471. */
  41472. function RibbonGeometry(id, scene,
  41473. /**
  41474. * Defines the array of paths to use
  41475. */
  41476. pathArray,
  41477. /**
  41478. * Defines if the last and first points of each path in your pathArray must be joined
  41479. */
  41480. closeArray,
  41481. /**
  41482. * Defines if the last and first points of each path in your pathArray must be joined
  41483. */
  41484. closePath,
  41485. /**
  41486. * Defines the offset between points
  41487. */
  41488. offset, canBeRegenerated, mesh,
  41489. /**
  41490. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41491. */
  41492. side) {
  41493. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41494. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41495. _this.pathArray = pathArray;
  41496. _this.closeArray = closeArray;
  41497. _this.closePath = closePath;
  41498. _this.offset = offset;
  41499. _this.side = side;
  41500. return _this;
  41501. }
  41502. /** @hidden */
  41503. RibbonGeometry.prototype._regenerateVertexData = function () {
  41504. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41505. };
  41506. RibbonGeometry.prototype.copy = function (id) {
  41507. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41508. };
  41509. return RibbonGeometry;
  41510. }(_PrimitiveGeometry));
  41511. BABYLON.RibbonGeometry = RibbonGeometry;
  41512. /**
  41513. * Creates a box geometry
  41514. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41515. */
  41516. var BoxGeometry = /** @class */ (function (_super) {
  41517. __extends(BoxGeometry, _super);
  41518. /**
  41519. * Creates a box geometry
  41520. * @param id defines the unique ID of the geometry
  41521. * @param scene defines the hosting scene
  41522. * @param size defines the zise of the box (width, height and depth are the same)
  41523. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41524. * @param mesh defines the hosting mesh (can be null)
  41525. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41526. */
  41527. function BoxGeometry(id, scene,
  41528. /**
  41529. * Defines the zise of the box (width, height and depth are the same)
  41530. */
  41531. size, canBeRegenerated, mesh,
  41532. /**
  41533. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41534. */
  41535. side) {
  41536. if (mesh === void 0) { mesh = null; }
  41537. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41538. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41539. _this.size = size;
  41540. _this.side = side;
  41541. return _this;
  41542. }
  41543. /** @hidden */
  41544. BoxGeometry.prototype._regenerateVertexData = function () {
  41545. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41546. };
  41547. BoxGeometry.prototype.copy = function (id) {
  41548. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41549. };
  41550. BoxGeometry.prototype.serialize = function () {
  41551. var serializationObject = _super.prototype.serialize.call(this);
  41552. serializationObject.size = this.size;
  41553. return serializationObject;
  41554. };
  41555. BoxGeometry.Parse = function (parsedBox, scene) {
  41556. if (scene.getGeometryByID(parsedBox.id)) {
  41557. return null; // null since geometry could be something else than a box...
  41558. }
  41559. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41560. if (BABYLON.Tags) {
  41561. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41562. }
  41563. scene.pushGeometry(box, true);
  41564. return box;
  41565. };
  41566. return BoxGeometry;
  41567. }(_PrimitiveGeometry));
  41568. BABYLON.BoxGeometry = BoxGeometry;
  41569. /**
  41570. * Creates a sphere geometry
  41571. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41572. */
  41573. var SphereGeometry = /** @class */ (function (_super) {
  41574. __extends(SphereGeometry, _super);
  41575. /**
  41576. * Create a new sphere geometry
  41577. * @param id defines the unique ID of the geometry
  41578. * @param scene defines the hosting scene
  41579. * @param segments defines the number of segments to use to create the sphere
  41580. * @param diameter defines the diameter of the sphere
  41581. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41582. * @param mesh defines the hosting mesh (can be null)
  41583. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41584. */
  41585. function SphereGeometry(id, scene,
  41586. /**
  41587. * Defines the number of segments to use to create the sphere
  41588. */
  41589. segments,
  41590. /**
  41591. * Defines the diameter of the sphere
  41592. */
  41593. diameter, canBeRegenerated, mesh,
  41594. /**
  41595. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41596. */
  41597. side) {
  41598. if (mesh === void 0) { mesh = null; }
  41599. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41600. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41601. _this.segments = segments;
  41602. _this.diameter = diameter;
  41603. _this.side = side;
  41604. return _this;
  41605. }
  41606. /** @hidden */
  41607. SphereGeometry.prototype._regenerateVertexData = function () {
  41608. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41609. };
  41610. SphereGeometry.prototype.copy = function (id) {
  41611. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41612. };
  41613. SphereGeometry.prototype.serialize = function () {
  41614. var serializationObject = _super.prototype.serialize.call(this);
  41615. serializationObject.segments = this.segments;
  41616. serializationObject.diameter = this.diameter;
  41617. return serializationObject;
  41618. };
  41619. SphereGeometry.Parse = function (parsedSphere, scene) {
  41620. if (scene.getGeometryByID(parsedSphere.id)) {
  41621. return null; // null since geometry could be something else than a sphere...
  41622. }
  41623. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41624. if (BABYLON.Tags) {
  41625. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41626. }
  41627. scene.pushGeometry(sphere, true);
  41628. return sphere;
  41629. };
  41630. return SphereGeometry;
  41631. }(_PrimitiveGeometry));
  41632. BABYLON.SphereGeometry = SphereGeometry;
  41633. /**
  41634. * Creates a disc geometry
  41635. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41636. */
  41637. var DiscGeometry = /** @class */ (function (_super) {
  41638. __extends(DiscGeometry, _super);
  41639. /**
  41640. * Creates a new disc geometry
  41641. * @param id defines the unique ID of the geometry
  41642. * @param scene defines the hosting scene
  41643. * @param radius defines the radius of the disc
  41644. * @param tessellation defines the tesselation factor to apply to the disc
  41645. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41646. * @param mesh defines the hosting mesh (can be null)
  41647. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41648. */
  41649. function DiscGeometry(id, scene,
  41650. /**
  41651. * Defines the radius of the disc
  41652. */
  41653. radius,
  41654. /**
  41655. * Defines the tesselation factor to apply to the disc
  41656. */
  41657. tessellation, canBeRegenerated, mesh,
  41658. /**
  41659. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41660. */
  41661. side) {
  41662. if (mesh === void 0) { mesh = null; }
  41663. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41664. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41665. _this.radius = radius;
  41666. _this.tessellation = tessellation;
  41667. _this.side = side;
  41668. return _this;
  41669. }
  41670. /** @hidden */
  41671. DiscGeometry.prototype._regenerateVertexData = function () {
  41672. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41673. };
  41674. DiscGeometry.prototype.copy = function (id) {
  41675. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41676. };
  41677. return DiscGeometry;
  41678. }(_PrimitiveGeometry));
  41679. BABYLON.DiscGeometry = DiscGeometry;
  41680. /**
  41681. * Creates a new cylinder geometry
  41682. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41683. */
  41684. var CylinderGeometry = /** @class */ (function (_super) {
  41685. __extends(CylinderGeometry, _super);
  41686. /**
  41687. * Creates a new cylinder geometry
  41688. * @param id defines the unique ID of the geometry
  41689. * @param scene defines the hosting scene
  41690. * @param height defines the height of the cylinder
  41691. * @param diameterTop defines the diameter of the cylinder's top cap
  41692. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41693. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41694. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41695. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41696. * @param mesh defines the hosting mesh (can be null)
  41697. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41698. */
  41699. function CylinderGeometry(id, scene,
  41700. /**
  41701. * Defines the height of the cylinder
  41702. */
  41703. height,
  41704. /**
  41705. * Defines the diameter of the cylinder's top cap
  41706. */
  41707. diameterTop,
  41708. /**
  41709. * Defines the diameter of the cylinder's bottom cap
  41710. */
  41711. diameterBottom,
  41712. /**
  41713. * Defines the tessellation factor to apply to the cylinder
  41714. */
  41715. tessellation,
  41716. /**
  41717. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41718. */
  41719. subdivisions, canBeRegenerated, mesh,
  41720. /**
  41721. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41722. */
  41723. side) {
  41724. if (subdivisions === void 0) { subdivisions = 1; }
  41725. if (mesh === void 0) { mesh = null; }
  41726. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41727. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41728. _this.height = height;
  41729. _this.diameterTop = diameterTop;
  41730. _this.diameterBottom = diameterBottom;
  41731. _this.tessellation = tessellation;
  41732. _this.subdivisions = subdivisions;
  41733. _this.side = side;
  41734. return _this;
  41735. }
  41736. /** @hidden */
  41737. CylinderGeometry.prototype._regenerateVertexData = function () {
  41738. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41739. };
  41740. CylinderGeometry.prototype.copy = function (id) {
  41741. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41742. };
  41743. CylinderGeometry.prototype.serialize = function () {
  41744. var serializationObject = _super.prototype.serialize.call(this);
  41745. serializationObject.height = this.height;
  41746. serializationObject.diameterTop = this.diameterTop;
  41747. serializationObject.diameterBottom = this.diameterBottom;
  41748. serializationObject.tessellation = this.tessellation;
  41749. return serializationObject;
  41750. };
  41751. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41752. if (scene.getGeometryByID(parsedCylinder.id)) {
  41753. return null; // null since geometry could be something else than a cylinder...
  41754. }
  41755. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41756. if (BABYLON.Tags) {
  41757. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41758. }
  41759. scene.pushGeometry(cylinder, true);
  41760. return cylinder;
  41761. };
  41762. return CylinderGeometry;
  41763. }(_PrimitiveGeometry));
  41764. BABYLON.CylinderGeometry = CylinderGeometry;
  41765. /**
  41766. * Creates a new torus geometry
  41767. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41768. */
  41769. var TorusGeometry = /** @class */ (function (_super) {
  41770. __extends(TorusGeometry, _super);
  41771. /**
  41772. * Creates a new torus geometry
  41773. * @param id defines the unique ID of the geometry
  41774. * @param scene defines the hosting scene
  41775. * @param diameter defines the diameter of the torus
  41776. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41777. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41778. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41779. * @param mesh defines the hosting mesh (can be null)
  41780. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41781. */
  41782. function TorusGeometry(id, scene,
  41783. /**
  41784. * Defines the diameter of the torus
  41785. */
  41786. diameter,
  41787. /**
  41788. * Defines the thickness of the torus (ie. internal diameter)
  41789. */
  41790. thickness,
  41791. /**
  41792. * Defines the tesselation factor to apply to the torus
  41793. */
  41794. tessellation, canBeRegenerated, mesh,
  41795. /**
  41796. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41797. */
  41798. side) {
  41799. if (mesh === void 0) { mesh = null; }
  41800. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41801. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41802. _this.diameter = diameter;
  41803. _this.thickness = thickness;
  41804. _this.tessellation = tessellation;
  41805. _this.side = side;
  41806. return _this;
  41807. }
  41808. /** @hidden */
  41809. TorusGeometry.prototype._regenerateVertexData = function () {
  41810. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41811. };
  41812. TorusGeometry.prototype.copy = function (id) {
  41813. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41814. };
  41815. TorusGeometry.prototype.serialize = function () {
  41816. var serializationObject = _super.prototype.serialize.call(this);
  41817. serializationObject.diameter = this.diameter;
  41818. serializationObject.thickness = this.thickness;
  41819. serializationObject.tessellation = this.tessellation;
  41820. return serializationObject;
  41821. };
  41822. TorusGeometry.Parse = function (parsedTorus, scene) {
  41823. if (scene.getGeometryByID(parsedTorus.id)) {
  41824. return null; // null since geometry could be something else than a torus...
  41825. }
  41826. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41827. if (BABYLON.Tags) {
  41828. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41829. }
  41830. scene.pushGeometry(torus, true);
  41831. return torus;
  41832. };
  41833. return TorusGeometry;
  41834. }(_PrimitiveGeometry));
  41835. BABYLON.TorusGeometry = TorusGeometry;
  41836. /**
  41837. * Creates a new ground geometry
  41838. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41839. */
  41840. var GroundGeometry = /** @class */ (function (_super) {
  41841. __extends(GroundGeometry, _super);
  41842. /**
  41843. * Creates a new ground geometry
  41844. * @param id defines the unique ID of the geometry
  41845. * @param scene defines the hosting scene
  41846. * @param width defines the width of the ground
  41847. * @param height defines the height of the ground
  41848. * @param subdivisions defines the subdivisions to apply to the ground
  41849. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41850. * @param mesh defines the hosting mesh (can be null)
  41851. */
  41852. function GroundGeometry(id, scene,
  41853. /**
  41854. * Defines the width of the ground
  41855. */
  41856. width,
  41857. /**
  41858. * Defines the height of the ground
  41859. */
  41860. height,
  41861. /**
  41862. * Defines the subdivisions to apply to the ground
  41863. */
  41864. subdivisions, canBeRegenerated, mesh) {
  41865. if (mesh === void 0) { mesh = null; }
  41866. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41867. _this.width = width;
  41868. _this.height = height;
  41869. _this.subdivisions = subdivisions;
  41870. return _this;
  41871. }
  41872. /** @hidden */
  41873. GroundGeometry.prototype._regenerateVertexData = function () {
  41874. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41875. };
  41876. GroundGeometry.prototype.copy = function (id) {
  41877. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41878. };
  41879. GroundGeometry.prototype.serialize = function () {
  41880. var serializationObject = _super.prototype.serialize.call(this);
  41881. serializationObject.width = this.width;
  41882. serializationObject.height = this.height;
  41883. serializationObject.subdivisions = this.subdivisions;
  41884. return serializationObject;
  41885. };
  41886. GroundGeometry.Parse = function (parsedGround, scene) {
  41887. if (scene.getGeometryByID(parsedGround.id)) {
  41888. return null; // null since geometry could be something else than a ground...
  41889. }
  41890. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41891. if (BABYLON.Tags) {
  41892. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41893. }
  41894. scene.pushGeometry(ground, true);
  41895. return ground;
  41896. };
  41897. return GroundGeometry;
  41898. }(_PrimitiveGeometry));
  41899. BABYLON.GroundGeometry = GroundGeometry;
  41900. /**
  41901. * Creates a tiled ground geometry
  41902. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41903. */
  41904. var TiledGroundGeometry = /** @class */ (function (_super) {
  41905. __extends(TiledGroundGeometry, _super);
  41906. /**
  41907. * Creates a tiled ground geometry
  41908. * @param id defines the unique ID of the geometry
  41909. * @param scene defines the hosting scene
  41910. * @param xmin defines the minimum value on X axis
  41911. * @param zmin defines the minimum value on Z axis
  41912. * @param xmax defines the maximum value on X axis
  41913. * @param zmax defines the maximum value on Z axis
  41914. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41915. * @param precision defines the precision to use when computing the tiles
  41916. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41917. * @param mesh defines the hosting mesh (can be null)
  41918. */
  41919. function TiledGroundGeometry(id, scene,
  41920. /**
  41921. * Defines the minimum value on X axis
  41922. */
  41923. xmin,
  41924. /**
  41925. * Defines the minimum value on Z axis
  41926. */
  41927. zmin,
  41928. /**
  41929. * Defines the maximum value on X axis
  41930. */
  41931. xmax,
  41932. /**
  41933. * Defines the maximum value on Z axis
  41934. */
  41935. zmax,
  41936. /**
  41937. * Defines the subdivisions to apply to the ground
  41938. */
  41939. subdivisions,
  41940. /**
  41941. * Defines the precision to use when computing the tiles
  41942. */
  41943. precision, canBeRegenerated, mesh) {
  41944. if (mesh === void 0) { mesh = null; }
  41945. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41946. _this.xmin = xmin;
  41947. _this.zmin = zmin;
  41948. _this.xmax = xmax;
  41949. _this.zmax = zmax;
  41950. _this.subdivisions = subdivisions;
  41951. _this.precision = precision;
  41952. return _this;
  41953. }
  41954. /** @hidden */
  41955. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41956. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41957. };
  41958. TiledGroundGeometry.prototype.copy = function (id) {
  41959. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41960. };
  41961. return TiledGroundGeometry;
  41962. }(_PrimitiveGeometry));
  41963. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41964. /**
  41965. * Creates a plane geometry
  41966. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41967. */
  41968. var PlaneGeometry = /** @class */ (function (_super) {
  41969. __extends(PlaneGeometry, _super);
  41970. /**
  41971. * Creates a plane geometry
  41972. * @param id defines the unique ID of the geometry
  41973. * @param scene defines the hosting scene
  41974. * @param size defines the size of the plane (width === height)
  41975. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41976. * @param mesh defines the hosting mesh (can be null)
  41977. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41978. */
  41979. function PlaneGeometry(id, scene,
  41980. /**
  41981. * Defines the size of the plane (width === height)
  41982. */
  41983. size, canBeRegenerated, mesh,
  41984. /**
  41985. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41986. */
  41987. side) {
  41988. if (mesh === void 0) { mesh = null; }
  41989. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41990. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41991. _this.size = size;
  41992. _this.side = side;
  41993. return _this;
  41994. }
  41995. /** @hidden */
  41996. PlaneGeometry.prototype._regenerateVertexData = function () {
  41997. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41998. };
  41999. PlaneGeometry.prototype.copy = function (id) {
  42000. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42001. };
  42002. PlaneGeometry.prototype.serialize = function () {
  42003. var serializationObject = _super.prototype.serialize.call(this);
  42004. serializationObject.size = this.size;
  42005. return serializationObject;
  42006. };
  42007. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42008. if (scene.getGeometryByID(parsedPlane.id)) {
  42009. return null; // null since geometry could be something else than a ground...
  42010. }
  42011. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42012. if (BABYLON.Tags) {
  42013. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42014. }
  42015. scene.pushGeometry(plane, true);
  42016. return plane;
  42017. };
  42018. return PlaneGeometry;
  42019. }(_PrimitiveGeometry));
  42020. BABYLON.PlaneGeometry = PlaneGeometry;
  42021. /**
  42022. * Creates a torus knot geometry
  42023. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42024. */
  42025. var TorusKnotGeometry = /** @class */ (function (_super) {
  42026. __extends(TorusKnotGeometry, _super);
  42027. /**
  42028. * Creates a torus knot geometry
  42029. * @param id defines the unique ID of the geometry
  42030. * @param scene defines the hosting scene
  42031. * @param radius defines the radius of the torus knot
  42032. * @param tube defines the thickness of the torus knot tube
  42033. * @param radialSegments defines the number of radial segments
  42034. * @param tubularSegments defines the number of tubular segments
  42035. * @param p defines the first number of windings
  42036. * @param q defines the second number of windings
  42037. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42038. * @param mesh defines the hosting mesh (can be null)
  42039. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42040. */
  42041. function TorusKnotGeometry(id, scene,
  42042. /**
  42043. * Defines the radius of the torus knot
  42044. */
  42045. radius,
  42046. /**
  42047. * Defines the thickness of the torus knot tube
  42048. */
  42049. tube,
  42050. /**
  42051. * Defines the number of radial segments
  42052. */
  42053. radialSegments,
  42054. /**
  42055. * Defines the number of tubular segments
  42056. */
  42057. tubularSegments,
  42058. /**
  42059. * Defines the first number of windings
  42060. */
  42061. p,
  42062. /**
  42063. * Defines the second number of windings
  42064. */
  42065. q, canBeRegenerated, mesh,
  42066. /**
  42067. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42068. */
  42069. side) {
  42070. if (mesh === void 0) { mesh = null; }
  42071. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42072. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42073. _this.radius = radius;
  42074. _this.tube = tube;
  42075. _this.radialSegments = radialSegments;
  42076. _this.tubularSegments = tubularSegments;
  42077. _this.p = p;
  42078. _this.q = q;
  42079. _this.side = side;
  42080. return _this;
  42081. }
  42082. /** @hidden */
  42083. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  42084. 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 });
  42085. };
  42086. TorusKnotGeometry.prototype.copy = function (id) {
  42087. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42088. };
  42089. TorusKnotGeometry.prototype.serialize = function () {
  42090. var serializationObject = _super.prototype.serialize.call(this);
  42091. serializationObject.radius = this.radius;
  42092. serializationObject.tube = this.tube;
  42093. serializationObject.radialSegments = this.radialSegments;
  42094. serializationObject.tubularSegments = this.tubularSegments;
  42095. serializationObject.p = this.p;
  42096. serializationObject.q = this.q;
  42097. return serializationObject;
  42098. };
  42099. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  42100. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42101. return null; // null since geometry could be something else than a ground...
  42102. }
  42103. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42104. if (BABYLON.Tags) {
  42105. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42106. }
  42107. scene.pushGeometry(torusKnot, true);
  42108. return torusKnot;
  42109. };
  42110. return TorusKnotGeometry;
  42111. }(_PrimitiveGeometry));
  42112. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  42113. //}
  42114. })(BABYLON || (BABYLON = {}));
  42115. //# sourceMappingURL=babylon.geometry.js.map
  42116. var BABYLON;
  42117. (function (BABYLON) {
  42118. /**
  42119. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42120. */
  42121. var PerformanceMonitor = /** @class */ (function () {
  42122. /**
  42123. * constructor
  42124. * @param frameSampleSize The number of samples required to saturate the sliding window
  42125. */
  42126. function PerformanceMonitor(frameSampleSize) {
  42127. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42128. this._enabled = true;
  42129. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42130. }
  42131. /**
  42132. * Samples current frame
  42133. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42134. */
  42135. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42136. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42137. if (!this._enabled) {
  42138. return;
  42139. }
  42140. if (this._lastFrameTimeMs != null) {
  42141. var dt = timeMs - this._lastFrameTimeMs;
  42142. this._rollingFrameTime.add(dt);
  42143. }
  42144. this._lastFrameTimeMs = timeMs;
  42145. };
  42146. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42147. /**
  42148. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42149. */
  42150. get: function () {
  42151. return this._rollingFrameTime.average;
  42152. },
  42153. enumerable: true,
  42154. configurable: true
  42155. });
  42156. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42157. /**
  42158. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42159. */
  42160. get: function () {
  42161. return this._rollingFrameTime.variance;
  42162. },
  42163. enumerable: true,
  42164. configurable: true
  42165. });
  42166. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42167. /**
  42168. * Returns the frame time of the most recent frame
  42169. */
  42170. get: function () {
  42171. return this._rollingFrameTime.history(0);
  42172. },
  42173. enumerable: true,
  42174. configurable: true
  42175. });
  42176. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42177. /**
  42178. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42179. */
  42180. get: function () {
  42181. return 1000.0 / this._rollingFrameTime.average;
  42182. },
  42183. enumerable: true,
  42184. configurable: true
  42185. });
  42186. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42187. /**
  42188. * Returns the average framerate in frames per second using the most recent frame time
  42189. */
  42190. get: function () {
  42191. var history = this._rollingFrameTime.history(0);
  42192. if (history === 0) {
  42193. return 0;
  42194. }
  42195. return 1000.0 / history;
  42196. },
  42197. enumerable: true,
  42198. configurable: true
  42199. });
  42200. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42201. /**
  42202. * Returns true if enough samples have been taken to completely fill the sliding window
  42203. */
  42204. get: function () {
  42205. return this._rollingFrameTime.isSaturated();
  42206. },
  42207. enumerable: true,
  42208. configurable: true
  42209. });
  42210. /**
  42211. * Enables contributions to the sliding window sample set
  42212. */
  42213. PerformanceMonitor.prototype.enable = function () {
  42214. this._enabled = true;
  42215. };
  42216. /**
  42217. * Disables contributions to the sliding window sample set
  42218. * Samples will not be interpolated over the disabled period
  42219. */
  42220. PerformanceMonitor.prototype.disable = function () {
  42221. this._enabled = false;
  42222. //clear last sample to avoid interpolating over the disabled period when next enabled
  42223. this._lastFrameTimeMs = null;
  42224. };
  42225. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42226. /**
  42227. * Returns true if sampling is enabled
  42228. */
  42229. get: function () {
  42230. return this._enabled;
  42231. },
  42232. enumerable: true,
  42233. configurable: true
  42234. });
  42235. /**
  42236. * Resets performance monitor
  42237. */
  42238. PerformanceMonitor.prototype.reset = function () {
  42239. //clear last sample to avoid interpolating over the disabled period when next enabled
  42240. this._lastFrameTimeMs = null;
  42241. //wipe record
  42242. this._rollingFrameTime.reset();
  42243. };
  42244. return PerformanceMonitor;
  42245. }());
  42246. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42247. /**
  42248. * RollingAverage
  42249. *
  42250. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42251. */
  42252. var RollingAverage = /** @class */ (function () {
  42253. /**
  42254. * constructor
  42255. * @param length The number of samples required to saturate the sliding window
  42256. */
  42257. function RollingAverage(length) {
  42258. this._samples = new Array(length);
  42259. this.reset();
  42260. }
  42261. /**
  42262. * Adds a sample to the sample set
  42263. * @param v The sample value
  42264. */
  42265. RollingAverage.prototype.add = function (v) {
  42266. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42267. var delta;
  42268. //we need to check if we've already wrapped round
  42269. if (this.isSaturated()) {
  42270. //remove bottom of stack from mean
  42271. var bottomValue = this._samples[this._pos];
  42272. delta = bottomValue - this.average;
  42273. this.average -= delta / (this._sampleCount - 1);
  42274. this._m2 -= delta * (bottomValue - this.average);
  42275. }
  42276. else {
  42277. this._sampleCount++;
  42278. }
  42279. //add new value to mean
  42280. delta = v - this.average;
  42281. this.average += delta / (this._sampleCount);
  42282. this._m2 += delta * (v - this.average);
  42283. //set the new variance
  42284. this.variance = this._m2 / (this._sampleCount - 1);
  42285. this._samples[this._pos] = v;
  42286. this._pos++;
  42287. this._pos %= this._samples.length; //positive wrap around
  42288. };
  42289. /**
  42290. * Returns previously added values or null if outside of history or outside the sliding window domain
  42291. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42292. * @return Value previously recorded with add() or null if outside of range
  42293. */
  42294. RollingAverage.prototype.history = function (i) {
  42295. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42296. return 0;
  42297. }
  42298. var i0 = this._wrapPosition(this._pos - 1.0);
  42299. return this._samples[this._wrapPosition(i0 - i)];
  42300. };
  42301. /**
  42302. * Returns true if enough samples have been taken to completely fill the sliding window
  42303. * @return true if sample-set saturated
  42304. */
  42305. RollingAverage.prototype.isSaturated = function () {
  42306. return this._sampleCount >= this._samples.length;
  42307. };
  42308. /**
  42309. * Resets the rolling average (equivalent to 0 samples taken so far)
  42310. */
  42311. RollingAverage.prototype.reset = function () {
  42312. this.average = 0;
  42313. this.variance = 0;
  42314. this._sampleCount = 0;
  42315. this._pos = 0;
  42316. this._m2 = 0;
  42317. };
  42318. /**
  42319. * Wraps a value around the sample range boundaries
  42320. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42321. * @return Wrapped position in sample range
  42322. */
  42323. RollingAverage.prototype._wrapPosition = function (i) {
  42324. var max = this._samples.length;
  42325. return ((i % max) + max) % max;
  42326. };
  42327. return RollingAverage;
  42328. }());
  42329. BABYLON.RollingAverage = RollingAverage;
  42330. })(BABYLON || (BABYLON = {}));
  42331. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42332. var BABYLON;
  42333. (function (BABYLON) {
  42334. /**
  42335. * "Static Class" containing the most commonly used helper while dealing with material for
  42336. * rendering purpose.
  42337. *
  42338. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42339. *
  42340. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42341. */
  42342. var MaterialHelper = /** @class */ (function () {
  42343. function MaterialHelper() {
  42344. }
  42345. /**
  42346. * Bind the current view position to an effect.
  42347. * @param effect The effect to be bound
  42348. * @param scene The scene the eyes position is used from
  42349. */
  42350. MaterialHelper.BindEyePosition = function (effect, scene) {
  42351. if (scene._forcedViewPosition) {
  42352. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42353. return;
  42354. }
  42355. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42356. };
  42357. /**
  42358. * Helps preparing the defines values about the UVs in used in the effect.
  42359. * UVs are shared as much as we can accross channels in the shaders.
  42360. * @param texture The texture we are preparing the UVs for
  42361. * @param defines The defines to update
  42362. * @param key The channel key "diffuse", "specular"... used in the shader
  42363. */
  42364. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42365. defines._needUVs = true;
  42366. defines[key] = true;
  42367. if (texture.getTextureMatrix().isIdentity(true)) {
  42368. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42369. if (texture.coordinatesIndex === 0) {
  42370. defines["MAINUV1"] = true;
  42371. }
  42372. else {
  42373. defines["MAINUV2"] = true;
  42374. }
  42375. }
  42376. else {
  42377. defines[key + "DIRECTUV"] = 0;
  42378. }
  42379. };
  42380. /**
  42381. * Binds a texture matrix value to its corrsponding uniform
  42382. * @param texture The texture to bind the matrix for
  42383. * @param uniformBuffer The uniform buffer receivin the data
  42384. * @param key The channel key "diffuse", "specular"... used in the shader
  42385. */
  42386. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42387. var matrix = texture.getTextureMatrix();
  42388. if (!matrix.isIdentity(true)) {
  42389. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42390. }
  42391. };
  42392. /**
  42393. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42394. * @param mesh defines the current mesh
  42395. * @param scene defines the current scene
  42396. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42397. * @param pointsCloud defines if point cloud rendering has to be turned on
  42398. * @param fogEnabled defines if fog has to be turned on
  42399. * @param alphaTest defines if alpha testing has to be turned on
  42400. * @param defines defines the current list of defines
  42401. */
  42402. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42403. if (defines._areMiscDirty) {
  42404. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42405. defines["POINTSIZE"] = pointsCloud;
  42406. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42407. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42408. defines["ALPHATEST"] = alphaTest;
  42409. }
  42410. };
  42411. /**
  42412. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42413. * @param scene defines the current scene
  42414. * @param engine defines the current engine
  42415. * @param defines specifies the list of active defines
  42416. * @param useInstances defines if instances have to be turned on
  42417. * @param useClipPlane defines if clip plane have to be turned on
  42418. */
  42419. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42420. if (useClipPlane === void 0) { useClipPlane = null; }
  42421. var changed = false;
  42422. var useClipPlane1 = false;
  42423. var useClipPlane2 = false;
  42424. var useClipPlane3 = false;
  42425. var useClipPlane4 = false;
  42426. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42427. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42428. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42429. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42430. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42431. defines["CLIPPLANE"] = useClipPlane1;
  42432. changed = true;
  42433. }
  42434. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42435. defines["CLIPPLANE2"] = useClipPlane2;
  42436. changed = true;
  42437. }
  42438. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42439. defines["CLIPPLANE3"] = useClipPlane3;
  42440. changed = true;
  42441. }
  42442. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42443. defines["CLIPPLANE4"] = useClipPlane4;
  42444. changed = true;
  42445. }
  42446. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42447. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42448. changed = true;
  42449. }
  42450. if (defines["INSTANCES"] !== useInstances) {
  42451. defines["INSTANCES"] = useInstances;
  42452. changed = true;
  42453. }
  42454. if (changed) {
  42455. defines.markAsUnprocessed();
  42456. }
  42457. };
  42458. /**
  42459. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42460. * @param mesh The mesh containing the geometry data we will draw
  42461. * @param defines The defines to update
  42462. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42463. * @param useBones Precise whether bones should be used or not (override mesh info)
  42464. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42465. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42466. * @returns false if defines are considered not dirty and have not been checked
  42467. */
  42468. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42469. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42470. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42471. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42472. return false;
  42473. }
  42474. defines._normals = defines._needNormals;
  42475. defines._uvs = defines._needUVs;
  42476. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42477. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42478. defines["TANGENT"] = true;
  42479. }
  42480. if (defines._needUVs) {
  42481. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42482. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42483. }
  42484. else {
  42485. defines["UV1"] = false;
  42486. defines["UV2"] = false;
  42487. }
  42488. if (useVertexColor) {
  42489. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42490. defines["VERTEXCOLOR"] = hasVertexColors;
  42491. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42492. }
  42493. if (useBones) {
  42494. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42495. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42496. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42497. }
  42498. else {
  42499. defines["NUM_BONE_INFLUENCERS"] = 0;
  42500. defines["BonesPerMesh"] = 0;
  42501. }
  42502. }
  42503. if (useMorphTargets) {
  42504. var manager = mesh.morphTargetManager;
  42505. if (manager) {
  42506. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42507. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42508. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42509. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42510. }
  42511. else {
  42512. defines["MORPHTARGETS_TANGENT"] = false;
  42513. defines["MORPHTARGETS_NORMAL"] = false;
  42514. defines["MORPHTARGETS"] = false;
  42515. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42516. }
  42517. }
  42518. return true;
  42519. };
  42520. /**
  42521. * Prepares the defines related to the light information passed in parameter
  42522. * @param scene The scene we are intending to draw
  42523. * @param mesh The mesh the effect is compiling for
  42524. * @param defines The defines to update
  42525. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42526. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42527. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42528. * @returns true if normals will be required for the rest of the effect
  42529. */
  42530. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42531. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42532. if (disableLighting === void 0) { disableLighting = false; }
  42533. if (!defines._areLightsDirty) {
  42534. return defines._needNormals;
  42535. }
  42536. var lightIndex = 0;
  42537. var needNormals = false;
  42538. var needRebuild = false;
  42539. var lightmapMode = false;
  42540. var shadowEnabled = false;
  42541. var specularEnabled = false;
  42542. if (scene.lightsEnabled && !disableLighting) {
  42543. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42544. var light = _a[_i];
  42545. needNormals = true;
  42546. if (defines["LIGHT" + lightIndex] === undefined) {
  42547. needRebuild = true;
  42548. }
  42549. defines["LIGHT" + lightIndex] = true;
  42550. defines["SPOTLIGHT" + lightIndex] = false;
  42551. defines["HEMILIGHT" + lightIndex] = false;
  42552. defines["POINTLIGHT" + lightIndex] = false;
  42553. defines["DIRLIGHT" + lightIndex] = false;
  42554. light.prepareLightSpecificDefines(defines, lightIndex);
  42555. // FallOff.
  42556. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42557. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42558. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42559. switch (light.falloffType) {
  42560. case BABYLON.Light.FALLOFF_GLTF:
  42561. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42562. break;
  42563. case BABYLON.Light.FALLOFF_PHYSICAL:
  42564. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42565. break;
  42566. case BABYLON.Light.FALLOFF_STANDARD:
  42567. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42568. break;
  42569. }
  42570. // Specular
  42571. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42572. specularEnabled = true;
  42573. }
  42574. // Shadows
  42575. defines["SHADOW" + lightIndex] = false;
  42576. defines["SHADOWPCF" + lightIndex] = false;
  42577. defines["SHADOWPCSS" + lightIndex] = false;
  42578. defines["SHADOWPOISSON" + lightIndex] = false;
  42579. defines["SHADOWESM" + lightIndex] = false;
  42580. defines["SHADOWCUBE" + lightIndex] = false;
  42581. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42582. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42583. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42584. var shadowGenerator = light.getShadowGenerator();
  42585. if (shadowGenerator) {
  42586. var shadowMap = shadowGenerator.getShadowMap();
  42587. if (shadowMap) {
  42588. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42589. shadowEnabled = true;
  42590. shadowGenerator.prepareDefines(defines, lightIndex);
  42591. }
  42592. }
  42593. }
  42594. }
  42595. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42596. lightmapMode = true;
  42597. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42598. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42599. }
  42600. else {
  42601. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42602. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42603. }
  42604. lightIndex++;
  42605. if (lightIndex === maxSimultaneousLights) {
  42606. break;
  42607. }
  42608. }
  42609. }
  42610. defines["SPECULARTERM"] = specularEnabled;
  42611. defines["SHADOWS"] = shadowEnabled;
  42612. // Resetting all other lights if any
  42613. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42614. if (defines["LIGHT" + index] !== undefined) {
  42615. defines["LIGHT" + index] = false;
  42616. defines["HEMILIGHT" + lightIndex] = false;
  42617. defines["POINTLIGHT" + lightIndex] = false;
  42618. defines["DIRLIGHT" + lightIndex] = false;
  42619. defines["SPOTLIGHT" + lightIndex] = false;
  42620. defines["SHADOW" + lightIndex] = false;
  42621. }
  42622. }
  42623. var caps = scene.getEngine().getCaps();
  42624. if (defines["SHADOWFLOAT"] === undefined) {
  42625. needRebuild = true;
  42626. }
  42627. defines["SHADOWFLOAT"] = shadowEnabled &&
  42628. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42629. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42630. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42631. if (needRebuild) {
  42632. defines.rebuild();
  42633. }
  42634. return needNormals;
  42635. };
  42636. /**
  42637. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42638. * that won t be acctive due to defines being turned off.
  42639. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42640. * @param samplersList The samplers list
  42641. * @param defines The defines helping in the list generation
  42642. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42643. */
  42644. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42645. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42646. var uniformsList;
  42647. var uniformBuffersList = null;
  42648. if (uniformsListOrOptions.uniformsNames) {
  42649. var options = uniformsListOrOptions;
  42650. uniformsList = options.uniformsNames;
  42651. uniformBuffersList = options.uniformBuffersNames;
  42652. samplersList = options.samplers;
  42653. defines = options.defines;
  42654. maxSimultaneousLights = options.maxSimultaneousLights;
  42655. }
  42656. else {
  42657. uniformsList = uniformsListOrOptions;
  42658. if (!samplersList) {
  42659. samplersList = [];
  42660. }
  42661. }
  42662. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42663. if (!defines["LIGHT" + lightIndex]) {
  42664. break;
  42665. }
  42666. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42667. if (uniformBuffersList) {
  42668. uniformBuffersList.push("Light" + lightIndex);
  42669. }
  42670. samplersList.push("shadowSampler" + lightIndex);
  42671. samplersList.push("depthSampler" + lightIndex);
  42672. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42673. samplersList.push("projectionLightSampler" + lightIndex);
  42674. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42675. }
  42676. }
  42677. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42678. uniformsList.push("morphTargetInfluences");
  42679. }
  42680. };
  42681. /**
  42682. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42683. * @param defines The defines to update while falling back
  42684. * @param fallbacks The authorized effect fallbacks
  42685. * @param maxSimultaneousLights The maximum number of lights allowed
  42686. * @param rank the current rank of the Effect
  42687. * @returns The newly affected rank
  42688. */
  42689. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42690. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42691. if (rank === void 0) { rank = 0; }
  42692. var lightFallbackRank = 0;
  42693. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42694. if (!defines["LIGHT" + lightIndex]) {
  42695. break;
  42696. }
  42697. if (lightIndex > 0) {
  42698. lightFallbackRank = rank + lightIndex;
  42699. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42700. }
  42701. if (!defines["SHADOWS"]) {
  42702. if (defines["SHADOW" + lightIndex]) {
  42703. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42704. }
  42705. if (defines["SHADOWPCF" + lightIndex]) {
  42706. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42707. }
  42708. if (defines["SHADOWPCSS" + lightIndex]) {
  42709. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42710. }
  42711. if (defines["SHADOWPOISSON" + lightIndex]) {
  42712. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42713. }
  42714. if (defines["SHADOWESM" + lightIndex]) {
  42715. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42716. }
  42717. }
  42718. }
  42719. return lightFallbackRank++;
  42720. };
  42721. /**
  42722. * Prepares the list of attributes required for morph targets according to the effect defines.
  42723. * @param attribs The current list of supported attribs
  42724. * @param mesh The mesh to prepare the morph targets attributes for
  42725. * @param defines The current Defines of the effect
  42726. */
  42727. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42728. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42729. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42730. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42731. var manager = mesh.morphTargetManager;
  42732. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42733. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42734. for (var index = 0; index < influencers; index++) {
  42735. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42736. if (normal) {
  42737. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42738. }
  42739. if (tangent) {
  42740. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42741. }
  42742. if (attribs.length > maxAttributesCount) {
  42743. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42744. }
  42745. }
  42746. }
  42747. };
  42748. /**
  42749. * Prepares the list of attributes required for bones according to the effect defines.
  42750. * @param attribs The current list of supported attribs
  42751. * @param mesh The mesh to prepare the bones attributes for
  42752. * @param defines The current Defines of the effect
  42753. * @param fallbacks The current efffect fallback strategy
  42754. */
  42755. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42756. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42757. fallbacks.addCPUSkinningFallback(0, mesh);
  42758. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42759. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42760. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42761. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42762. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42763. }
  42764. }
  42765. };
  42766. /**
  42767. * Prepares the list of attributes required for instances according to the effect defines.
  42768. * @param attribs The current list of supported attribs
  42769. * @param defines The current Defines of the effect
  42770. */
  42771. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42772. if (defines["INSTANCES"]) {
  42773. attribs.push("world0");
  42774. attribs.push("world1");
  42775. attribs.push("world2");
  42776. attribs.push("world3");
  42777. }
  42778. };
  42779. /**
  42780. * Binds the light shadow information to the effect for the given mesh.
  42781. * @param light The light containing the generator
  42782. * @param scene The scene the lights belongs to
  42783. * @param mesh The mesh we are binding the information to render
  42784. * @param lightIndex The light index in the effect used to render the mesh
  42785. * @param effect The effect we are binding the data to
  42786. */
  42787. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42788. if (light.shadowEnabled && mesh.receiveShadows) {
  42789. var shadowGenerator = light.getShadowGenerator();
  42790. if (shadowGenerator) {
  42791. shadowGenerator.bindShadowLight(lightIndex, effect);
  42792. }
  42793. }
  42794. };
  42795. /**
  42796. * Binds the light information to the effect.
  42797. * @param light The light containing the generator
  42798. * @param effect The effect we are binding the data to
  42799. * @param lightIndex The light index in the effect used to render
  42800. */
  42801. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42802. light.transferToEffect(effect, lightIndex + "");
  42803. };
  42804. /**
  42805. * Binds the lights information from the scene to the effect for the given mesh.
  42806. * @param scene The scene the lights belongs to
  42807. * @param mesh The mesh we are binding the information to render
  42808. * @param effect The effect we are binding the data to
  42809. * @param defines The generated defines for the effect
  42810. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42811. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42812. */
  42813. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42814. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42815. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42816. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42817. for (var i = 0; i < len; i++) {
  42818. var light = mesh._lightSources[i];
  42819. var iAsString = i.toString();
  42820. var scaledIntensity = light.getScaledIntensity();
  42821. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42822. MaterialHelper.BindLightProperties(light, effect, i);
  42823. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42824. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42825. if (defines["SPECULARTERM"]) {
  42826. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42827. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42828. }
  42829. // Shadows
  42830. if (scene.shadowsEnabled) {
  42831. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42832. }
  42833. light._uniformBuffer.update();
  42834. }
  42835. };
  42836. /**
  42837. * Binds the fog information from the scene to the effect for the given mesh.
  42838. * @param scene The scene the lights belongs to
  42839. * @param mesh The mesh we are binding the information to render
  42840. * @param effect The effect we are binding the data to
  42841. * @param linearSpace Defines if the fog effect is applied in linear space
  42842. */
  42843. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42844. if (linearSpace === void 0) { linearSpace = false; }
  42845. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42846. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42847. // Convert fog color to linear space if used in a linear space computed shader.
  42848. if (linearSpace) {
  42849. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42850. effect.setColor3("vFogColor", this._tempFogColor);
  42851. }
  42852. else {
  42853. effect.setColor3("vFogColor", scene.fogColor);
  42854. }
  42855. }
  42856. };
  42857. /**
  42858. * Binds the bones information from the mesh to the effect.
  42859. * @param mesh The mesh we are binding the information to render
  42860. * @param effect The effect we are binding the data to
  42861. */
  42862. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42863. if (!effect || !mesh) {
  42864. return;
  42865. }
  42866. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42867. mesh.computeBonesUsingShaders = false;
  42868. }
  42869. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42870. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42871. if (matrices) {
  42872. effect.setMatrices("mBones", matrices);
  42873. }
  42874. }
  42875. };
  42876. /**
  42877. * Binds the morph targets information from the mesh to the effect.
  42878. * @param abstractMesh The mesh we are binding the information to render
  42879. * @param effect The effect we are binding the data to
  42880. */
  42881. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42882. var manager = abstractMesh.morphTargetManager;
  42883. if (!abstractMesh || !manager) {
  42884. return;
  42885. }
  42886. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42887. };
  42888. /**
  42889. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42890. * @param defines The generated defines used in the effect
  42891. * @param effect The effect we are binding the data to
  42892. * @param scene The scene we are willing to render with logarithmic scale for
  42893. */
  42894. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42895. if (defines["LOGARITHMICDEPTH"]) {
  42896. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42897. }
  42898. };
  42899. /**
  42900. * Binds the clip plane information from the scene to the effect.
  42901. * @param scene The scene the clip plane information are extracted from
  42902. * @param effect The effect we are binding the data to
  42903. */
  42904. MaterialHelper.BindClipPlane = function (effect, scene) {
  42905. if (scene.clipPlane) {
  42906. var clipPlane = scene.clipPlane;
  42907. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42908. }
  42909. if (scene.clipPlane2) {
  42910. var clipPlane = scene.clipPlane2;
  42911. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42912. }
  42913. if (scene.clipPlane3) {
  42914. var clipPlane = scene.clipPlane3;
  42915. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42916. }
  42917. if (scene.clipPlane4) {
  42918. var clipPlane = scene.clipPlane4;
  42919. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42920. }
  42921. };
  42922. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42923. return MaterialHelper;
  42924. }());
  42925. BABYLON.MaterialHelper = MaterialHelper;
  42926. })(BABYLON || (BABYLON = {}));
  42927. //# sourceMappingURL=babylon.materialHelper.js.map
  42928. var BABYLON;
  42929. (function (BABYLON) {
  42930. /**
  42931. * Base class of materials working in push mode in babylon JS
  42932. * @hidden
  42933. */
  42934. var PushMaterial = /** @class */ (function (_super) {
  42935. __extends(PushMaterial, _super);
  42936. function PushMaterial(name, scene) {
  42937. var _this = _super.call(this, name, scene) || this;
  42938. _this._normalMatrix = new BABYLON.Matrix();
  42939. _this.storeEffectOnSubMeshes = true;
  42940. return _this;
  42941. }
  42942. PushMaterial.prototype.getEffect = function () {
  42943. return this._activeEffect;
  42944. };
  42945. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42946. if (!mesh) {
  42947. return false;
  42948. }
  42949. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42950. return true;
  42951. }
  42952. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42953. };
  42954. /**
  42955. * Binds the given world matrix to the active effect
  42956. *
  42957. * @param world the matrix to bind
  42958. */
  42959. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42960. this._activeEffect.setMatrix("world", world);
  42961. };
  42962. /**
  42963. * Binds the given normal matrix to the active effect
  42964. *
  42965. * @param normalMatrix the matrix to bind
  42966. */
  42967. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42968. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42969. };
  42970. PushMaterial.prototype.bind = function (world, mesh) {
  42971. if (!mesh) {
  42972. return;
  42973. }
  42974. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42975. };
  42976. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42977. if (effect === void 0) { effect = null; }
  42978. _super.prototype._afterBind.call(this, mesh);
  42979. this.getScene()._cachedEffect = effect;
  42980. };
  42981. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42982. if (visibility === void 0) { visibility = 1; }
  42983. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42984. };
  42985. return PushMaterial;
  42986. }(BABYLON.Material));
  42987. BABYLON.PushMaterial = PushMaterial;
  42988. })(BABYLON || (BABYLON = {}));
  42989. //# sourceMappingURL=babylon.pushMaterial.js.map
  42990. var BABYLON;
  42991. (function (BABYLON) {
  42992. /** @hidden */
  42993. var StandardMaterialDefines = /** @class */ (function (_super) {
  42994. __extends(StandardMaterialDefines, _super);
  42995. function StandardMaterialDefines() {
  42996. var _this = _super.call(this) || this;
  42997. _this.MAINUV1 = false;
  42998. _this.MAINUV2 = false;
  42999. _this.DIFFUSE = false;
  43000. _this.DIFFUSEDIRECTUV = 0;
  43001. _this.AMBIENT = false;
  43002. _this.AMBIENTDIRECTUV = 0;
  43003. _this.OPACITY = false;
  43004. _this.OPACITYDIRECTUV = 0;
  43005. _this.OPACITYRGB = false;
  43006. _this.REFLECTION = false;
  43007. _this.EMISSIVE = false;
  43008. _this.EMISSIVEDIRECTUV = 0;
  43009. _this.SPECULAR = false;
  43010. _this.SPECULARDIRECTUV = 0;
  43011. _this.BUMP = false;
  43012. _this.BUMPDIRECTUV = 0;
  43013. _this.PARALLAX = false;
  43014. _this.PARALLAXOCCLUSION = false;
  43015. _this.SPECULAROVERALPHA = false;
  43016. _this.CLIPPLANE = false;
  43017. _this.CLIPPLANE2 = false;
  43018. _this.CLIPPLANE3 = false;
  43019. _this.CLIPPLANE4 = false;
  43020. _this.ALPHATEST = false;
  43021. _this.DEPTHPREPASS = false;
  43022. _this.ALPHAFROMDIFFUSE = false;
  43023. _this.POINTSIZE = false;
  43024. _this.FOG = false;
  43025. _this.SPECULARTERM = false;
  43026. _this.DIFFUSEFRESNEL = false;
  43027. _this.OPACITYFRESNEL = false;
  43028. _this.REFLECTIONFRESNEL = false;
  43029. _this.REFRACTIONFRESNEL = false;
  43030. _this.EMISSIVEFRESNEL = false;
  43031. _this.FRESNEL = false;
  43032. _this.NORMAL = false;
  43033. _this.UV1 = false;
  43034. _this.UV2 = false;
  43035. _this.VERTEXCOLOR = false;
  43036. _this.VERTEXALPHA = false;
  43037. _this.NUM_BONE_INFLUENCERS = 0;
  43038. _this.BonesPerMesh = 0;
  43039. _this.INSTANCES = false;
  43040. _this.GLOSSINESS = false;
  43041. _this.ROUGHNESS = false;
  43042. _this.EMISSIVEASILLUMINATION = false;
  43043. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43044. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43045. _this.LIGHTMAP = false;
  43046. _this.LIGHTMAPDIRECTUV = 0;
  43047. _this.OBJECTSPACE_NORMALMAP = false;
  43048. _this.USELIGHTMAPASSHADOWMAP = false;
  43049. _this.REFLECTIONMAP_3D = false;
  43050. _this.REFLECTIONMAP_SPHERICAL = false;
  43051. _this.REFLECTIONMAP_PLANAR = false;
  43052. _this.REFLECTIONMAP_CUBIC = false;
  43053. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43054. _this.REFLECTIONMAP_PROJECTION = false;
  43055. _this.REFLECTIONMAP_SKYBOX = false;
  43056. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43057. _this.REFLECTIONMAP_EXPLICIT = false;
  43058. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43059. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43060. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43061. _this.INVERTCUBICMAP = false;
  43062. _this.LOGARITHMICDEPTH = false;
  43063. _this.REFRACTION = false;
  43064. _this.REFRACTIONMAP_3D = false;
  43065. _this.REFLECTIONOVERALPHA = false;
  43066. _this.TWOSIDEDLIGHTING = false;
  43067. _this.SHADOWFLOAT = false;
  43068. _this.MORPHTARGETS = false;
  43069. _this.MORPHTARGETS_NORMAL = false;
  43070. _this.MORPHTARGETS_TANGENT = false;
  43071. _this.NUM_MORPH_INFLUENCERS = 0;
  43072. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43073. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43074. _this.IMAGEPROCESSING = false;
  43075. _this.VIGNETTE = false;
  43076. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43077. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43078. _this.TONEMAPPING = false;
  43079. _this.TONEMAPPING_ACES = false;
  43080. _this.CONTRAST = false;
  43081. _this.COLORCURVES = false;
  43082. _this.COLORGRADING = false;
  43083. _this.COLORGRADING3D = false;
  43084. _this.SAMPLER3DGREENDEPTH = false;
  43085. _this.SAMPLER3DBGRMAP = false;
  43086. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43087. /**
  43088. * If the reflection texture on this material is in linear color space
  43089. * @hidden
  43090. */
  43091. _this.IS_REFLECTION_LINEAR = false;
  43092. /**
  43093. * If the refraction texture on this material is in linear color space
  43094. * @hidden
  43095. */
  43096. _this.IS_REFRACTION_LINEAR = false;
  43097. _this.EXPOSURE = false;
  43098. _this.rebuild();
  43099. return _this;
  43100. }
  43101. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43102. var modes = [
  43103. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43104. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43105. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43106. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43107. ];
  43108. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43109. var mode = modes_1[_i];
  43110. this[mode] = (mode === modeToEnable);
  43111. }
  43112. };
  43113. return StandardMaterialDefines;
  43114. }(BABYLON.MaterialDefines));
  43115. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43116. /**
  43117. * This is the default material used in Babylon. It is the best trade off between quality
  43118. * and performances.
  43119. * @see http://doc.babylonjs.com/babylon101/materials
  43120. */
  43121. var StandardMaterial = /** @class */ (function (_super) {
  43122. __extends(StandardMaterial, _super);
  43123. /**
  43124. * Instantiates a new standard material.
  43125. * This is the default material used in Babylon. It is the best trade off between quality
  43126. * and performances.
  43127. * @see http://doc.babylonjs.com/babylon101/materials
  43128. * @param name Define the name of the material in the scene
  43129. * @param scene Define the scene the material belong to
  43130. */
  43131. function StandardMaterial(name, scene) {
  43132. var _this = _super.call(this, name, scene) || this;
  43133. /**
  43134. * The color of the material lit by the environmental background lighting.
  43135. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43136. */
  43137. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43138. /**
  43139. * The basic color of the material as viewed under a light.
  43140. */
  43141. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43142. /**
  43143. * Define how the color and intensity of the highlight given by the light in the material.
  43144. */
  43145. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43146. /**
  43147. * Define the color of the material as if self lit.
  43148. * This will be mixed in the final result even in the absence of light.
  43149. */
  43150. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43151. /**
  43152. * Defines how sharp are the highlights in the material.
  43153. * The bigger the value the sharper giving a more glossy feeling to the result.
  43154. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43155. */
  43156. _this.specularPower = 64;
  43157. _this._useAlphaFromDiffuseTexture = false;
  43158. _this._useEmissiveAsIllumination = false;
  43159. _this._linkEmissiveWithDiffuse = false;
  43160. _this._useSpecularOverAlpha = false;
  43161. _this._useReflectionOverAlpha = false;
  43162. _this._disableLighting = false;
  43163. _this._useObjectSpaceNormalMap = false;
  43164. _this._useParallax = false;
  43165. _this._useParallaxOcclusion = false;
  43166. /**
  43167. * 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.
  43168. */
  43169. _this.parallaxScaleBias = 0.05;
  43170. _this._roughness = 0;
  43171. /**
  43172. * In case of refraction, define the value of the indice of refraction.
  43173. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43174. */
  43175. _this.indexOfRefraction = 0.98;
  43176. /**
  43177. * Invert the refraction texture alongside the y axis.
  43178. * It can be usefull with procedural textures or probe for instance.
  43179. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43180. */
  43181. _this.invertRefractionY = true;
  43182. /**
  43183. * Defines the alpha limits in alpha test mode.
  43184. */
  43185. _this.alphaCutOff = 0.4;
  43186. _this._useLightmapAsShadowmap = false;
  43187. _this._useReflectionFresnelFromSpecular = false;
  43188. _this._useGlossinessFromSpecularMapAlpha = false;
  43189. _this._maxSimultaneousLights = 4;
  43190. _this._invertNormalMapX = false;
  43191. _this._invertNormalMapY = false;
  43192. _this._twoSidedLighting = false;
  43193. _this._renderTargets = new BABYLON.SmartArray(16);
  43194. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43195. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43196. // Setup the default processing configuration to the scene.
  43197. _this._attachImageProcessingConfiguration(null);
  43198. _this.getRenderTargetTextures = function () {
  43199. _this._renderTargets.reset();
  43200. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43201. _this._renderTargets.push(_this._reflectionTexture);
  43202. }
  43203. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43204. _this._renderTargets.push(_this._refractionTexture);
  43205. }
  43206. return _this._renderTargets;
  43207. };
  43208. return _this;
  43209. }
  43210. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43211. /**
  43212. * Gets the image processing configuration used either in this material.
  43213. */
  43214. get: function () {
  43215. return this._imageProcessingConfiguration;
  43216. },
  43217. /**
  43218. * Sets the Default image processing configuration used either in the this material.
  43219. *
  43220. * If sets to null, the scene one is in use.
  43221. */
  43222. set: function (value) {
  43223. this._attachImageProcessingConfiguration(value);
  43224. // Ensure the effect will be rebuilt.
  43225. this._markAllSubMeshesAsTexturesDirty();
  43226. },
  43227. enumerable: true,
  43228. configurable: true
  43229. });
  43230. /**
  43231. * Attaches a new image processing configuration to the Standard Material.
  43232. * @param configuration
  43233. */
  43234. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43235. var _this = this;
  43236. if (configuration === this._imageProcessingConfiguration) {
  43237. return;
  43238. }
  43239. // Detaches observer.
  43240. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43241. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43242. }
  43243. // Pick the scene configuration if needed.
  43244. if (!configuration) {
  43245. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43246. }
  43247. else {
  43248. this._imageProcessingConfiguration = configuration;
  43249. }
  43250. // Attaches observer.
  43251. if (this._imageProcessingConfiguration) {
  43252. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43253. _this._markAllSubMeshesAsImageProcessingDirty();
  43254. });
  43255. }
  43256. };
  43257. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43258. /**
  43259. * Gets wether the color curves effect is enabled.
  43260. */
  43261. get: function () {
  43262. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43263. },
  43264. /**
  43265. * Sets wether the color curves effect is enabled.
  43266. */
  43267. set: function (value) {
  43268. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43269. },
  43270. enumerable: true,
  43271. configurable: true
  43272. });
  43273. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43274. /**
  43275. * Gets wether the color grading effect is enabled.
  43276. */
  43277. get: function () {
  43278. return this.imageProcessingConfiguration.colorGradingEnabled;
  43279. },
  43280. /**
  43281. * Gets wether the color grading effect is enabled.
  43282. */
  43283. set: function (value) {
  43284. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43285. },
  43286. enumerable: true,
  43287. configurable: true
  43288. });
  43289. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43290. /**
  43291. * Gets wether tonemapping is enabled or not.
  43292. */
  43293. get: function () {
  43294. return this._imageProcessingConfiguration.toneMappingEnabled;
  43295. },
  43296. /**
  43297. * Sets wether tonemapping is enabled or not
  43298. */
  43299. set: function (value) {
  43300. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43301. },
  43302. enumerable: true,
  43303. configurable: true
  43304. });
  43305. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43306. /**
  43307. * The camera exposure used on this material.
  43308. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43309. * This corresponds to a photographic exposure.
  43310. */
  43311. get: function () {
  43312. return this._imageProcessingConfiguration.exposure;
  43313. },
  43314. /**
  43315. * The camera exposure used on this material.
  43316. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43317. * This corresponds to a photographic exposure.
  43318. */
  43319. set: function (value) {
  43320. this._imageProcessingConfiguration.exposure = value;
  43321. },
  43322. enumerable: true,
  43323. configurable: true
  43324. });
  43325. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43326. /**
  43327. * Gets The camera contrast used on this material.
  43328. */
  43329. get: function () {
  43330. return this._imageProcessingConfiguration.contrast;
  43331. },
  43332. /**
  43333. * Sets The camera contrast used on this material.
  43334. */
  43335. set: function (value) {
  43336. this._imageProcessingConfiguration.contrast = value;
  43337. },
  43338. enumerable: true,
  43339. configurable: true
  43340. });
  43341. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43342. /**
  43343. * Gets the Color Grading 2D Lookup Texture.
  43344. */
  43345. get: function () {
  43346. return this._imageProcessingConfiguration.colorGradingTexture;
  43347. },
  43348. /**
  43349. * Sets the Color Grading 2D Lookup Texture.
  43350. */
  43351. set: function (value) {
  43352. this._imageProcessingConfiguration.colorGradingTexture = value;
  43353. },
  43354. enumerable: true,
  43355. configurable: true
  43356. });
  43357. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43358. /**
  43359. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43360. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43361. * 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;
  43362. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43363. */
  43364. get: function () {
  43365. return this._imageProcessingConfiguration.colorCurves;
  43366. },
  43367. /**
  43368. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43369. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43370. * 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;
  43371. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43372. */
  43373. set: function (value) {
  43374. this._imageProcessingConfiguration.colorCurves = value;
  43375. },
  43376. enumerable: true,
  43377. configurable: true
  43378. });
  43379. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43380. /**
  43381. * Gets a boolean indicating that current material needs to register RTT
  43382. */
  43383. get: function () {
  43384. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43385. return true;
  43386. }
  43387. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43388. return true;
  43389. }
  43390. return false;
  43391. },
  43392. enumerable: true,
  43393. configurable: true
  43394. });
  43395. /**
  43396. * Gets the current class name of the material e.g. "StandardMaterial"
  43397. * Mainly use in serialization.
  43398. * @returns the class name
  43399. */
  43400. StandardMaterial.prototype.getClassName = function () {
  43401. return "StandardMaterial";
  43402. };
  43403. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43404. /**
  43405. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43406. * You can try switching to logarithmic depth.
  43407. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43408. */
  43409. get: function () {
  43410. return this._useLogarithmicDepth;
  43411. },
  43412. set: function (value) {
  43413. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43414. this._markAllSubMeshesAsMiscDirty();
  43415. },
  43416. enumerable: true,
  43417. configurable: true
  43418. });
  43419. /**
  43420. * Specifies if the material will require alpha blending
  43421. * @returns a boolean specifying if alpha blending is needed
  43422. */
  43423. StandardMaterial.prototype.needAlphaBlending = function () {
  43424. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43425. };
  43426. /**
  43427. * Specifies if this material should be rendered in alpha test mode
  43428. * @returns a boolean specifying if an alpha test is needed.
  43429. */
  43430. StandardMaterial.prototype.needAlphaTesting = function () {
  43431. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43432. };
  43433. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43434. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43435. };
  43436. /**
  43437. * Get the texture used for alpha test purpose.
  43438. * @returns the diffuse texture in case of the standard material.
  43439. */
  43440. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43441. return this._diffuseTexture;
  43442. };
  43443. /**
  43444. * Get if the submesh is ready to be used and all its information available.
  43445. * Child classes can use it to update shaders
  43446. * @param mesh defines the mesh to check
  43447. * @param subMesh defines which submesh to check
  43448. * @param useInstances specifies that instances should be used
  43449. * @returns a boolean indicating that the submesh is ready or not
  43450. */
  43451. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43452. if (useInstances === void 0) { useInstances = false; }
  43453. if (subMesh.effect && this.isFrozen) {
  43454. if (this._wasPreviouslyReady) {
  43455. return true;
  43456. }
  43457. }
  43458. if (!subMesh._materialDefines) {
  43459. subMesh._materialDefines = new StandardMaterialDefines();
  43460. }
  43461. var scene = this.getScene();
  43462. var defines = subMesh._materialDefines;
  43463. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43464. if (defines._renderId === scene.getRenderId()) {
  43465. return true;
  43466. }
  43467. }
  43468. var engine = scene.getEngine();
  43469. // Lights
  43470. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43471. // Textures
  43472. if (defines._areTexturesDirty) {
  43473. defines._needUVs = false;
  43474. defines.MAINUV1 = false;
  43475. defines.MAINUV2 = false;
  43476. if (scene.texturesEnabled) {
  43477. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43478. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43479. return false;
  43480. }
  43481. else {
  43482. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43483. }
  43484. }
  43485. else {
  43486. defines.DIFFUSE = false;
  43487. }
  43488. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43489. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43490. return false;
  43491. }
  43492. else {
  43493. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43494. }
  43495. }
  43496. else {
  43497. defines.AMBIENT = false;
  43498. }
  43499. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43500. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43501. return false;
  43502. }
  43503. else {
  43504. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43505. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43506. }
  43507. }
  43508. else {
  43509. defines.OPACITY = false;
  43510. }
  43511. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43512. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43513. return false;
  43514. }
  43515. else {
  43516. defines._needNormals = true;
  43517. defines.REFLECTION = true;
  43518. defines.ROUGHNESS = (this._roughness > 0);
  43519. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43520. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43521. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43522. switch (this._reflectionTexture.coordinatesMode) {
  43523. case BABYLON.Texture.EXPLICIT_MODE:
  43524. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43525. break;
  43526. case BABYLON.Texture.PLANAR_MODE:
  43527. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43528. break;
  43529. case BABYLON.Texture.PROJECTION_MODE:
  43530. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43531. break;
  43532. case BABYLON.Texture.SKYBOX_MODE:
  43533. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43534. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43535. break;
  43536. case BABYLON.Texture.SPHERICAL_MODE:
  43537. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43538. break;
  43539. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43540. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43541. break;
  43542. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43543. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43544. break;
  43545. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43546. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43547. break;
  43548. case BABYLON.Texture.CUBIC_MODE:
  43549. case BABYLON.Texture.INVCUBIC_MODE:
  43550. default:
  43551. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43552. break;
  43553. }
  43554. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43555. }
  43556. }
  43557. else {
  43558. defines.REFLECTION = false;
  43559. }
  43560. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43561. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43562. return false;
  43563. }
  43564. else {
  43565. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43566. }
  43567. }
  43568. else {
  43569. defines.EMISSIVE = false;
  43570. }
  43571. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43572. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43573. return false;
  43574. }
  43575. else {
  43576. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43577. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43578. }
  43579. }
  43580. else {
  43581. defines.LIGHTMAP = false;
  43582. }
  43583. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43584. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43585. return false;
  43586. }
  43587. else {
  43588. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43589. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43590. }
  43591. }
  43592. else {
  43593. defines.SPECULAR = false;
  43594. }
  43595. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43596. // Bump texure can not be not blocking.
  43597. if (!this._bumpTexture.isReady()) {
  43598. return false;
  43599. }
  43600. else {
  43601. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43602. defines.PARALLAX = this._useParallax;
  43603. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43604. }
  43605. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43606. }
  43607. else {
  43608. defines.BUMP = false;
  43609. }
  43610. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43611. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43612. return false;
  43613. }
  43614. else {
  43615. defines._needUVs = true;
  43616. defines.REFRACTION = true;
  43617. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43618. }
  43619. }
  43620. else {
  43621. defines.REFRACTION = false;
  43622. }
  43623. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43624. }
  43625. else {
  43626. defines.DIFFUSE = false;
  43627. defines.AMBIENT = false;
  43628. defines.OPACITY = false;
  43629. defines.REFLECTION = false;
  43630. defines.EMISSIVE = false;
  43631. defines.LIGHTMAP = false;
  43632. defines.BUMP = false;
  43633. defines.REFRACTION = false;
  43634. }
  43635. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43636. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43637. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43638. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43639. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43640. }
  43641. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43642. if (!this._imageProcessingConfiguration.isReady()) {
  43643. return false;
  43644. }
  43645. this._imageProcessingConfiguration.prepareDefines(defines);
  43646. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43647. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43648. }
  43649. if (defines._areFresnelDirty) {
  43650. if (StandardMaterial.FresnelEnabled) {
  43651. // Fresnel
  43652. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43653. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43654. this._reflectionFresnelParameters) {
  43655. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43656. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43657. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43658. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43659. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43660. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43661. defines._needNormals = true;
  43662. defines.FRESNEL = true;
  43663. }
  43664. }
  43665. else {
  43666. defines.FRESNEL = false;
  43667. }
  43668. }
  43669. // Misc.
  43670. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43671. // Attribs
  43672. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43673. // Values that need to be evaluated on every frame
  43674. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43675. // Get correct effect
  43676. if (defines.isDirty) {
  43677. defines.markAsProcessed();
  43678. scene.resetCachedMaterial();
  43679. // Fallbacks
  43680. var fallbacks = new BABYLON.EffectFallbacks();
  43681. if (defines.REFLECTION) {
  43682. fallbacks.addFallback(0, "REFLECTION");
  43683. }
  43684. if (defines.SPECULAR) {
  43685. fallbacks.addFallback(0, "SPECULAR");
  43686. }
  43687. if (defines.BUMP) {
  43688. fallbacks.addFallback(0, "BUMP");
  43689. }
  43690. if (defines.PARALLAX) {
  43691. fallbacks.addFallback(1, "PARALLAX");
  43692. }
  43693. if (defines.PARALLAXOCCLUSION) {
  43694. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43695. }
  43696. if (defines.SPECULAROVERALPHA) {
  43697. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43698. }
  43699. if (defines.FOG) {
  43700. fallbacks.addFallback(1, "FOG");
  43701. }
  43702. if (defines.POINTSIZE) {
  43703. fallbacks.addFallback(0, "POINTSIZE");
  43704. }
  43705. if (defines.LOGARITHMICDEPTH) {
  43706. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43707. }
  43708. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43709. if (defines.SPECULARTERM) {
  43710. fallbacks.addFallback(0, "SPECULARTERM");
  43711. }
  43712. if (defines.DIFFUSEFRESNEL) {
  43713. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43714. }
  43715. if (defines.OPACITYFRESNEL) {
  43716. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43717. }
  43718. if (defines.REFLECTIONFRESNEL) {
  43719. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43720. }
  43721. if (defines.EMISSIVEFRESNEL) {
  43722. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43723. }
  43724. if (defines.FRESNEL) {
  43725. fallbacks.addFallback(4, "FRESNEL");
  43726. }
  43727. //Attributes
  43728. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43729. if (defines.NORMAL) {
  43730. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43731. }
  43732. if (defines.UV1) {
  43733. attribs.push(BABYLON.VertexBuffer.UVKind);
  43734. }
  43735. if (defines.UV2) {
  43736. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43737. }
  43738. if (defines.VERTEXCOLOR) {
  43739. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43740. }
  43741. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43742. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43743. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43744. var shaderName = "default";
  43745. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43746. "vFogInfos", "vFogColor", "pointSize",
  43747. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43748. "mBones",
  43749. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43750. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43751. "vReflectionPosition", "vReflectionSize",
  43752. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43753. ];
  43754. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43755. var uniformBuffers = ["Material", "Scene"];
  43756. if (BABYLON.ImageProcessingConfiguration) {
  43757. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43758. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43759. }
  43760. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43761. uniformsNames: uniforms,
  43762. uniformBuffersNames: uniformBuffers,
  43763. samplers: samplers,
  43764. defines: defines,
  43765. maxSimultaneousLights: this._maxSimultaneousLights
  43766. });
  43767. if (this.customShaderNameResolve) {
  43768. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43769. }
  43770. var join = defines.toString();
  43771. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43772. attributes: attribs,
  43773. uniformsNames: uniforms,
  43774. uniformBuffersNames: uniformBuffers,
  43775. samplers: samplers,
  43776. defines: join,
  43777. fallbacks: fallbacks,
  43778. onCompiled: this.onCompiled,
  43779. onError: this.onError,
  43780. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43781. }, engine), defines);
  43782. this.buildUniformLayout();
  43783. }
  43784. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43785. return false;
  43786. }
  43787. defines._renderId = scene.getRenderId();
  43788. this._wasPreviouslyReady = true;
  43789. return true;
  43790. };
  43791. /**
  43792. * Builds the material UBO layouts.
  43793. * Used internally during the effect preparation.
  43794. */
  43795. StandardMaterial.prototype.buildUniformLayout = function () {
  43796. // Order is important !
  43797. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43798. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43799. this._uniformBuffer.addUniform("opacityParts", 4);
  43800. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43801. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43802. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43803. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43804. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43805. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43806. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43807. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43808. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43809. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43810. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43811. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43812. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43813. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43814. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43815. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43816. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43817. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43818. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43819. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43820. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43821. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43822. this._uniformBuffer.addUniform("specularMatrix", 16);
  43823. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43824. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43825. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43826. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43827. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43828. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43829. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43830. this._uniformBuffer.addUniform("pointSize", 1);
  43831. this._uniformBuffer.create();
  43832. };
  43833. /**
  43834. * Unbinds the material from the mesh
  43835. */
  43836. StandardMaterial.prototype.unbind = function () {
  43837. if (this._activeEffect) {
  43838. var needFlag = false;
  43839. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43840. this._activeEffect.setTexture("reflection2DSampler", null);
  43841. needFlag = true;
  43842. }
  43843. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43844. this._activeEffect.setTexture("refraction2DSampler", null);
  43845. needFlag = true;
  43846. }
  43847. if (needFlag) {
  43848. this._markAllSubMeshesAsTexturesDirty();
  43849. }
  43850. }
  43851. _super.prototype.unbind.call(this);
  43852. };
  43853. /**
  43854. * Binds the submesh to this material by preparing the effect and shader to draw
  43855. * @param world defines the world transformation matrix
  43856. * @param mesh defines the mesh containing the submesh
  43857. * @param subMesh defines the submesh to bind the material to
  43858. */
  43859. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43860. var scene = this.getScene();
  43861. var defines = subMesh._materialDefines;
  43862. if (!defines) {
  43863. return;
  43864. }
  43865. var effect = subMesh.effect;
  43866. if (!effect) {
  43867. return;
  43868. }
  43869. this._activeEffect = effect;
  43870. // Matrices
  43871. this.bindOnlyWorldMatrix(world);
  43872. // Normal Matrix
  43873. if (defines.OBJECTSPACE_NORMALMAP) {
  43874. world.toNormalMatrix(this._normalMatrix);
  43875. this.bindOnlyNormalMatrix(this._normalMatrix);
  43876. }
  43877. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43878. // Bones
  43879. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43880. if (mustRebind) {
  43881. this._uniformBuffer.bindToEffect(effect, "Material");
  43882. this.bindViewProjection(effect);
  43883. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43884. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43885. // Fresnel
  43886. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43887. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43888. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43889. }
  43890. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43891. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43892. }
  43893. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43894. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43895. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43896. }
  43897. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43898. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43899. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43900. }
  43901. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43902. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43903. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43904. }
  43905. }
  43906. // Textures
  43907. if (scene.texturesEnabled) {
  43908. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43909. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43910. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43911. if (this._diffuseTexture.hasAlpha) {
  43912. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43913. }
  43914. }
  43915. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43916. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43917. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43918. }
  43919. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43920. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43921. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43922. }
  43923. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43924. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43925. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43926. if (this._reflectionTexture.boundingBoxSize) {
  43927. var cubeTexture = this._reflectionTexture;
  43928. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43929. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43930. }
  43931. }
  43932. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43933. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43934. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43935. }
  43936. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43937. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43938. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43939. }
  43940. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43941. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43942. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43943. }
  43944. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43945. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43946. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43947. if (scene._mirroredCameraPosition) {
  43948. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43949. }
  43950. else {
  43951. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43952. }
  43953. }
  43954. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43955. var depth = 1.0;
  43956. if (!this._refractionTexture.isCube) {
  43957. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43958. if (this._refractionTexture.depth) {
  43959. depth = this._refractionTexture.depth;
  43960. }
  43961. }
  43962. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43963. }
  43964. }
  43965. // Point size
  43966. if (this.pointsCloud) {
  43967. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43968. }
  43969. if (defines.SPECULARTERM) {
  43970. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43971. }
  43972. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43973. // Diffuse
  43974. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43975. }
  43976. // Textures
  43977. if (scene.texturesEnabled) {
  43978. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43979. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43980. }
  43981. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43982. effect.setTexture("ambientSampler", this._ambientTexture);
  43983. }
  43984. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43985. effect.setTexture("opacitySampler", this._opacityTexture);
  43986. }
  43987. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43988. if (this._reflectionTexture.isCube) {
  43989. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43990. }
  43991. else {
  43992. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43993. }
  43994. }
  43995. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43996. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43997. }
  43998. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43999. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44000. }
  44001. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44002. effect.setTexture("specularSampler", this._specularTexture);
  44003. }
  44004. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44005. effect.setTexture("bumpSampler", this._bumpTexture);
  44006. }
  44007. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44008. var depth = 1.0;
  44009. if (this._refractionTexture.isCube) {
  44010. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44011. }
  44012. else {
  44013. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44014. }
  44015. }
  44016. }
  44017. // Clip plane
  44018. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44019. // Colors
  44020. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44021. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44022. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44023. }
  44024. if (mustRebind || !this.isFrozen) {
  44025. // Lights
  44026. if (scene.lightsEnabled && !this._disableLighting) {
  44027. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44028. }
  44029. // View
  44030. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44031. this.bindView(effect);
  44032. }
  44033. // Fog
  44034. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44035. // Morph targets
  44036. if (defines.NUM_MORPH_INFLUENCERS) {
  44037. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44038. }
  44039. // Log. depth
  44040. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44041. // image processing
  44042. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  44043. this._imageProcessingConfiguration.bind(this._activeEffect);
  44044. }
  44045. }
  44046. this._uniformBuffer.update();
  44047. this._afterBind(mesh, this._activeEffect);
  44048. };
  44049. /**
  44050. * Get the list of animatables in the material.
  44051. * @returns the list of animatables object used in the material
  44052. */
  44053. StandardMaterial.prototype.getAnimatables = function () {
  44054. var results = [];
  44055. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44056. results.push(this._diffuseTexture);
  44057. }
  44058. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44059. results.push(this._ambientTexture);
  44060. }
  44061. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44062. results.push(this._opacityTexture);
  44063. }
  44064. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44065. results.push(this._reflectionTexture);
  44066. }
  44067. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44068. results.push(this._emissiveTexture);
  44069. }
  44070. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44071. results.push(this._specularTexture);
  44072. }
  44073. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44074. results.push(this._bumpTexture);
  44075. }
  44076. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44077. results.push(this._lightmapTexture);
  44078. }
  44079. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44080. results.push(this._refractionTexture);
  44081. }
  44082. return results;
  44083. };
  44084. /**
  44085. * Gets the active textures from the material
  44086. * @returns an array of textures
  44087. */
  44088. StandardMaterial.prototype.getActiveTextures = function () {
  44089. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44090. if (this._diffuseTexture) {
  44091. activeTextures.push(this._diffuseTexture);
  44092. }
  44093. if (this._ambientTexture) {
  44094. activeTextures.push(this._ambientTexture);
  44095. }
  44096. if (this._opacityTexture) {
  44097. activeTextures.push(this._opacityTexture);
  44098. }
  44099. if (this._reflectionTexture) {
  44100. activeTextures.push(this._reflectionTexture);
  44101. }
  44102. if (this._emissiveTexture) {
  44103. activeTextures.push(this._emissiveTexture);
  44104. }
  44105. if (this._specularTexture) {
  44106. activeTextures.push(this._specularTexture);
  44107. }
  44108. if (this._bumpTexture) {
  44109. activeTextures.push(this._bumpTexture);
  44110. }
  44111. if (this._lightmapTexture) {
  44112. activeTextures.push(this._lightmapTexture);
  44113. }
  44114. if (this._refractionTexture) {
  44115. activeTextures.push(this._refractionTexture);
  44116. }
  44117. return activeTextures;
  44118. };
  44119. /**
  44120. * Specifies if the material uses a texture
  44121. * @param texture defines the texture to check against the material
  44122. * @returns a boolean specifying if the material uses the texture
  44123. */
  44124. StandardMaterial.prototype.hasTexture = function (texture) {
  44125. if (_super.prototype.hasTexture.call(this, texture)) {
  44126. return true;
  44127. }
  44128. if (this._diffuseTexture === texture) {
  44129. return true;
  44130. }
  44131. if (this._ambientTexture === texture) {
  44132. return true;
  44133. }
  44134. if (this._opacityTexture === texture) {
  44135. return true;
  44136. }
  44137. if (this._reflectionTexture === texture) {
  44138. return true;
  44139. }
  44140. if (this._emissiveTexture === texture) {
  44141. return true;
  44142. }
  44143. if (this._specularTexture === texture) {
  44144. return true;
  44145. }
  44146. if (this._bumpTexture === texture) {
  44147. return true;
  44148. }
  44149. if (this._lightmapTexture === texture) {
  44150. return true;
  44151. }
  44152. if (this._refractionTexture === texture) {
  44153. return true;
  44154. }
  44155. return false;
  44156. };
  44157. /**
  44158. * Disposes the material
  44159. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44160. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44161. */
  44162. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44163. if (forceDisposeTextures) {
  44164. if (this._diffuseTexture) {
  44165. this._diffuseTexture.dispose();
  44166. }
  44167. if (this._ambientTexture) {
  44168. this._ambientTexture.dispose();
  44169. }
  44170. if (this._opacityTexture) {
  44171. this._opacityTexture.dispose();
  44172. }
  44173. if (this._reflectionTexture) {
  44174. this._reflectionTexture.dispose();
  44175. }
  44176. if (this._emissiveTexture) {
  44177. this._emissiveTexture.dispose();
  44178. }
  44179. if (this._specularTexture) {
  44180. this._specularTexture.dispose();
  44181. }
  44182. if (this._bumpTexture) {
  44183. this._bumpTexture.dispose();
  44184. }
  44185. if (this._lightmapTexture) {
  44186. this._lightmapTexture.dispose();
  44187. }
  44188. if (this._refractionTexture) {
  44189. this._refractionTexture.dispose();
  44190. }
  44191. }
  44192. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44193. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44194. }
  44195. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44196. };
  44197. /**
  44198. * Makes a duplicate of the material, and gives it a new name
  44199. * @param name defines the new name for the duplicated material
  44200. * @returns the cloned material
  44201. */
  44202. StandardMaterial.prototype.clone = function (name) {
  44203. var _this = this;
  44204. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44205. result.name = name;
  44206. result.id = name;
  44207. return result;
  44208. };
  44209. /**
  44210. * Serializes this material in a JSON representation
  44211. * @returns the serialized material object
  44212. */
  44213. StandardMaterial.prototype.serialize = function () {
  44214. return BABYLON.SerializationHelper.Serialize(this);
  44215. };
  44216. /**
  44217. * Creates a standard material from parsed material data
  44218. * @param source defines the JSON represnetation of the material
  44219. * @param scene defines the hosting scene
  44220. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44221. * @returns a new material
  44222. */
  44223. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44224. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44225. };
  44226. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44227. /**
  44228. * Are diffuse textures enabled in the application.
  44229. */
  44230. get: function () {
  44231. return StandardMaterial._DiffuseTextureEnabled;
  44232. },
  44233. set: function (value) {
  44234. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44235. return;
  44236. }
  44237. StandardMaterial._DiffuseTextureEnabled = value;
  44238. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44239. },
  44240. enumerable: true,
  44241. configurable: true
  44242. });
  44243. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44244. /**
  44245. * Are ambient textures enabled in the application.
  44246. */
  44247. get: function () {
  44248. return StandardMaterial._AmbientTextureEnabled;
  44249. },
  44250. set: function (value) {
  44251. if (StandardMaterial._AmbientTextureEnabled === value) {
  44252. return;
  44253. }
  44254. StandardMaterial._AmbientTextureEnabled = value;
  44255. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44256. },
  44257. enumerable: true,
  44258. configurable: true
  44259. });
  44260. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44261. /**
  44262. * Are opacity textures enabled in the application.
  44263. */
  44264. get: function () {
  44265. return StandardMaterial._OpacityTextureEnabled;
  44266. },
  44267. set: function (value) {
  44268. if (StandardMaterial._OpacityTextureEnabled === value) {
  44269. return;
  44270. }
  44271. StandardMaterial._OpacityTextureEnabled = value;
  44272. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44273. },
  44274. enumerable: true,
  44275. configurable: true
  44276. });
  44277. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44278. /**
  44279. * Are reflection textures enabled in the application.
  44280. */
  44281. get: function () {
  44282. return StandardMaterial._ReflectionTextureEnabled;
  44283. },
  44284. set: function (value) {
  44285. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44286. return;
  44287. }
  44288. StandardMaterial._ReflectionTextureEnabled = value;
  44289. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44290. },
  44291. enumerable: true,
  44292. configurable: true
  44293. });
  44294. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44295. /**
  44296. * Are emissive textures enabled in the application.
  44297. */
  44298. get: function () {
  44299. return StandardMaterial._EmissiveTextureEnabled;
  44300. },
  44301. set: function (value) {
  44302. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44303. return;
  44304. }
  44305. StandardMaterial._EmissiveTextureEnabled = value;
  44306. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44307. },
  44308. enumerable: true,
  44309. configurable: true
  44310. });
  44311. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44312. /**
  44313. * Are specular textures enabled in the application.
  44314. */
  44315. get: function () {
  44316. return StandardMaterial._SpecularTextureEnabled;
  44317. },
  44318. set: function (value) {
  44319. if (StandardMaterial._SpecularTextureEnabled === value) {
  44320. return;
  44321. }
  44322. StandardMaterial._SpecularTextureEnabled = value;
  44323. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44324. },
  44325. enumerable: true,
  44326. configurable: true
  44327. });
  44328. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44329. /**
  44330. * Are bump textures enabled in the application.
  44331. */
  44332. get: function () {
  44333. return StandardMaterial._BumpTextureEnabled;
  44334. },
  44335. set: function (value) {
  44336. if (StandardMaterial._BumpTextureEnabled === value) {
  44337. return;
  44338. }
  44339. StandardMaterial._BumpTextureEnabled = value;
  44340. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44341. },
  44342. enumerable: true,
  44343. configurable: true
  44344. });
  44345. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44346. /**
  44347. * Are lightmap textures enabled in the application.
  44348. */
  44349. get: function () {
  44350. return StandardMaterial._LightmapTextureEnabled;
  44351. },
  44352. set: function (value) {
  44353. if (StandardMaterial._LightmapTextureEnabled === value) {
  44354. return;
  44355. }
  44356. StandardMaterial._LightmapTextureEnabled = value;
  44357. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44358. },
  44359. enumerable: true,
  44360. configurable: true
  44361. });
  44362. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44363. /**
  44364. * Are refraction textures enabled in the application.
  44365. */
  44366. get: function () {
  44367. return StandardMaterial._RefractionTextureEnabled;
  44368. },
  44369. set: function (value) {
  44370. if (StandardMaterial._RefractionTextureEnabled === value) {
  44371. return;
  44372. }
  44373. StandardMaterial._RefractionTextureEnabled = value;
  44374. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44375. },
  44376. enumerable: true,
  44377. configurable: true
  44378. });
  44379. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44380. /**
  44381. * Are color grading textures enabled in the application.
  44382. */
  44383. get: function () {
  44384. return StandardMaterial._ColorGradingTextureEnabled;
  44385. },
  44386. set: function (value) {
  44387. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44388. return;
  44389. }
  44390. StandardMaterial._ColorGradingTextureEnabled = value;
  44391. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44392. },
  44393. enumerable: true,
  44394. configurable: true
  44395. });
  44396. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44397. /**
  44398. * Are fresnels enabled in the application.
  44399. */
  44400. get: function () {
  44401. return StandardMaterial._FresnelEnabled;
  44402. },
  44403. set: function (value) {
  44404. if (StandardMaterial._FresnelEnabled === value) {
  44405. return;
  44406. }
  44407. StandardMaterial._FresnelEnabled = value;
  44408. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44409. },
  44410. enumerable: true,
  44411. configurable: true
  44412. });
  44413. // Flags used to enable or disable a type of texture for all Standard Materials
  44414. StandardMaterial._DiffuseTextureEnabled = true;
  44415. StandardMaterial._AmbientTextureEnabled = true;
  44416. StandardMaterial._OpacityTextureEnabled = true;
  44417. StandardMaterial._ReflectionTextureEnabled = true;
  44418. StandardMaterial._EmissiveTextureEnabled = true;
  44419. StandardMaterial._SpecularTextureEnabled = true;
  44420. StandardMaterial._BumpTextureEnabled = true;
  44421. StandardMaterial._LightmapTextureEnabled = true;
  44422. StandardMaterial._RefractionTextureEnabled = true;
  44423. StandardMaterial._ColorGradingTextureEnabled = true;
  44424. StandardMaterial._FresnelEnabled = true;
  44425. __decorate([
  44426. BABYLON.serializeAsTexture("diffuseTexture")
  44427. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44428. __decorate([
  44429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44430. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44431. __decorate([
  44432. BABYLON.serializeAsTexture("ambientTexture")
  44433. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44434. __decorate([
  44435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44436. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44437. __decorate([
  44438. BABYLON.serializeAsTexture("opacityTexture")
  44439. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44440. __decorate([
  44441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44442. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44443. __decorate([
  44444. BABYLON.serializeAsTexture("reflectionTexture")
  44445. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44446. __decorate([
  44447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44448. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44449. __decorate([
  44450. BABYLON.serializeAsTexture("emissiveTexture")
  44451. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44452. __decorate([
  44453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44454. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44455. __decorate([
  44456. BABYLON.serializeAsTexture("specularTexture")
  44457. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44458. __decorate([
  44459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44460. ], StandardMaterial.prototype, "specularTexture", void 0);
  44461. __decorate([
  44462. BABYLON.serializeAsTexture("bumpTexture")
  44463. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44464. __decorate([
  44465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44466. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44467. __decorate([
  44468. BABYLON.serializeAsTexture("lightmapTexture")
  44469. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44470. __decorate([
  44471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44472. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44473. __decorate([
  44474. BABYLON.serializeAsTexture("refractionTexture")
  44475. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44476. __decorate([
  44477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44478. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44479. __decorate([
  44480. BABYLON.serializeAsColor3("ambient")
  44481. ], StandardMaterial.prototype, "ambientColor", void 0);
  44482. __decorate([
  44483. BABYLON.serializeAsColor3("diffuse")
  44484. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44485. __decorate([
  44486. BABYLON.serializeAsColor3("specular")
  44487. ], StandardMaterial.prototype, "specularColor", void 0);
  44488. __decorate([
  44489. BABYLON.serializeAsColor3("emissive")
  44490. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44491. __decorate([
  44492. BABYLON.serialize()
  44493. ], StandardMaterial.prototype, "specularPower", void 0);
  44494. __decorate([
  44495. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44496. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44497. __decorate([
  44498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44499. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44500. __decorate([
  44501. BABYLON.serialize("useEmissiveAsIllumination")
  44502. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44503. __decorate([
  44504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44505. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44506. __decorate([
  44507. BABYLON.serialize("linkEmissiveWithDiffuse")
  44508. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44509. __decorate([
  44510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44511. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44512. __decorate([
  44513. BABYLON.serialize("useSpecularOverAlpha")
  44514. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44515. __decorate([
  44516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44517. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44518. __decorate([
  44519. BABYLON.serialize("useReflectionOverAlpha")
  44520. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44521. __decorate([
  44522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44523. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44524. __decorate([
  44525. BABYLON.serialize("disableLighting")
  44526. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44527. __decorate([
  44528. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44529. ], StandardMaterial.prototype, "disableLighting", void 0);
  44530. __decorate([
  44531. BABYLON.serialize("useObjectSpaceNormalMap")
  44532. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44533. __decorate([
  44534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44535. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44536. __decorate([
  44537. BABYLON.serialize("useParallax")
  44538. ], StandardMaterial.prototype, "_useParallax", void 0);
  44539. __decorate([
  44540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44541. ], StandardMaterial.prototype, "useParallax", void 0);
  44542. __decorate([
  44543. BABYLON.serialize("useParallaxOcclusion")
  44544. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44545. __decorate([
  44546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44547. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44548. __decorate([
  44549. BABYLON.serialize()
  44550. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44551. __decorate([
  44552. BABYLON.serialize("roughness")
  44553. ], StandardMaterial.prototype, "_roughness", void 0);
  44554. __decorate([
  44555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44556. ], StandardMaterial.prototype, "roughness", void 0);
  44557. __decorate([
  44558. BABYLON.serialize()
  44559. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44560. __decorate([
  44561. BABYLON.serialize()
  44562. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44563. __decorate([
  44564. BABYLON.serialize()
  44565. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44566. __decorate([
  44567. BABYLON.serialize("useLightmapAsShadowmap")
  44568. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44569. __decorate([
  44570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44571. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44572. __decorate([
  44573. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44574. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44575. __decorate([
  44576. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44577. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44578. __decorate([
  44579. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44580. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44581. __decorate([
  44582. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44583. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44584. __decorate([
  44585. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44586. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44587. __decorate([
  44588. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44589. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44590. __decorate([
  44591. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44592. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44593. __decorate([
  44594. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44595. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44596. __decorate([
  44597. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44598. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44599. __decorate([
  44600. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44601. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44602. __decorate([
  44603. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44604. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44605. __decorate([
  44606. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44607. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44608. __decorate([
  44609. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44610. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44611. __decorate([
  44612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44613. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44614. __decorate([
  44615. BABYLON.serialize("maxSimultaneousLights")
  44616. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44617. __decorate([
  44618. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44619. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44620. __decorate([
  44621. BABYLON.serialize("invertNormalMapX")
  44622. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44623. __decorate([
  44624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44625. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44626. __decorate([
  44627. BABYLON.serialize("invertNormalMapY")
  44628. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44629. __decorate([
  44630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44631. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44632. __decorate([
  44633. BABYLON.serialize("twoSidedLighting")
  44634. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44635. __decorate([
  44636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44637. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44638. __decorate([
  44639. BABYLON.serialize()
  44640. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44641. return StandardMaterial;
  44642. }(BABYLON.PushMaterial));
  44643. BABYLON.StandardMaterial = StandardMaterial;
  44644. })(BABYLON || (BABYLON = {}));
  44645. //# sourceMappingURL=babylon.standardMaterial.js.map
  44646. var BABYLON;
  44647. (function (BABYLON) {
  44648. /**
  44649. * Class representing spherical polynomial coefficients to the 3rd degree
  44650. */
  44651. var SphericalPolynomial = /** @class */ (function () {
  44652. function SphericalPolynomial() {
  44653. /**
  44654. * The x coefficients of the spherical polynomial
  44655. */
  44656. this.x = BABYLON.Vector3.Zero();
  44657. /**
  44658. * The y coefficients of the spherical polynomial
  44659. */
  44660. this.y = BABYLON.Vector3.Zero();
  44661. /**
  44662. * The z coefficients of the spherical polynomial
  44663. */
  44664. this.z = BABYLON.Vector3.Zero();
  44665. /**
  44666. * The xx coefficients of the spherical polynomial
  44667. */
  44668. this.xx = BABYLON.Vector3.Zero();
  44669. /**
  44670. * The yy coefficients of the spherical polynomial
  44671. */
  44672. this.yy = BABYLON.Vector3.Zero();
  44673. /**
  44674. * The zz coefficients of the spherical polynomial
  44675. */
  44676. this.zz = BABYLON.Vector3.Zero();
  44677. /**
  44678. * The xy coefficients of the spherical polynomial
  44679. */
  44680. this.xy = BABYLON.Vector3.Zero();
  44681. /**
  44682. * The yz coefficients of the spherical polynomial
  44683. */
  44684. this.yz = BABYLON.Vector3.Zero();
  44685. /**
  44686. * The zx coefficients of the spherical polynomial
  44687. */
  44688. this.zx = BABYLON.Vector3.Zero();
  44689. }
  44690. /**
  44691. * Adds an ambient color to the spherical polynomial
  44692. * @param color the color to add
  44693. */
  44694. SphericalPolynomial.prototype.addAmbient = function (color) {
  44695. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44696. this.xx = this.xx.add(colorVector);
  44697. this.yy = this.yy.add(colorVector);
  44698. this.zz = this.zz.add(colorVector);
  44699. };
  44700. /**
  44701. * Scales the spherical polynomial by the given amount
  44702. * @param scale the amount to scale
  44703. */
  44704. SphericalPolynomial.prototype.scale = function (scale) {
  44705. this.x = this.x.scale(scale);
  44706. this.y = this.y.scale(scale);
  44707. this.z = this.z.scale(scale);
  44708. this.xx = this.xx.scale(scale);
  44709. this.yy = this.yy.scale(scale);
  44710. this.zz = this.zz.scale(scale);
  44711. this.yz = this.yz.scale(scale);
  44712. this.zx = this.zx.scale(scale);
  44713. this.xy = this.xy.scale(scale);
  44714. };
  44715. /**
  44716. * Gets the spherical polynomial from harmonics
  44717. * @param harmonics the spherical harmonics
  44718. * @returns the spherical polynomial
  44719. */
  44720. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44721. var result = new SphericalPolynomial();
  44722. result.x = harmonics.l11.scale(1.02333);
  44723. result.y = harmonics.l1_1.scale(1.02333);
  44724. result.z = harmonics.l10.scale(1.02333);
  44725. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44726. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44727. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44728. result.yz = harmonics.l2_1.scale(0.858086);
  44729. result.zx = harmonics.l21.scale(0.858086);
  44730. result.xy = harmonics.l2_2.scale(0.858086);
  44731. result.scale(1.0 / Math.PI);
  44732. return result;
  44733. };
  44734. /**
  44735. * Constructs a spherical polynomial from an array.
  44736. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44737. * @returns the spherical polynomial
  44738. */
  44739. SphericalPolynomial.FromArray = function (data) {
  44740. var sp = new SphericalPolynomial();
  44741. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44742. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44743. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44744. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44745. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44746. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44747. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44748. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44749. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44750. return sp;
  44751. };
  44752. return SphericalPolynomial;
  44753. }());
  44754. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44755. /**
  44756. * Class representing spherical harmonics coefficients to the 3rd degree
  44757. */
  44758. var SphericalHarmonics = /** @class */ (function () {
  44759. function SphericalHarmonics() {
  44760. /**
  44761. * The l0,0 coefficients of the spherical harmonics
  44762. */
  44763. this.l00 = BABYLON.Vector3.Zero();
  44764. /**
  44765. * The l1,-1 coefficients of the spherical harmonics
  44766. */
  44767. this.l1_1 = BABYLON.Vector3.Zero();
  44768. /**
  44769. * The l1,0 coefficients of the spherical harmonics
  44770. */
  44771. this.l10 = BABYLON.Vector3.Zero();
  44772. /**
  44773. * The l1,1 coefficients of the spherical harmonics
  44774. */
  44775. this.l11 = BABYLON.Vector3.Zero();
  44776. /**
  44777. * The l2,-2 coefficients of the spherical harmonics
  44778. */
  44779. this.l2_2 = BABYLON.Vector3.Zero();
  44780. /**
  44781. * The l2,-1 coefficients of the spherical harmonics
  44782. */
  44783. this.l2_1 = BABYLON.Vector3.Zero();
  44784. /**
  44785. * The l2,0 coefficients of the spherical harmonics
  44786. */
  44787. this.l20 = BABYLON.Vector3.Zero();
  44788. /**
  44789. * The l2,1 coefficients of the spherical harmonics
  44790. */
  44791. this.l21 = BABYLON.Vector3.Zero();
  44792. /**
  44793. * The l2,2 coefficients of the spherical harmonics
  44794. */
  44795. this.lL22 = BABYLON.Vector3.Zero();
  44796. }
  44797. /**
  44798. * Adds a light to the spherical harmonics
  44799. * @param direction the direction of the light
  44800. * @param color the color of the light
  44801. * @param deltaSolidAngle the delta solid angle of the light
  44802. */
  44803. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44804. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44805. var c = colorVector.scale(deltaSolidAngle);
  44806. this.l00 = this.l00.add(c.scale(0.282095));
  44807. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44808. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44809. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44810. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44811. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44812. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44813. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44814. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44815. };
  44816. /**
  44817. * Scales the spherical harmonics by the given amount
  44818. * @param scale the amount to scale
  44819. */
  44820. SphericalHarmonics.prototype.scale = function (scale) {
  44821. this.l00 = this.l00.scale(scale);
  44822. this.l1_1 = this.l1_1.scale(scale);
  44823. this.l10 = this.l10.scale(scale);
  44824. this.l11 = this.l11.scale(scale);
  44825. this.l2_2 = this.l2_2.scale(scale);
  44826. this.l2_1 = this.l2_1.scale(scale);
  44827. this.l20 = this.l20.scale(scale);
  44828. this.l21 = this.l21.scale(scale);
  44829. this.lL22 = this.lL22.scale(scale);
  44830. };
  44831. /**
  44832. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44833. *
  44834. * ```
  44835. * E_lm = A_l * L_lm
  44836. * ```
  44837. *
  44838. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44839. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44840. * the scaling factors are given in equation 9.
  44841. */
  44842. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44843. // Constant (Band 0)
  44844. this.l00 = this.l00.scale(3.141593);
  44845. // Linear (Band 1)
  44846. this.l1_1 = this.l1_1.scale(2.094395);
  44847. this.l10 = this.l10.scale(2.094395);
  44848. this.l11 = this.l11.scale(2.094395);
  44849. // Quadratic (Band 2)
  44850. this.l2_2 = this.l2_2.scale(0.785398);
  44851. this.l2_1 = this.l2_1.scale(0.785398);
  44852. this.l20 = this.l20.scale(0.785398);
  44853. this.l21 = this.l21.scale(0.785398);
  44854. this.lL22 = this.lL22.scale(0.785398);
  44855. };
  44856. /**
  44857. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44858. *
  44859. * ```
  44860. * L = (1/pi) * E * rho
  44861. * ```
  44862. *
  44863. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44864. */
  44865. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44866. this.scale(1.0 / Math.PI);
  44867. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44868. // (The pixel shader must apply albedo after texture fetches, etc).
  44869. };
  44870. /**
  44871. * Gets the spherical harmonics from polynomial
  44872. * @param polynomial the spherical polynomial
  44873. * @returns the spherical harmonics
  44874. */
  44875. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44876. var result = new SphericalHarmonics();
  44877. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44878. result.l1_1 = polynomial.y.scale(0.977204);
  44879. result.l10 = polynomial.z.scale(0.977204);
  44880. result.l11 = polynomial.x.scale(0.977204);
  44881. result.l2_2 = polynomial.xy.scale(1.16538);
  44882. result.l2_1 = polynomial.yz.scale(1.16538);
  44883. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44884. result.l21 = polynomial.zx.scale(1.16538);
  44885. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44886. result.scale(Math.PI);
  44887. return result;
  44888. };
  44889. /**
  44890. * Constructs a spherical harmonics from an array.
  44891. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44892. * @returns the spherical harmonics
  44893. */
  44894. SphericalHarmonics.FromArray = function (data) {
  44895. var sh = new SphericalHarmonics();
  44896. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44897. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44898. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44899. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44900. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44901. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44902. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44903. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44904. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44905. return sh;
  44906. };
  44907. return SphericalHarmonics;
  44908. }());
  44909. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44910. })(BABYLON || (BABYLON = {}));
  44911. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44912. var BABYLON;
  44913. (function (BABYLON) {
  44914. var FileFaceOrientation = /** @class */ (function () {
  44915. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44916. this.name = name;
  44917. this.worldAxisForNormal = worldAxisForNormal;
  44918. this.worldAxisForFileX = worldAxisForFileX;
  44919. this.worldAxisForFileY = worldAxisForFileY;
  44920. }
  44921. return FileFaceOrientation;
  44922. }());
  44923. /**
  44924. * Helper class dealing with the extraction of spherical polynomial dataArray
  44925. * from a cube map.
  44926. */
  44927. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44928. function CubeMapToSphericalPolynomialTools() {
  44929. }
  44930. /**
  44931. * Converts a texture to the according Spherical Polynomial data.
  44932. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44933. *
  44934. * @param texture The texture to extract the information from.
  44935. * @return The Spherical Polynomial data.
  44936. */
  44937. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44938. if (!texture.isCube) {
  44939. // Only supports cube Textures currently.
  44940. return null;
  44941. }
  44942. var size = texture.getSize().width;
  44943. var right = texture.readPixels(0);
  44944. var left = texture.readPixels(1);
  44945. var up;
  44946. var down;
  44947. if (texture.isRenderTarget) {
  44948. up = texture.readPixels(3);
  44949. down = texture.readPixels(2);
  44950. }
  44951. else {
  44952. up = texture.readPixels(2);
  44953. down = texture.readPixels(3);
  44954. }
  44955. var front = texture.readPixels(4);
  44956. var back = texture.readPixels(5);
  44957. var gammaSpace = texture.gammaSpace;
  44958. // Always read as RGBA.
  44959. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44960. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44961. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44962. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44963. }
  44964. var cubeInfo = {
  44965. size: size,
  44966. right: right,
  44967. left: left,
  44968. up: up,
  44969. down: down,
  44970. front: front,
  44971. back: back,
  44972. format: format,
  44973. type: type,
  44974. gammaSpace: gammaSpace,
  44975. };
  44976. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44977. };
  44978. /**
  44979. * Converts a cubemap to the according Spherical Polynomial data.
  44980. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44981. *
  44982. * @param cubeInfo The Cube map to extract the information from.
  44983. * @return The Spherical Polynomial data.
  44984. */
  44985. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44986. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44987. var totalSolidAngle = 0.0;
  44988. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44989. var du = 2.0 / cubeInfo.size;
  44990. var dv = du;
  44991. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44992. var minUV = du * 0.5 - 1.0;
  44993. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44994. var fileFace = this.FileFaces[faceIndex];
  44995. var dataArray = cubeInfo[fileFace.name];
  44996. var v = minUV;
  44997. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  44998. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  44999. // Because SP is still linear, so summation is fine in that basis.
  45000. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  45001. for (var y = 0; y < cubeInfo.size; y++) {
  45002. var u = minUV;
  45003. for (var x = 0; x < cubeInfo.size; x++) {
  45004. // World direction (not normalised)
  45005. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45006. worldDirection.normalize();
  45007. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45008. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  45009. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  45010. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  45011. // Handle Integer types.
  45012. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45013. r /= 255;
  45014. g /= 255;
  45015. b /= 255;
  45016. }
  45017. // Handle Gamma space textures.
  45018. if (cubeInfo.gammaSpace) {
  45019. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  45020. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  45021. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  45022. }
  45023. var color = new BABYLON.Color3(r, g, b);
  45024. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45025. totalSolidAngle += deltaSolidAngle;
  45026. u += du;
  45027. }
  45028. v += dv;
  45029. }
  45030. }
  45031. // Solid angle for entire sphere is 4*pi
  45032. var sphereSolidAngle = 4.0 * Math.PI;
  45033. // Adjust the solid angle to allow for how many faces we processed.
  45034. var facesProcessed = 6.0;
  45035. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  45036. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  45037. // This is needed because the numerical integration over the cube uses a
  45038. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  45039. // and also to compensate for accumulative error due to float precision in the summation.
  45040. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  45041. sphericalHarmonics.scale(correctionFactor);
  45042. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  45043. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  45044. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  45045. };
  45046. CubeMapToSphericalPolynomialTools.FileFaces = [
  45047. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45048. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45049. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45050. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45051. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45052. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45053. ];
  45054. return CubeMapToSphericalPolynomialTools;
  45055. }());
  45056. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45057. })(BABYLON || (BABYLON = {}));
  45058. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45059. var BABYLON;
  45060. (function (BABYLON) {
  45061. /**
  45062. * Manages the defines for the PBR Material.
  45063. * @hiddenChildren
  45064. */
  45065. var PBRMaterialDefines = /** @class */ (function (_super) {
  45066. __extends(PBRMaterialDefines, _super);
  45067. /**
  45068. * Initializes the PBR Material defines.
  45069. */
  45070. function PBRMaterialDefines() {
  45071. var _this = _super.call(this) || this;
  45072. _this.PBR = true;
  45073. _this.MAINUV1 = false;
  45074. _this.MAINUV2 = false;
  45075. _this.UV1 = false;
  45076. _this.UV2 = false;
  45077. _this.ALBEDO = false;
  45078. _this.ALBEDODIRECTUV = 0;
  45079. _this.VERTEXCOLOR = false;
  45080. _this.AMBIENT = false;
  45081. _this.AMBIENTDIRECTUV = 0;
  45082. _this.AMBIENTINGRAYSCALE = false;
  45083. _this.OPACITY = false;
  45084. _this.VERTEXALPHA = false;
  45085. _this.OPACITYDIRECTUV = 0;
  45086. _this.OPACITYRGB = false;
  45087. _this.ALPHATEST = false;
  45088. _this.DEPTHPREPASS = false;
  45089. _this.ALPHABLEND = false;
  45090. _this.ALPHAFROMALBEDO = false;
  45091. _this.ALPHATESTVALUE = "0.5";
  45092. _this.SPECULAROVERALPHA = false;
  45093. _this.RADIANCEOVERALPHA = false;
  45094. _this.ALPHAFRESNEL = false;
  45095. _this.LINEARALPHAFRESNEL = false;
  45096. _this.PREMULTIPLYALPHA = false;
  45097. _this.EMISSIVE = false;
  45098. _this.EMISSIVEDIRECTUV = 0;
  45099. _this.REFLECTIVITY = false;
  45100. _this.REFLECTIVITYDIRECTUV = 0;
  45101. _this.SPECULARTERM = false;
  45102. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45103. _this.MICROSURFACEAUTOMATIC = false;
  45104. _this.LODBASEDMICROSFURACE = false;
  45105. _this.MICROSURFACEMAP = false;
  45106. _this.MICROSURFACEMAPDIRECTUV = 0;
  45107. _this.METALLICWORKFLOW = false;
  45108. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  45109. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  45110. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45111. _this.AOSTOREINMETALMAPRED = false;
  45112. _this.ENVIRONMENTBRDF = false;
  45113. _this.NORMAL = false;
  45114. _this.TANGENT = false;
  45115. _this.BUMP = false;
  45116. _this.BUMPDIRECTUV = 0;
  45117. _this.OBJECTSPACE_NORMALMAP = false;
  45118. _this.PARALLAX = false;
  45119. _this.PARALLAXOCCLUSION = false;
  45120. _this.NORMALXYSCALE = true;
  45121. _this.LIGHTMAP = false;
  45122. _this.LIGHTMAPDIRECTUV = 0;
  45123. _this.USELIGHTMAPASSHADOWMAP = false;
  45124. _this.GAMMALIGHTMAP = false;
  45125. _this.REFLECTION = false;
  45126. _this.REFLECTIONMAP_3D = false;
  45127. _this.REFLECTIONMAP_SPHERICAL = false;
  45128. _this.REFLECTIONMAP_PLANAR = false;
  45129. _this.REFLECTIONMAP_CUBIC = false;
  45130. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45131. _this.REFLECTIONMAP_PROJECTION = false;
  45132. _this.REFLECTIONMAP_SKYBOX = false;
  45133. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45134. _this.REFLECTIONMAP_EXPLICIT = false;
  45135. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45136. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45137. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45138. _this.INVERTCUBICMAP = false;
  45139. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45140. _this.USESPHERICALINVERTEX = false;
  45141. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45142. _this.LODINREFLECTIONALPHA = false;
  45143. _this.GAMMAREFLECTION = false;
  45144. _this.RGBDREFLECTION = false;
  45145. _this.RADIANCEOCCLUSION = false;
  45146. _this.HORIZONOCCLUSION = false;
  45147. _this.REFRACTION = false;
  45148. _this.REFRACTIONMAP_3D = false;
  45149. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45150. _this.LODINREFRACTIONALPHA = false;
  45151. _this.GAMMAREFRACTION = false;
  45152. _this.RGBDREFRACTION = false;
  45153. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45154. _this.INSTANCES = false;
  45155. _this.NUM_BONE_INFLUENCERS = 0;
  45156. _this.BonesPerMesh = 0;
  45157. _this.NONUNIFORMSCALING = false;
  45158. _this.MORPHTARGETS = false;
  45159. _this.MORPHTARGETS_NORMAL = false;
  45160. _this.MORPHTARGETS_TANGENT = false;
  45161. _this.NUM_MORPH_INFLUENCERS = 0;
  45162. _this.IMAGEPROCESSING = false;
  45163. _this.VIGNETTE = false;
  45164. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45165. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45166. _this.TONEMAPPING = false;
  45167. _this.TONEMAPPING_ACES = false;
  45168. _this.CONTRAST = false;
  45169. _this.COLORCURVES = false;
  45170. _this.COLORGRADING = false;
  45171. _this.COLORGRADING3D = false;
  45172. _this.SAMPLER3DGREENDEPTH = false;
  45173. _this.SAMPLER3DBGRMAP = false;
  45174. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45175. _this.EXPOSURE = false;
  45176. _this.USEPHYSICALLIGHTFALLOFF = false;
  45177. _this.USEGLTFLIGHTFALLOFF = false;
  45178. _this.TWOSIDEDLIGHTING = false;
  45179. _this.SHADOWFLOAT = false;
  45180. _this.CLIPPLANE = false;
  45181. _this.CLIPPLANE2 = false;
  45182. _this.CLIPPLANE3 = false;
  45183. _this.CLIPPLANE4 = false;
  45184. _this.POINTSIZE = false;
  45185. _this.FOG = false;
  45186. _this.LOGARITHMICDEPTH = false;
  45187. _this.FORCENORMALFORWARD = false;
  45188. _this.SPECULARAA = false;
  45189. _this.UNLIT = false;
  45190. _this.rebuild();
  45191. return _this;
  45192. }
  45193. /**
  45194. * Resets the PBR Material defines.
  45195. */
  45196. PBRMaterialDefines.prototype.reset = function () {
  45197. _super.prototype.reset.call(this);
  45198. this.ALPHATESTVALUE = "0.5";
  45199. this.PBR = true;
  45200. };
  45201. return PBRMaterialDefines;
  45202. }(BABYLON.MaterialDefines));
  45203. /**
  45204. * The Physically based material base class of BJS.
  45205. *
  45206. * This offers the main features of a standard PBR material.
  45207. * For more information, please refer to the documentation :
  45208. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45209. */
  45210. var PBRBaseMaterial = /** @class */ (function (_super) {
  45211. __extends(PBRBaseMaterial, _super);
  45212. /**
  45213. * Instantiates a new PBRMaterial instance.
  45214. *
  45215. * @param name The material name
  45216. * @param scene The scene the material will be use in.
  45217. */
  45218. function PBRBaseMaterial(name, scene) {
  45219. var _this = _super.call(this, name, scene) || this;
  45220. /**
  45221. * Intensity of the direct lights e.g. the four lights available in your scene.
  45222. * This impacts both the direct diffuse and specular highlights.
  45223. */
  45224. _this._directIntensity = 1.0;
  45225. /**
  45226. * Intensity of the emissive part of the material.
  45227. * This helps controlling the emissive effect without modifying the emissive color.
  45228. */
  45229. _this._emissiveIntensity = 1.0;
  45230. /**
  45231. * Intensity of the environment e.g. how much the environment will light the object
  45232. * either through harmonics for rough material or through the refelction for shiny ones.
  45233. */
  45234. _this._environmentIntensity = 1.0;
  45235. /**
  45236. * This is a special control allowing the reduction of the specular highlights coming from the
  45237. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45238. */
  45239. _this._specularIntensity = 1.0;
  45240. /**
  45241. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45242. */
  45243. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45244. /**
  45245. * Debug Control allowing disabling the bump map on this material.
  45246. */
  45247. _this._disableBumpMap = false;
  45248. /**
  45249. * AKA Occlusion Texture Intensity in other nomenclature.
  45250. */
  45251. _this._ambientTextureStrength = 1.0;
  45252. /**
  45253. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45254. * 1 means it completely occludes it
  45255. * 0 mean it has no impact
  45256. */
  45257. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45258. /**
  45259. * The color of a material in ambient lighting.
  45260. */
  45261. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45262. /**
  45263. * AKA Diffuse Color in other nomenclature.
  45264. */
  45265. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45266. /**
  45267. * AKA Specular Color in other nomenclature.
  45268. */
  45269. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45270. /**
  45271. * The color applied when light is reflected from a material.
  45272. */
  45273. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45274. /**
  45275. * The color applied when light is emitted from a material.
  45276. */
  45277. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45278. /**
  45279. * AKA Glossiness in other nomenclature.
  45280. */
  45281. _this._microSurface = 0.9;
  45282. /**
  45283. * source material index of refraction (IOR)' / 'destination material IOR.
  45284. */
  45285. _this._indexOfRefraction = 0.66;
  45286. /**
  45287. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45288. */
  45289. _this._invertRefractionY = false;
  45290. /**
  45291. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45292. * Materials half opaque for instance using refraction could benefit from this control.
  45293. */
  45294. _this._linkRefractionWithTransparency = false;
  45295. /**
  45296. * Specifies that the material will use the light map as a show map.
  45297. */
  45298. _this._useLightmapAsShadowmap = false;
  45299. /**
  45300. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45301. * makes the reflect vector face the model (under horizon).
  45302. */
  45303. _this._useHorizonOcclusion = true;
  45304. /**
  45305. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45306. * too much the area relying on ambient texture to define their ambient occlusion.
  45307. */
  45308. _this._useRadianceOcclusion = true;
  45309. /**
  45310. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45311. */
  45312. _this._useAlphaFromAlbedoTexture = false;
  45313. /**
  45314. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45315. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45316. */
  45317. _this._useSpecularOverAlpha = true;
  45318. /**
  45319. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45320. */
  45321. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45322. /**
  45323. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45324. */
  45325. _this._useRoughnessFromMetallicTextureAlpha = true;
  45326. /**
  45327. * Specifies if the metallic texture contains the roughness information in its green channel.
  45328. */
  45329. _this._useRoughnessFromMetallicTextureGreen = false;
  45330. /**
  45331. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45332. */
  45333. _this._useMetallnessFromMetallicTextureBlue = false;
  45334. /**
  45335. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45336. */
  45337. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45338. /**
  45339. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45340. */
  45341. _this._useAmbientInGrayScale = false;
  45342. /**
  45343. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45344. * The material will try to infer what glossiness each pixel should be.
  45345. */
  45346. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45347. /**
  45348. * Defines the falloff type used in this material.
  45349. * It by default is Physical.
  45350. */
  45351. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45352. /**
  45353. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45354. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45355. */
  45356. _this._useRadianceOverAlpha = true;
  45357. /**
  45358. * Allows using an object space normal map (instead of tangent space).
  45359. */
  45360. _this._useObjectSpaceNormalMap = false;
  45361. /**
  45362. * Allows using the bump map in parallax mode.
  45363. */
  45364. _this._useParallax = false;
  45365. /**
  45366. * Allows using the bump map in parallax occlusion mode.
  45367. */
  45368. _this._useParallaxOcclusion = false;
  45369. /**
  45370. * Controls the scale bias of the parallax mode.
  45371. */
  45372. _this._parallaxScaleBias = 0.05;
  45373. /**
  45374. * If sets to true, disables all the lights affecting the material.
  45375. */
  45376. _this._disableLighting = false;
  45377. /**
  45378. * Number of Simultaneous lights allowed on the material.
  45379. */
  45380. _this._maxSimultaneousLights = 4;
  45381. /**
  45382. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45383. */
  45384. _this._invertNormalMapX = false;
  45385. /**
  45386. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45387. */
  45388. _this._invertNormalMapY = false;
  45389. /**
  45390. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45391. */
  45392. _this._twoSidedLighting = false;
  45393. /**
  45394. * Defines the alpha limits in alpha test mode.
  45395. */
  45396. _this._alphaCutOff = 0.4;
  45397. /**
  45398. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45399. */
  45400. _this._forceAlphaTest = false;
  45401. /**
  45402. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45403. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45404. */
  45405. _this._useAlphaFresnel = false;
  45406. /**
  45407. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45408. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45409. */
  45410. _this._useLinearAlphaFresnel = false;
  45411. /**
  45412. * The transparency mode of the material.
  45413. */
  45414. _this._transparencyMode = null;
  45415. /**
  45416. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45417. * from cos thetav and roughness:
  45418. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45419. */
  45420. _this._environmentBRDFTexture = null;
  45421. /**
  45422. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45423. */
  45424. _this._forceIrradianceInFragment = false;
  45425. /**
  45426. * Force normal to face away from face.
  45427. */
  45428. _this._forceNormalForward = false;
  45429. /**
  45430. * Enables specular anti aliasing in the PBR shader.
  45431. * It will both interacts on the Geometry for analytical and IBL lighting.
  45432. * It also prefilter the roughness map based on the bump values.
  45433. */
  45434. _this._enableSpecularAntiAliasing = false;
  45435. /**
  45436. * Stores the available render targets.
  45437. */
  45438. _this._renderTargets = new BABYLON.SmartArray(16);
  45439. /**
  45440. * Sets the global ambient color for the material used in lighting calculations.
  45441. */
  45442. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45443. /**
  45444. * If set to true, no lighting calculations will be applied.
  45445. */
  45446. _this._unlit = false;
  45447. // Setup the default processing configuration to the scene.
  45448. _this._attachImageProcessingConfiguration(null);
  45449. _this.getRenderTargetTextures = function () {
  45450. _this._renderTargets.reset();
  45451. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45452. _this._renderTargets.push(_this._reflectionTexture);
  45453. }
  45454. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45455. _this._renderTargets.push(_this._refractionTexture);
  45456. }
  45457. return _this._renderTargets;
  45458. };
  45459. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45460. return _this;
  45461. }
  45462. /**
  45463. * Attaches a new image processing configuration to the PBR Material.
  45464. * @param configuration
  45465. */
  45466. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45467. var _this = this;
  45468. if (configuration === this._imageProcessingConfiguration) {
  45469. return;
  45470. }
  45471. // Detaches observer.
  45472. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45473. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45474. }
  45475. // Pick the scene configuration if needed.
  45476. if (!configuration) {
  45477. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45478. }
  45479. else {
  45480. this._imageProcessingConfiguration = configuration;
  45481. }
  45482. // Attaches observer.
  45483. if (this._imageProcessingConfiguration) {
  45484. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45485. _this._markAllSubMeshesAsImageProcessingDirty();
  45486. });
  45487. }
  45488. };
  45489. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45490. /**
  45491. * Gets a boolean indicating that current material needs to register RTT
  45492. */
  45493. get: function () {
  45494. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45495. return true;
  45496. }
  45497. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45498. return true;
  45499. }
  45500. return false;
  45501. },
  45502. enumerable: true,
  45503. configurable: true
  45504. });
  45505. /**
  45506. * Gets the name of the material class.
  45507. */
  45508. PBRBaseMaterial.prototype.getClassName = function () {
  45509. return "PBRBaseMaterial";
  45510. };
  45511. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45512. /**
  45513. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45514. */
  45515. get: function () {
  45516. return this._useLogarithmicDepth;
  45517. },
  45518. /**
  45519. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45520. */
  45521. set: function (value) {
  45522. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45523. },
  45524. enumerable: true,
  45525. configurable: true
  45526. });
  45527. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45528. /**
  45529. * Gets the current transparency mode.
  45530. */
  45531. get: function () {
  45532. return this._transparencyMode;
  45533. },
  45534. /**
  45535. * Sets the transparency mode of the material.
  45536. *
  45537. * | Value | Type | Description |
  45538. * | ----- | ----------------------------------- | ----------- |
  45539. * | 0 | OPAQUE | |
  45540. * | 1 | ALPHATEST | |
  45541. * | 2 | ALPHABLEND | |
  45542. * | 3 | ALPHATESTANDBLEND | |
  45543. *
  45544. */
  45545. set: function (value) {
  45546. if (this._transparencyMode === value) {
  45547. return;
  45548. }
  45549. this._transparencyMode = value;
  45550. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45551. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45552. },
  45553. enumerable: true,
  45554. configurable: true
  45555. });
  45556. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45557. /**
  45558. * Returns true if alpha blending should be disabled.
  45559. */
  45560. get: function () {
  45561. return (this._linkRefractionWithTransparency ||
  45562. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45563. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45564. },
  45565. enumerable: true,
  45566. configurable: true
  45567. });
  45568. /**
  45569. * Specifies whether or not this material should be rendered in alpha blend mode.
  45570. */
  45571. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45572. if (this._disableAlphaBlending) {
  45573. return false;
  45574. }
  45575. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45576. };
  45577. /**
  45578. * Specifies if the mesh will require alpha blending.
  45579. * @param mesh - BJS mesh.
  45580. */
  45581. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45582. if (this._disableAlphaBlending) {
  45583. return false;
  45584. }
  45585. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45586. };
  45587. /**
  45588. * Specifies whether or not this material should be rendered in alpha test mode.
  45589. */
  45590. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45591. if (this._forceAlphaTest) {
  45592. return true;
  45593. }
  45594. if (this._linkRefractionWithTransparency) {
  45595. return false;
  45596. }
  45597. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45598. };
  45599. /**
  45600. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45601. */
  45602. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45603. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45604. };
  45605. /**
  45606. * Gets the texture used for the alpha test.
  45607. */
  45608. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45609. return this._albedoTexture;
  45610. };
  45611. /**
  45612. * Specifies that the submesh is ready to be used.
  45613. * @param mesh - BJS mesh.
  45614. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45615. * @param useInstances - Specifies that instances should be used.
  45616. * @returns - boolean indicating that the submesh is ready or not.
  45617. */
  45618. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45619. if (subMesh.effect && this.isFrozen) {
  45620. if (this._wasPreviouslyReady) {
  45621. return true;
  45622. }
  45623. }
  45624. if (!subMesh._materialDefines) {
  45625. subMesh._materialDefines = new PBRMaterialDefines();
  45626. }
  45627. var defines = subMesh._materialDefines;
  45628. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45629. if (defines._renderId === this.getScene().getRenderId()) {
  45630. return true;
  45631. }
  45632. }
  45633. var scene = this.getScene();
  45634. var engine = scene.getEngine();
  45635. if (defines._areTexturesDirty) {
  45636. if (scene.texturesEnabled) {
  45637. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45638. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45639. return false;
  45640. }
  45641. }
  45642. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45643. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45644. return false;
  45645. }
  45646. }
  45647. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45648. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45649. return false;
  45650. }
  45651. }
  45652. var reflectionTexture = this._getReflectionTexture();
  45653. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45654. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45655. return false;
  45656. }
  45657. }
  45658. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45659. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45660. return false;
  45661. }
  45662. }
  45663. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45664. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45665. return false;
  45666. }
  45667. }
  45668. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45669. if (this._metallicTexture) {
  45670. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45671. return false;
  45672. }
  45673. }
  45674. else if (this._reflectivityTexture) {
  45675. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45676. return false;
  45677. }
  45678. }
  45679. if (this._microSurfaceTexture) {
  45680. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45681. return false;
  45682. }
  45683. }
  45684. }
  45685. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45686. // Bump texture cannot be not blocking.
  45687. if (!this._bumpTexture.isReady()) {
  45688. return false;
  45689. }
  45690. }
  45691. var refractionTexture = this._getRefractionTexture();
  45692. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45693. if (!refractionTexture.isReadyOrNotBlocking()) {
  45694. return false;
  45695. }
  45696. }
  45697. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45698. // This is blocking.
  45699. if (!this._environmentBRDFTexture.isReady()) {
  45700. return false;
  45701. }
  45702. }
  45703. }
  45704. }
  45705. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45706. if (!this._imageProcessingConfiguration.isReady()) {
  45707. return false;
  45708. }
  45709. }
  45710. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45711. mesh.createNormals(true);
  45712. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45713. }
  45714. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45715. if (effect) {
  45716. scene.resetCachedMaterial();
  45717. subMesh.setEffect(effect, defines);
  45718. this.buildUniformLayout();
  45719. }
  45720. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45721. return false;
  45722. }
  45723. defines._renderId = scene.getRenderId();
  45724. this._wasPreviouslyReady = true;
  45725. return true;
  45726. };
  45727. /**
  45728. * Specifies if the material uses metallic roughness workflow.
  45729. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45730. */
  45731. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45732. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45733. return true;
  45734. }
  45735. return false;
  45736. };
  45737. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45738. if (onCompiled === void 0) { onCompiled = null; }
  45739. if (onError === void 0) { onError = null; }
  45740. if (useInstances === void 0) { useInstances = null; }
  45741. if (useClipPlane === void 0) { useClipPlane = null; }
  45742. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45743. if (!defines.isDirty) {
  45744. return null;
  45745. }
  45746. defines.markAsProcessed();
  45747. var scene = this.getScene();
  45748. var engine = scene.getEngine();
  45749. // Fallbacks
  45750. var fallbacks = new BABYLON.EffectFallbacks();
  45751. var fallbackRank = 0;
  45752. if (defines.USESPHERICALINVERTEX) {
  45753. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45754. }
  45755. if (defines.FOG) {
  45756. fallbacks.addFallback(fallbackRank, "FOG");
  45757. }
  45758. if (defines.SPECULARAA) {
  45759. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45760. }
  45761. if (defines.POINTSIZE) {
  45762. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45763. }
  45764. if (defines.LOGARITHMICDEPTH) {
  45765. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45766. }
  45767. if (defines.PARALLAX) {
  45768. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45769. }
  45770. if (defines.PARALLAXOCCLUSION) {
  45771. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45772. }
  45773. if (defines.ENVIRONMENTBRDF) {
  45774. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45775. }
  45776. if (defines.TANGENT) {
  45777. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45778. }
  45779. if (defines.BUMP) {
  45780. fallbacks.addFallback(fallbackRank++, "BUMP");
  45781. }
  45782. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45783. if (defines.SPECULARTERM) {
  45784. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45785. }
  45786. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45787. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45788. }
  45789. if (defines.LIGHTMAP) {
  45790. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45791. }
  45792. if (defines.NORMAL) {
  45793. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45794. }
  45795. if (defines.AMBIENT) {
  45796. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45797. }
  45798. if (defines.EMISSIVE) {
  45799. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45800. }
  45801. if (defines.VERTEXCOLOR) {
  45802. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45803. }
  45804. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45805. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45806. }
  45807. if (defines.MORPHTARGETS) {
  45808. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45809. }
  45810. //Attributes
  45811. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45812. if (defines.NORMAL) {
  45813. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45814. }
  45815. if (defines.TANGENT) {
  45816. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45817. }
  45818. if (defines.UV1) {
  45819. attribs.push(BABYLON.VertexBuffer.UVKind);
  45820. }
  45821. if (defines.UV2) {
  45822. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45823. }
  45824. if (defines.VERTEXCOLOR) {
  45825. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45826. }
  45827. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45828. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45829. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45830. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45831. "vFogInfos", "vFogColor", "pointSize",
  45832. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45833. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45834. "mBones",
  45835. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45836. "vLightingIntensity",
  45837. "logarithmicDepthConstant",
  45838. "vSphericalX", "vSphericalY", "vSphericalZ",
  45839. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45840. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45841. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45842. "vTangentSpaceParams"
  45843. ];
  45844. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45845. "bumpSampler", "lightmapSampler", "opacitySampler",
  45846. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45847. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45848. "microSurfaceSampler", "environmentBrdfSampler"];
  45849. var uniformBuffers = ["Material", "Scene"];
  45850. if (BABYLON.ImageProcessingConfiguration) {
  45851. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45852. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45853. }
  45854. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45855. uniformsNames: uniforms,
  45856. uniformBuffersNames: uniformBuffers,
  45857. samplers: samplers,
  45858. defines: defines,
  45859. maxSimultaneousLights: this._maxSimultaneousLights
  45860. });
  45861. var join = defines.toString();
  45862. return engine.createEffect("pbr", {
  45863. attributes: attribs,
  45864. uniformsNames: uniforms,
  45865. uniformBuffersNames: uniformBuffers,
  45866. samplers: samplers,
  45867. defines: join,
  45868. fallbacks: fallbacks,
  45869. onCompiled: onCompiled,
  45870. onError: onError,
  45871. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45872. }, engine);
  45873. };
  45874. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45875. if (useInstances === void 0) { useInstances = null; }
  45876. if (useClipPlane === void 0) { useClipPlane = null; }
  45877. var scene = this.getScene();
  45878. var engine = scene.getEngine();
  45879. // Lights
  45880. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45881. defines._needNormals = true;
  45882. // Textures
  45883. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45884. if (defines._areTexturesDirty) {
  45885. defines._needUVs = false;
  45886. if (scene.texturesEnabled) {
  45887. if (scene.getEngine().getCaps().textureLOD) {
  45888. defines.LODBASEDMICROSFURACE = true;
  45889. }
  45890. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45891. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45892. }
  45893. else {
  45894. defines.ALBEDO = false;
  45895. }
  45896. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45897. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45898. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45899. }
  45900. else {
  45901. defines.AMBIENT = false;
  45902. }
  45903. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45904. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45905. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45906. }
  45907. else {
  45908. defines.OPACITY = false;
  45909. }
  45910. var reflectionTexture = this._getReflectionTexture();
  45911. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45912. defines.REFLECTION = true;
  45913. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45914. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45915. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45916. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45917. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45918. defines.INVERTCUBICMAP = true;
  45919. }
  45920. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45921. switch (reflectionTexture.coordinatesMode) {
  45922. case BABYLON.Texture.EXPLICIT_MODE:
  45923. defines.REFLECTIONMAP_EXPLICIT = true;
  45924. break;
  45925. case BABYLON.Texture.PLANAR_MODE:
  45926. defines.REFLECTIONMAP_PLANAR = true;
  45927. break;
  45928. case BABYLON.Texture.PROJECTION_MODE:
  45929. defines.REFLECTIONMAP_PROJECTION = true;
  45930. break;
  45931. case BABYLON.Texture.SKYBOX_MODE:
  45932. defines.REFLECTIONMAP_SKYBOX = true;
  45933. break;
  45934. case BABYLON.Texture.SPHERICAL_MODE:
  45935. defines.REFLECTIONMAP_SPHERICAL = true;
  45936. break;
  45937. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45938. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45939. break;
  45940. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45941. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45942. break;
  45943. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45944. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45945. break;
  45946. case BABYLON.Texture.CUBIC_MODE:
  45947. case BABYLON.Texture.INVCUBIC_MODE:
  45948. default:
  45949. defines.REFLECTIONMAP_CUBIC = true;
  45950. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45951. break;
  45952. }
  45953. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45954. if (reflectionTexture.sphericalPolynomial) {
  45955. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45956. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45957. defines.USESPHERICALINVERTEX = false;
  45958. }
  45959. else {
  45960. defines.USESPHERICALINVERTEX = true;
  45961. }
  45962. }
  45963. }
  45964. else {
  45965. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45966. }
  45967. }
  45968. else {
  45969. defines.REFLECTION = false;
  45970. defines.REFLECTIONMAP_3D = false;
  45971. defines.REFLECTIONMAP_SPHERICAL = false;
  45972. defines.REFLECTIONMAP_PLANAR = false;
  45973. defines.REFLECTIONMAP_CUBIC = false;
  45974. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45975. defines.REFLECTIONMAP_PROJECTION = false;
  45976. defines.REFLECTIONMAP_SKYBOX = false;
  45977. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45978. defines.REFLECTIONMAP_EXPLICIT = false;
  45979. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45980. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45981. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45982. defines.INVERTCUBICMAP = false;
  45983. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45984. defines.USESPHERICALINVERTEX = false;
  45985. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45986. defines.LODINREFLECTIONALPHA = false;
  45987. defines.GAMMAREFLECTION = false;
  45988. defines.RGBDREFLECTION = false;
  45989. }
  45990. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45991. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45992. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45993. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45994. }
  45995. else {
  45996. defines.LIGHTMAP = false;
  45997. }
  45998. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45999. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  46000. }
  46001. else {
  46002. defines.EMISSIVE = false;
  46003. }
  46004. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46005. if (this._metallicTexture) {
  46006. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  46007. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  46008. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  46009. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  46010. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  46011. }
  46012. else if (this._reflectivityTexture) {
  46013. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  46014. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  46015. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  46016. }
  46017. else {
  46018. defines.REFLECTIVITY = false;
  46019. }
  46020. if (this._microSurfaceTexture) {
  46021. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  46022. }
  46023. else {
  46024. defines.MICROSURFACEMAP = false;
  46025. }
  46026. }
  46027. else {
  46028. defines.REFLECTIVITY = false;
  46029. defines.MICROSURFACEMAP = false;
  46030. }
  46031. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46032. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  46033. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46034. defines.PARALLAX = true;
  46035. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  46036. }
  46037. else {
  46038. defines.PARALLAX = false;
  46039. }
  46040. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  46041. }
  46042. else {
  46043. defines.BUMP = false;
  46044. }
  46045. var refractionTexture = this._getRefractionTexture();
  46046. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46047. defines.REFRACTION = true;
  46048. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  46049. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  46050. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  46051. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  46052. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  46053. if (this._linkRefractionWithTransparency) {
  46054. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  46055. }
  46056. }
  46057. else {
  46058. defines.REFRACTION = false;
  46059. }
  46060. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46061. defines.ENVIRONMENTBRDF = true;
  46062. }
  46063. else {
  46064. defines.ENVIRONMENTBRDF = false;
  46065. }
  46066. if (this._shouldUseAlphaFromAlbedoTexture()) {
  46067. defines.ALPHAFROMALBEDO = true;
  46068. }
  46069. else {
  46070. defines.ALPHAFROMALBEDO = false;
  46071. }
  46072. }
  46073. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  46074. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  46075. defines.USEPHYSICALLIGHTFALLOFF = false;
  46076. defines.USEGLTFLIGHTFALLOFF = false;
  46077. }
  46078. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  46079. defines.USEPHYSICALLIGHTFALLOFF = false;
  46080. defines.USEGLTFLIGHTFALLOFF = true;
  46081. }
  46082. else {
  46083. defines.USEPHYSICALLIGHTFALLOFF = true;
  46084. defines.USEGLTFLIGHTFALLOFF = false;
  46085. }
  46086. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  46087. if (!this.backFaceCulling && this._twoSidedLighting) {
  46088. defines.TWOSIDEDLIGHTING = true;
  46089. }
  46090. else {
  46091. defines.TWOSIDEDLIGHTING = false;
  46092. }
  46093. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  46094. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  46095. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  46096. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  46097. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  46098. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  46099. }
  46100. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46101. this._imageProcessingConfiguration.prepareDefines(defines);
  46102. }
  46103. defines.FORCENORMALFORWARD = this._forceNormalForward;
  46104. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  46105. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  46106. // Misc.
  46107. if (defines._areMiscDirty) {
  46108. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  46109. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  46110. }
  46111. // Values that need to be evaluated on every frame
  46112. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46113. // Attribs
  46114. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46115. };
  46116. /**
  46117. * Force shader compilation
  46118. */
  46119. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46120. var _this = this;
  46121. var localOptions = __assign({ clipPlane: false }, options);
  46122. var defines = new PBRMaterialDefines();
  46123. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46124. if (effect.isReady()) {
  46125. if (onCompiled) {
  46126. onCompiled(this);
  46127. }
  46128. }
  46129. else {
  46130. effect.onCompileObservable.add(function () {
  46131. if (onCompiled) {
  46132. onCompiled(_this);
  46133. }
  46134. });
  46135. }
  46136. };
  46137. /**
  46138. * Initializes the uniform buffer layout for the shader.
  46139. */
  46140. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46141. // Order is important !
  46142. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46143. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46144. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46145. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46146. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46147. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46148. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46149. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46150. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46151. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46152. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46153. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46154. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46155. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46156. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46157. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46158. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46159. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46160. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46161. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46162. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46163. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46164. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46165. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46166. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46167. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46168. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46169. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46170. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46171. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46172. this._uniformBuffer.addUniform("pointSize", 1);
  46173. this._uniformBuffer.create();
  46174. };
  46175. /**
  46176. * Unbinds the textures.
  46177. */
  46178. PBRBaseMaterial.prototype.unbind = function () {
  46179. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46180. this._uniformBuffer.setTexture("reflectionSampler", null);
  46181. }
  46182. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46183. this._uniformBuffer.setTexture("refractionSampler", null);
  46184. }
  46185. _super.prototype.unbind.call(this);
  46186. };
  46187. /**
  46188. * Binds the submesh data.
  46189. * @param world - The world matrix.
  46190. * @param mesh - The BJS mesh.
  46191. * @param subMesh - A submesh of the BJS mesh.
  46192. */
  46193. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46194. var scene = this.getScene();
  46195. var defines = subMesh._materialDefines;
  46196. if (!defines) {
  46197. return;
  46198. }
  46199. var effect = subMesh.effect;
  46200. if (!effect) {
  46201. return;
  46202. }
  46203. this._activeEffect = effect;
  46204. // Matrices
  46205. this.bindOnlyWorldMatrix(world);
  46206. // Normal Matrix
  46207. if (defines.OBJECTSPACE_NORMALMAP) {
  46208. world.toNormalMatrix(this._normalMatrix);
  46209. this.bindOnlyNormalMatrix(this._normalMatrix);
  46210. }
  46211. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46212. // Bones
  46213. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46214. var reflectionTexture = null;
  46215. if (mustRebind) {
  46216. this._uniformBuffer.bindToEffect(effect, "Material");
  46217. this.bindViewProjection(effect);
  46218. reflectionTexture = this._getReflectionTexture();
  46219. var refractionTexture = this._getRefractionTexture();
  46220. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46221. // Texture uniforms
  46222. if (scene.texturesEnabled) {
  46223. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46224. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46225. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46226. }
  46227. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46228. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46229. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46230. }
  46231. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46232. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46233. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46234. }
  46235. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46236. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46237. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46238. if (reflectionTexture.boundingBoxSize) {
  46239. var cubeTexture = reflectionTexture;
  46240. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46241. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46242. }
  46243. var polynomials = reflectionTexture.sphericalPolynomial;
  46244. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46245. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46246. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46247. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46248. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46249. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46250. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46251. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46252. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46253. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46254. }
  46255. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46256. }
  46257. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46258. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46259. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46260. }
  46261. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46262. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46263. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46264. }
  46265. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46266. if (this._metallicTexture) {
  46267. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46268. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46269. }
  46270. else if (this._reflectivityTexture) {
  46271. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46272. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46273. }
  46274. if (this._microSurfaceTexture) {
  46275. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46276. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46277. }
  46278. }
  46279. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46280. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46281. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46282. if (scene._mirroredCameraPosition) {
  46283. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46284. }
  46285. else {
  46286. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46287. }
  46288. }
  46289. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46290. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46291. var depth = 1.0;
  46292. if (!refractionTexture.isCube) {
  46293. if (refractionTexture.depth) {
  46294. depth = refractionTexture.depth;
  46295. }
  46296. }
  46297. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46298. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46299. }
  46300. }
  46301. // Point size
  46302. if (this.pointsCloud) {
  46303. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46304. }
  46305. // Colors
  46306. if (defines.METALLICWORKFLOW) {
  46307. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46308. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46309. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46310. }
  46311. else {
  46312. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46313. }
  46314. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46315. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46316. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46317. // Misc
  46318. this._lightingInfos.x = this._directIntensity;
  46319. this._lightingInfos.y = this._emissiveIntensity;
  46320. this._lightingInfos.z = this._environmentIntensity;
  46321. this._lightingInfos.w = this._specularIntensity;
  46322. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46323. }
  46324. // Textures
  46325. if (scene.texturesEnabled) {
  46326. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46327. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46328. }
  46329. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46330. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46331. }
  46332. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46333. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46334. }
  46335. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46336. if (defines.LODBASEDMICROSFURACE) {
  46337. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46338. }
  46339. else {
  46340. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46341. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46342. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46343. }
  46344. }
  46345. if (defines.ENVIRONMENTBRDF) {
  46346. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46347. }
  46348. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46349. if (defines.LODBASEDMICROSFURACE) {
  46350. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46351. }
  46352. else {
  46353. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46354. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46355. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46356. }
  46357. }
  46358. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46359. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46360. }
  46361. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46362. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46363. }
  46364. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46365. if (this._metallicTexture) {
  46366. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46367. }
  46368. else if (this._reflectivityTexture) {
  46369. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46370. }
  46371. if (this._microSurfaceTexture) {
  46372. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46373. }
  46374. }
  46375. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46376. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46377. }
  46378. }
  46379. // Clip plane
  46380. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46381. // Colors
  46382. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46383. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46384. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46385. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46386. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46387. }
  46388. if (mustRebind || !this.isFrozen) {
  46389. // Lights
  46390. if (scene.lightsEnabled && !this._disableLighting) {
  46391. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46392. }
  46393. // View
  46394. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46395. this.bindView(effect);
  46396. }
  46397. // Fog
  46398. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46399. // Morph targets
  46400. if (defines.NUM_MORPH_INFLUENCERS) {
  46401. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46402. }
  46403. // image processing
  46404. this._imageProcessingConfiguration.bind(this._activeEffect);
  46405. // Log. depth
  46406. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46407. }
  46408. this._uniformBuffer.update();
  46409. this._afterBind(mesh, this._activeEffect);
  46410. };
  46411. /**
  46412. * Returns the animatable textures.
  46413. * @returns - Array of animatable textures.
  46414. */
  46415. PBRBaseMaterial.prototype.getAnimatables = function () {
  46416. var results = [];
  46417. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46418. results.push(this._albedoTexture);
  46419. }
  46420. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46421. results.push(this._ambientTexture);
  46422. }
  46423. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46424. results.push(this._opacityTexture);
  46425. }
  46426. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46427. results.push(this._reflectionTexture);
  46428. }
  46429. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46430. results.push(this._emissiveTexture);
  46431. }
  46432. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46433. results.push(this._metallicTexture);
  46434. }
  46435. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46436. results.push(this._reflectivityTexture);
  46437. }
  46438. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46439. results.push(this._bumpTexture);
  46440. }
  46441. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46442. results.push(this._lightmapTexture);
  46443. }
  46444. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46445. results.push(this._refractionTexture);
  46446. }
  46447. return results;
  46448. };
  46449. /**
  46450. * Returns the texture used for reflections.
  46451. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46452. */
  46453. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46454. if (this._reflectionTexture) {
  46455. return this._reflectionTexture;
  46456. }
  46457. return this.getScene().environmentTexture;
  46458. };
  46459. /**
  46460. * Returns the texture used for refraction or null if none is used.
  46461. * @returns - Refection texture if present. If no refraction texture and refraction
  46462. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46463. */
  46464. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46465. if (this._refractionTexture) {
  46466. return this._refractionTexture;
  46467. }
  46468. if (this._linkRefractionWithTransparency) {
  46469. return this.getScene().environmentTexture;
  46470. }
  46471. return null;
  46472. };
  46473. /**
  46474. * Disposes the resources of the material.
  46475. * @param forceDisposeEffect - Forces the disposal of effects.
  46476. * @param forceDisposeTextures - Forces the disposal of all textures.
  46477. */
  46478. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46479. if (forceDisposeTextures) {
  46480. if (this._albedoTexture) {
  46481. this._albedoTexture.dispose();
  46482. }
  46483. if (this._ambientTexture) {
  46484. this._ambientTexture.dispose();
  46485. }
  46486. if (this._opacityTexture) {
  46487. this._opacityTexture.dispose();
  46488. }
  46489. if (this._reflectionTexture) {
  46490. this._reflectionTexture.dispose();
  46491. }
  46492. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46493. this._environmentBRDFTexture.dispose();
  46494. }
  46495. if (this._emissiveTexture) {
  46496. this._emissiveTexture.dispose();
  46497. }
  46498. if (this._metallicTexture) {
  46499. this._metallicTexture.dispose();
  46500. }
  46501. if (this._reflectivityTexture) {
  46502. this._reflectivityTexture.dispose();
  46503. }
  46504. if (this._bumpTexture) {
  46505. this._bumpTexture.dispose();
  46506. }
  46507. if (this._lightmapTexture) {
  46508. this._lightmapTexture.dispose();
  46509. }
  46510. if (this._refractionTexture) {
  46511. this._refractionTexture.dispose();
  46512. }
  46513. }
  46514. this._renderTargets.dispose();
  46515. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46516. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46517. }
  46518. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46519. };
  46520. /**
  46521. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46522. */
  46523. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46524. /**
  46525. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46526. * to enhance interoperability with other engines.
  46527. */
  46528. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46529. /**
  46530. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46531. * to enhance interoperability with other materials.
  46532. */
  46533. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46534. /**
  46535. * Stores the reflectivity values based on metallic roughness workflow.
  46536. */
  46537. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46538. __decorate([
  46539. BABYLON.serializeAsImageProcessingConfiguration()
  46540. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46541. __decorate([
  46542. BABYLON.serialize()
  46543. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46544. __decorate([
  46545. BABYLON.serialize()
  46546. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46547. return PBRBaseMaterial;
  46548. }(BABYLON.PushMaterial));
  46549. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46550. })(BABYLON || (BABYLON = {}));
  46551. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46552. var BABYLON;
  46553. (function (BABYLON) {
  46554. /**
  46555. * The Physically based simple base material of BJS.
  46556. *
  46557. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46558. * It is used as the base class for both the specGloss and metalRough conventions.
  46559. */
  46560. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46561. __extends(PBRBaseSimpleMaterial, _super);
  46562. /**
  46563. * Instantiates a new PBRMaterial instance.
  46564. *
  46565. * @param name The material name
  46566. * @param scene The scene the material will be use in.
  46567. */
  46568. function PBRBaseSimpleMaterial(name, scene) {
  46569. var _this = _super.call(this, name, scene) || this;
  46570. /**
  46571. * Number of Simultaneous lights allowed on the material.
  46572. */
  46573. _this.maxSimultaneousLights = 4;
  46574. /**
  46575. * If sets to true, disables all the lights affecting the material.
  46576. */
  46577. _this.disableLighting = false;
  46578. /**
  46579. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46580. */
  46581. _this.invertNormalMapX = false;
  46582. /**
  46583. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46584. */
  46585. _this.invertNormalMapY = false;
  46586. /**
  46587. * Emissivie color used to self-illuminate the model.
  46588. */
  46589. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46590. /**
  46591. * Occlusion Channel Strenght.
  46592. */
  46593. _this.occlusionStrength = 1.0;
  46594. /**
  46595. * If true, the light map contains occlusion information instead of lighting info.
  46596. */
  46597. _this.useLightmapAsShadowmap = false;
  46598. _this._useAlphaFromAlbedoTexture = true;
  46599. _this._useAmbientInGrayScale = true;
  46600. return _this;
  46601. }
  46602. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46603. /**
  46604. * Gets the current double sided mode.
  46605. */
  46606. get: function () {
  46607. return this._twoSidedLighting;
  46608. },
  46609. /**
  46610. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46611. */
  46612. set: function (value) {
  46613. if (this._twoSidedLighting === value) {
  46614. return;
  46615. }
  46616. this._twoSidedLighting = value;
  46617. this.backFaceCulling = !value;
  46618. this._markAllSubMeshesAsTexturesDirty();
  46619. },
  46620. enumerable: true,
  46621. configurable: true
  46622. });
  46623. /**
  46624. * Return the active textures of the material.
  46625. */
  46626. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46627. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46628. if (this.environmentTexture) {
  46629. activeTextures.push(this.environmentTexture);
  46630. }
  46631. if (this.normalTexture) {
  46632. activeTextures.push(this.normalTexture);
  46633. }
  46634. if (this.emissiveTexture) {
  46635. activeTextures.push(this.emissiveTexture);
  46636. }
  46637. if (this.occlusionTexture) {
  46638. activeTextures.push(this.occlusionTexture);
  46639. }
  46640. if (this.lightmapTexture) {
  46641. activeTextures.push(this.lightmapTexture);
  46642. }
  46643. return activeTextures;
  46644. };
  46645. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46646. if (_super.prototype.hasTexture.call(this, texture)) {
  46647. return true;
  46648. }
  46649. if (this.lightmapTexture === texture) {
  46650. return true;
  46651. }
  46652. return false;
  46653. };
  46654. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46655. return "PBRBaseSimpleMaterial";
  46656. };
  46657. __decorate([
  46658. BABYLON.serialize(),
  46659. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46660. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46661. __decorate([
  46662. BABYLON.serialize(),
  46663. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46664. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46665. __decorate([
  46666. BABYLON.serializeAsTexture(),
  46667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46668. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46669. __decorate([
  46670. BABYLON.serialize(),
  46671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46672. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46673. __decorate([
  46674. BABYLON.serialize(),
  46675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46676. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46677. __decorate([
  46678. BABYLON.serializeAsTexture(),
  46679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46680. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46681. __decorate([
  46682. BABYLON.serializeAsColor3("emissive"),
  46683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46684. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46685. __decorate([
  46686. BABYLON.serializeAsTexture(),
  46687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46688. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46689. __decorate([
  46690. BABYLON.serialize(),
  46691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46692. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46693. __decorate([
  46694. BABYLON.serializeAsTexture(),
  46695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46696. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46697. __decorate([
  46698. BABYLON.serialize(),
  46699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46700. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46701. __decorate([
  46702. BABYLON.serialize()
  46703. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46704. __decorate([
  46705. BABYLON.serializeAsTexture(),
  46706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46707. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46708. __decorate([
  46709. BABYLON.serialize(),
  46710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46711. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46712. return PBRBaseSimpleMaterial;
  46713. }(BABYLON.PBRBaseMaterial));
  46714. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46715. })(BABYLON || (BABYLON = {}));
  46716. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46717. var BABYLON;
  46718. (function (BABYLON) {
  46719. /**
  46720. * The Physically based material of BJS.
  46721. *
  46722. * This offers the main features of a standard PBR material.
  46723. * For more information, please refer to the documentation :
  46724. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46725. */
  46726. var PBRMaterial = /** @class */ (function (_super) {
  46727. __extends(PBRMaterial, _super);
  46728. /**
  46729. * Instantiates a new PBRMaterial instance.
  46730. *
  46731. * @param name The material name
  46732. * @param scene The scene the material will be use in.
  46733. */
  46734. function PBRMaterial(name, scene) {
  46735. var _this = _super.call(this, name, scene) || this;
  46736. /**
  46737. * Intensity of the direct lights e.g. the four lights available in your scene.
  46738. * This impacts both the direct diffuse and specular highlights.
  46739. */
  46740. _this.directIntensity = 1.0;
  46741. /**
  46742. * Intensity of the emissive part of the material.
  46743. * This helps controlling the emissive effect without modifying the emissive color.
  46744. */
  46745. _this.emissiveIntensity = 1.0;
  46746. /**
  46747. * Intensity of the environment e.g. how much the environment will light the object
  46748. * either through harmonics for rough material or through the refelction for shiny ones.
  46749. */
  46750. _this.environmentIntensity = 1.0;
  46751. /**
  46752. * This is a special control allowing the reduction of the specular highlights coming from the
  46753. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46754. */
  46755. _this.specularIntensity = 1.0;
  46756. /**
  46757. * Debug Control allowing disabling the bump map on this material.
  46758. */
  46759. _this.disableBumpMap = false;
  46760. /**
  46761. * AKA Occlusion Texture Intensity in other nomenclature.
  46762. */
  46763. _this.ambientTextureStrength = 1.0;
  46764. /**
  46765. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46766. * 1 means it completely occludes it
  46767. * 0 mean it has no impact
  46768. */
  46769. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46770. /**
  46771. * The color of a material in ambient lighting.
  46772. */
  46773. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46774. /**
  46775. * AKA Diffuse Color in other nomenclature.
  46776. */
  46777. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46778. /**
  46779. * AKA Specular Color in other nomenclature.
  46780. */
  46781. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46782. /**
  46783. * The color reflected from the material.
  46784. */
  46785. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46786. /**
  46787. * The color emitted from the material.
  46788. */
  46789. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46790. /**
  46791. * AKA Glossiness in other nomenclature.
  46792. */
  46793. _this.microSurface = 1.0;
  46794. /**
  46795. * source material index of refraction (IOR)' / 'destination material IOR.
  46796. */
  46797. _this.indexOfRefraction = 0.66;
  46798. /**
  46799. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46800. */
  46801. _this.invertRefractionY = false;
  46802. /**
  46803. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46804. * Materials half opaque for instance using refraction could benefit from this control.
  46805. */
  46806. _this.linkRefractionWithTransparency = false;
  46807. /**
  46808. * If true, the light map contains occlusion information instead of lighting info.
  46809. */
  46810. _this.useLightmapAsShadowmap = false;
  46811. /**
  46812. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46813. */
  46814. _this.useAlphaFromAlbedoTexture = false;
  46815. /**
  46816. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46817. */
  46818. _this.forceAlphaTest = false;
  46819. /**
  46820. * Defines the alpha limits in alpha test mode.
  46821. */
  46822. _this.alphaCutOff = 0.4;
  46823. /**
  46824. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46825. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46826. */
  46827. _this.useSpecularOverAlpha = true;
  46828. /**
  46829. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46830. */
  46831. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46832. /**
  46833. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46834. */
  46835. _this.useRoughnessFromMetallicTextureAlpha = true;
  46836. /**
  46837. * Specifies if the metallic texture contains the roughness information in its green channel.
  46838. */
  46839. _this.useRoughnessFromMetallicTextureGreen = false;
  46840. /**
  46841. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46842. */
  46843. _this.useMetallnessFromMetallicTextureBlue = false;
  46844. /**
  46845. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46846. */
  46847. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46848. /**
  46849. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46850. */
  46851. _this.useAmbientInGrayScale = false;
  46852. /**
  46853. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46854. * The material will try to infer what glossiness each pixel should be.
  46855. */
  46856. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46857. /**
  46858. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46859. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46860. */
  46861. _this.useRadianceOverAlpha = true;
  46862. /**
  46863. * Allows using an object space normal map (instead of tangent space).
  46864. */
  46865. _this.useObjectSpaceNormalMap = false;
  46866. /**
  46867. * Allows using the bump map in parallax mode.
  46868. */
  46869. _this.useParallax = false;
  46870. /**
  46871. * Allows using the bump map in parallax occlusion mode.
  46872. */
  46873. _this.useParallaxOcclusion = false;
  46874. /**
  46875. * Controls the scale bias of the parallax mode.
  46876. */
  46877. _this.parallaxScaleBias = 0.05;
  46878. /**
  46879. * If sets to true, disables all the lights affecting the material.
  46880. */
  46881. _this.disableLighting = false;
  46882. /**
  46883. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46884. */
  46885. _this.forceIrradianceInFragment = false;
  46886. /**
  46887. * Number of Simultaneous lights allowed on the material.
  46888. */
  46889. _this.maxSimultaneousLights = 4;
  46890. /**
  46891. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46892. */
  46893. _this.invertNormalMapX = false;
  46894. /**
  46895. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46896. */
  46897. _this.invertNormalMapY = false;
  46898. /**
  46899. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46900. */
  46901. _this.twoSidedLighting = false;
  46902. /**
  46903. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46904. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46905. */
  46906. _this.useAlphaFresnel = false;
  46907. /**
  46908. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46909. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46910. */
  46911. _this.useLinearAlphaFresnel = false;
  46912. /**
  46913. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46914. * And/Or occlude the blended part.
  46915. */
  46916. _this.environmentBRDFTexture = null;
  46917. /**
  46918. * Force normal to face away from face.
  46919. */
  46920. _this.forceNormalForward = false;
  46921. /**
  46922. * Enables specular anti aliasing in the PBR shader.
  46923. * It will both interacts on the Geometry for analytical and IBL lighting.
  46924. * It also prefilter the roughness map based on the bump values.
  46925. */
  46926. _this.enableSpecularAntiAliasing = false;
  46927. /**
  46928. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46929. * makes the reflect vector face the model (under horizon).
  46930. */
  46931. _this.useHorizonOcclusion = true;
  46932. /**
  46933. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46934. * too much the area relying on ambient texture to define their ambient occlusion.
  46935. */
  46936. _this.useRadianceOcclusion = true;
  46937. /**
  46938. * If set to true, no lighting calculations will be applied.
  46939. */
  46940. _this.unlit = false;
  46941. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46942. return _this;
  46943. }
  46944. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46945. /**
  46946. * BJS is using an harcoded light falloff based on a manually sets up range.
  46947. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46948. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46949. */
  46950. get: function () {
  46951. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46952. },
  46953. /**
  46954. * BJS is using an harcoded light falloff based on a manually sets up range.
  46955. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46956. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46957. */
  46958. set: function (value) {
  46959. if (value !== this.usePhysicalLightFalloff) {
  46960. // Ensure the effect will be rebuilt.
  46961. this._markAllSubMeshesAsTexturesDirty();
  46962. if (value) {
  46963. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46964. }
  46965. else {
  46966. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46967. }
  46968. }
  46969. },
  46970. enumerable: true,
  46971. configurable: true
  46972. });
  46973. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46974. /**
  46975. * In order to support the falloff compatibility with gltf, a special mode has been added
  46976. * to reproduce the gltf light falloff.
  46977. */
  46978. get: function () {
  46979. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46980. },
  46981. /**
  46982. * In order to support the falloff compatibility with gltf, a special mode has been added
  46983. * to reproduce the gltf light falloff.
  46984. */
  46985. set: function (value) {
  46986. if (value !== this.useGLTFLightFalloff) {
  46987. // Ensure the effect will be rebuilt.
  46988. this._markAllSubMeshesAsTexturesDirty();
  46989. if (value) {
  46990. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46991. }
  46992. else {
  46993. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46994. }
  46995. }
  46996. },
  46997. enumerable: true,
  46998. configurable: true
  46999. });
  47000. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  47001. /**
  47002. * Gets the image processing configuration used either in this material.
  47003. */
  47004. get: function () {
  47005. return this._imageProcessingConfiguration;
  47006. },
  47007. /**
  47008. * Sets the Default image processing configuration used either in the this material.
  47009. *
  47010. * If sets to null, the scene one is in use.
  47011. */
  47012. set: function (value) {
  47013. this._attachImageProcessingConfiguration(value);
  47014. // Ensure the effect will be rebuilt.
  47015. this._markAllSubMeshesAsTexturesDirty();
  47016. },
  47017. enumerable: true,
  47018. configurable: true
  47019. });
  47020. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  47021. /**
  47022. * Gets wether the color curves effect is enabled.
  47023. */
  47024. get: function () {
  47025. return this.imageProcessingConfiguration.colorCurvesEnabled;
  47026. },
  47027. /**
  47028. * Sets wether the color curves effect is enabled.
  47029. */
  47030. set: function (value) {
  47031. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  47032. },
  47033. enumerable: true,
  47034. configurable: true
  47035. });
  47036. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  47037. /**
  47038. * Gets wether the color grading effect is enabled.
  47039. */
  47040. get: function () {
  47041. return this.imageProcessingConfiguration.colorGradingEnabled;
  47042. },
  47043. /**
  47044. * Gets wether the color grading effect is enabled.
  47045. */
  47046. set: function (value) {
  47047. this.imageProcessingConfiguration.colorGradingEnabled = value;
  47048. },
  47049. enumerable: true,
  47050. configurable: true
  47051. });
  47052. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  47053. /**
  47054. * Gets wether tonemapping is enabled or not.
  47055. */
  47056. get: function () {
  47057. return this._imageProcessingConfiguration.toneMappingEnabled;
  47058. },
  47059. /**
  47060. * Sets wether tonemapping is enabled or not
  47061. */
  47062. set: function (value) {
  47063. this._imageProcessingConfiguration.toneMappingEnabled = value;
  47064. },
  47065. enumerable: true,
  47066. configurable: true
  47067. });
  47068. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  47069. /**
  47070. * The camera exposure used on this material.
  47071. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47072. * This corresponds to a photographic exposure.
  47073. */
  47074. get: function () {
  47075. return this._imageProcessingConfiguration.exposure;
  47076. },
  47077. /**
  47078. * The camera exposure used on this material.
  47079. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47080. * This corresponds to a photographic exposure.
  47081. */
  47082. set: function (value) {
  47083. this._imageProcessingConfiguration.exposure = value;
  47084. },
  47085. enumerable: true,
  47086. configurable: true
  47087. });
  47088. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  47089. /**
  47090. * Gets The camera contrast used on this material.
  47091. */
  47092. get: function () {
  47093. return this._imageProcessingConfiguration.contrast;
  47094. },
  47095. /**
  47096. * Sets The camera contrast used on this material.
  47097. */
  47098. set: function (value) {
  47099. this._imageProcessingConfiguration.contrast = value;
  47100. },
  47101. enumerable: true,
  47102. configurable: true
  47103. });
  47104. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  47105. /**
  47106. * Gets the Color Grading 2D Lookup Texture.
  47107. */
  47108. get: function () {
  47109. return this._imageProcessingConfiguration.colorGradingTexture;
  47110. },
  47111. /**
  47112. * Sets the Color Grading 2D Lookup Texture.
  47113. */
  47114. set: function (value) {
  47115. this._imageProcessingConfiguration.colorGradingTexture = value;
  47116. },
  47117. enumerable: true,
  47118. configurable: true
  47119. });
  47120. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47121. /**
  47122. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47123. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47124. * 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;
  47125. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47126. */
  47127. get: function () {
  47128. return this._imageProcessingConfiguration.colorCurves;
  47129. },
  47130. /**
  47131. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47132. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47133. * 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;
  47134. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47135. */
  47136. set: function (value) {
  47137. this._imageProcessingConfiguration.colorCurves = value;
  47138. },
  47139. enumerable: true,
  47140. configurable: true
  47141. });
  47142. /**
  47143. * Returns the name of this material class.
  47144. */
  47145. PBRMaterial.prototype.getClassName = function () {
  47146. return "PBRMaterial";
  47147. };
  47148. /**
  47149. * Returns an array of the actively used textures.
  47150. * @returns - Array of BaseTextures
  47151. */
  47152. PBRMaterial.prototype.getActiveTextures = function () {
  47153. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47154. if (this._albedoTexture) {
  47155. activeTextures.push(this._albedoTexture);
  47156. }
  47157. if (this._ambientTexture) {
  47158. activeTextures.push(this._ambientTexture);
  47159. }
  47160. if (this._opacityTexture) {
  47161. activeTextures.push(this._opacityTexture);
  47162. }
  47163. if (this._reflectionTexture) {
  47164. activeTextures.push(this._reflectionTexture);
  47165. }
  47166. if (this._emissiveTexture) {
  47167. activeTextures.push(this._emissiveTexture);
  47168. }
  47169. if (this._reflectivityTexture) {
  47170. activeTextures.push(this._reflectivityTexture);
  47171. }
  47172. if (this._metallicTexture) {
  47173. activeTextures.push(this._metallicTexture);
  47174. }
  47175. if (this._microSurfaceTexture) {
  47176. activeTextures.push(this._microSurfaceTexture);
  47177. }
  47178. if (this._bumpTexture) {
  47179. activeTextures.push(this._bumpTexture);
  47180. }
  47181. if (this._lightmapTexture) {
  47182. activeTextures.push(this._lightmapTexture);
  47183. }
  47184. if (this._refractionTexture) {
  47185. activeTextures.push(this._refractionTexture);
  47186. }
  47187. return activeTextures;
  47188. };
  47189. /**
  47190. * Checks to see if a texture is used in the material.
  47191. * @param texture - Base texture to use.
  47192. * @returns - Boolean specifying if a texture is used in the material.
  47193. */
  47194. PBRMaterial.prototype.hasTexture = function (texture) {
  47195. if (_super.prototype.hasTexture.call(this, texture)) {
  47196. return true;
  47197. }
  47198. if (this._albedoTexture === texture) {
  47199. return true;
  47200. }
  47201. if (this._ambientTexture === texture) {
  47202. return true;
  47203. }
  47204. if (this._opacityTexture === texture) {
  47205. return true;
  47206. }
  47207. if (this._reflectionTexture === texture) {
  47208. return true;
  47209. }
  47210. if (this._reflectivityTexture === texture) {
  47211. return true;
  47212. }
  47213. if (this._metallicTexture === texture) {
  47214. return true;
  47215. }
  47216. if (this._microSurfaceTexture === texture) {
  47217. return true;
  47218. }
  47219. if (this._bumpTexture === texture) {
  47220. return true;
  47221. }
  47222. if (this._lightmapTexture === texture) {
  47223. return true;
  47224. }
  47225. if (this._refractionTexture === texture) {
  47226. return true;
  47227. }
  47228. return false;
  47229. };
  47230. /**
  47231. * Makes a duplicate of the current material.
  47232. * @param name - name to use for the new material.
  47233. */
  47234. PBRMaterial.prototype.clone = function (name) {
  47235. var _this = this;
  47236. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47237. clone.id = name;
  47238. clone.name = name;
  47239. return clone;
  47240. };
  47241. /**
  47242. * Serializes this PBR Material.
  47243. * @returns - An object with the serialized material.
  47244. */
  47245. PBRMaterial.prototype.serialize = function () {
  47246. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47247. serializationObject.customType = "BABYLON.PBRMaterial";
  47248. return serializationObject;
  47249. };
  47250. // Statics
  47251. /**
  47252. * Parses a PBR Material from a serialized object.
  47253. * @param source - Serialized object.
  47254. * @param scene - BJS scene instance.
  47255. * @param rootUrl - url for the scene object
  47256. * @returns - PBRMaterial
  47257. */
  47258. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47259. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47260. };
  47261. /**
  47262. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47263. */
  47264. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47265. /**
  47266. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47267. */
  47268. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47269. /**
  47270. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47271. */
  47272. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47273. /**
  47274. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47275. * They are also discarded below the alpha cutoff threshold to improve performances.
  47276. */
  47277. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47278. /**
  47279. * Defines the default value of how much AO map is occluding the analytical lights
  47280. * (point spot...).
  47281. */
  47282. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47283. __decorate([
  47284. BABYLON.serialize(),
  47285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47286. ], PBRMaterial.prototype, "directIntensity", void 0);
  47287. __decorate([
  47288. BABYLON.serialize(),
  47289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47290. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47291. __decorate([
  47292. BABYLON.serialize(),
  47293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47294. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47295. __decorate([
  47296. BABYLON.serialize(),
  47297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47298. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47299. __decorate([
  47300. BABYLON.serialize(),
  47301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47302. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47303. __decorate([
  47304. BABYLON.serializeAsTexture(),
  47305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47306. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47307. __decorate([
  47308. BABYLON.serializeAsTexture(),
  47309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47310. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47311. __decorate([
  47312. BABYLON.serialize(),
  47313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47314. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47315. __decorate([
  47316. BABYLON.serialize(),
  47317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47318. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47319. __decorate([
  47320. BABYLON.serializeAsTexture(),
  47321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47322. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47323. __decorate([
  47324. BABYLON.serializeAsTexture(),
  47325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47326. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47327. __decorate([
  47328. BABYLON.serializeAsTexture(),
  47329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47330. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47331. __decorate([
  47332. BABYLON.serializeAsTexture(),
  47333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47334. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47335. __decorate([
  47336. BABYLON.serializeAsTexture(),
  47337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47338. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47339. __decorate([
  47340. BABYLON.serialize(),
  47341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47342. ], PBRMaterial.prototype, "metallic", void 0);
  47343. __decorate([
  47344. BABYLON.serialize(),
  47345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47346. ], PBRMaterial.prototype, "roughness", void 0);
  47347. __decorate([
  47348. BABYLON.serializeAsTexture(),
  47349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47350. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47351. __decorate([
  47352. BABYLON.serializeAsTexture(),
  47353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47354. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47355. __decorate([
  47356. BABYLON.serializeAsTexture(),
  47357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47358. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47359. __decorate([
  47360. BABYLON.serializeAsTexture(),
  47361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47362. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47363. __decorate([
  47364. BABYLON.serializeAsColor3("ambient"),
  47365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47366. ], PBRMaterial.prototype, "ambientColor", void 0);
  47367. __decorate([
  47368. BABYLON.serializeAsColor3("albedo"),
  47369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47370. ], PBRMaterial.prototype, "albedoColor", void 0);
  47371. __decorate([
  47372. BABYLON.serializeAsColor3("reflectivity"),
  47373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47374. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47375. __decorate([
  47376. BABYLON.serializeAsColor3("reflection"),
  47377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47378. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47379. __decorate([
  47380. BABYLON.serializeAsColor3("emissive"),
  47381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47382. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47383. __decorate([
  47384. BABYLON.serialize(),
  47385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47386. ], PBRMaterial.prototype, "microSurface", void 0);
  47387. __decorate([
  47388. BABYLON.serialize(),
  47389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47390. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47391. __decorate([
  47392. BABYLON.serialize(),
  47393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47394. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47395. __decorate([
  47396. BABYLON.serialize(),
  47397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47398. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47399. __decorate([
  47400. BABYLON.serialize(),
  47401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47402. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47403. __decorate([
  47404. BABYLON.serialize(),
  47405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47406. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47407. __decorate([
  47408. BABYLON.serialize(),
  47409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47410. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47411. __decorate([
  47412. BABYLON.serialize(),
  47413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47414. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47415. __decorate([
  47416. BABYLON.serialize(),
  47417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47418. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47419. __decorate([
  47420. BABYLON.serialize(),
  47421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47422. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47423. __decorate([
  47424. BABYLON.serialize(),
  47425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47426. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47427. __decorate([
  47428. BABYLON.serialize(),
  47429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47430. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47431. __decorate([
  47432. BABYLON.serialize(),
  47433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47434. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47435. __decorate([
  47436. BABYLON.serialize(),
  47437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47438. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47439. __decorate([
  47440. BABYLON.serialize(),
  47441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47442. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47443. __decorate([
  47444. BABYLON.serialize(),
  47445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47446. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47447. __decorate([
  47448. BABYLON.serialize()
  47449. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47450. __decorate([
  47451. BABYLON.serialize()
  47452. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47453. __decorate([
  47454. BABYLON.serialize(),
  47455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47456. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47457. __decorate([
  47458. BABYLON.serialize(),
  47459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47460. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47461. __decorate([
  47462. BABYLON.serialize(),
  47463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47464. ], PBRMaterial.prototype, "useParallax", void 0);
  47465. __decorate([
  47466. BABYLON.serialize(),
  47467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47468. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47469. __decorate([
  47470. BABYLON.serialize(),
  47471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47472. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47473. __decorate([
  47474. BABYLON.serialize(),
  47475. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47476. ], PBRMaterial.prototype, "disableLighting", void 0);
  47477. __decorate([
  47478. BABYLON.serialize(),
  47479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47480. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47481. __decorate([
  47482. BABYLON.serialize(),
  47483. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47484. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47485. __decorate([
  47486. BABYLON.serialize(),
  47487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47488. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47489. __decorate([
  47490. BABYLON.serialize(),
  47491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47492. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47493. __decorate([
  47494. BABYLON.serialize(),
  47495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47496. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47497. __decorate([
  47498. BABYLON.serialize(),
  47499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47500. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47501. __decorate([
  47502. BABYLON.serialize(),
  47503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47504. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47505. __decorate([
  47506. BABYLON.serializeAsTexture(),
  47507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47508. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47509. __decorate([
  47510. BABYLON.serialize(),
  47511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47512. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47513. __decorate([
  47514. BABYLON.serialize(),
  47515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47516. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47517. __decorate([
  47518. BABYLON.serialize(),
  47519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47520. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47521. __decorate([
  47522. BABYLON.serialize(),
  47523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47524. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47525. __decorate([
  47526. BABYLON.serialize(),
  47527. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47528. ], PBRMaterial.prototype, "unlit", void 0);
  47529. return PBRMaterial;
  47530. }(BABYLON.PBRBaseMaterial));
  47531. BABYLON.PBRMaterial = PBRMaterial;
  47532. })(BABYLON || (BABYLON = {}));
  47533. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47534. var BABYLON;
  47535. (function (BABYLON) {
  47536. /**
  47537. * The PBR material of BJS following the metal roughness convention.
  47538. *
  47539. * This fits to the PBR convention in the GLTF definition:
  47540. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47541. */
  47542. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47543. __extends(PBRMetallicRoughnessMaterial, _super);
  47544. /**
  47545. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47546. *
  47547. * @param name The material name
  47548. * @param scene The scene the material will be use in.
  47549. */
  47550. function PBRMetallicRoughnessMaterial(name, scene) {
  47551. var _this = _super.call(this, name, scene) || this;
  47552. _this._useRoughnessFromMetallicTextureAlpha = false;
  47553. _this._useRoughnessFromMetallicTextureGreen = true;
  47554. _this._useMetallnessFromMetallicTextureBlue = true;
  47555. _this.metallic = 1.0;
  47556. _this.roughness = 1.0;
  47557. return _this;
  47558. }
  47559. /**
  47560. * Return the currrent class name of the material.
  47561. */
  47562. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47563. return "PBRMetallicRoughnessMaterial";
  47564. };
  47565. /**
  47566. * Return the active textures of the material.
  47567. */
  47568. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47569. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47570. if (this.baseTexture) {
  47571. activeTextures.push(this.baseTexture);
  47572. }
  47573. if (this.metallicRoughnessTexture) {
  47574. activeTextures.push(this.metallicRoughnessTexture);
  47575. }
  47576. return activeTextures;
  47577. };
  47578. /**
  47579. * Checks to see if a texture is used in the material.
  47580. * @param texture - Base texture to use.
  47581. * @returns - Boolean specifying if a texture is used in the material.
  47582. */
  47583. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47584. if (_super.prototype.hasTexture.call(this, texture)) {
  47585. return true;
  47586. }
  47587. if (this.baseTexture === texture) {
  47588. return true;
  47589. }
  47590. if (this.metallicRoughnessTexture === texture) {
  47591. return true;
  47592. }
  47593. return false;
  47594. };
  47595. /**
  47596. * Makes a duplicate of the current material.
  47597. * @param name - name to use for the new material.
  47598. */
  47599. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47600. var _this = this;
  47601. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47602. clone.id = name;
  47603. clone.name = name;
  47604. return clone;
  47605. };
  47606. /**
  47607. * Serialize the material to a parsable JSON object.
  47608. */
  47609. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47610. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47611. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47612. return serializationObject;
  47613. };
  47614. /**
  47615. * Parses a JSON object correponding to the serialize function.
  47616. */
  47617. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47618. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47619. };
  47620. __decorate([
  47621. BABYLON.serializeAsColor3(),
  47622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47623. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47624. __decorate([
  47625. BABYLON.serializeAsTexture(),
  47626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47627. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47628. __decorate([
  47629. BABYLON.serialize(),
  47630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47631. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47632. __decorate([
  47633. BABYLON.serialize(),
  47634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47635. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47636. __decorate([
  47637. BABYLON.serializeAsTexture(),
  47638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47639. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47640. return PBRMetallicRoughnessMaterial;
  47641. }(BABYLON.PBRBaseSimpleMaterial));
  47642. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47643. })(BABYLON || (BABYLON = {}));
  47644. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47645. var BABYLON;
  47646. (function (BABYLON) {
  47647. /**
  47648. * The PBR material of BJS following the specular glossiness convention.
  47649. *
  47650. * This fits to the PBR convention in the GLTF definition:
  47651. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47652. */
  47653. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47654. __extends(PBRSpecularGlossinessMaterial, _super);
  47655. /**
  47656. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47657. *
  47658. * @param name The material name
  47659. * @param scene The scene the material will be use in.
  47660. */
  47661. function PBRSpecularGlossinessMaterial(name, scene) {
  47662. var _this = _super.call(this, name, scene) || this;
  47663. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47664. return _this;
  47665. }
  47666. /**
  47667. * Return the currrent class name of the material.
  47668. */
  47669. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47670. return "PBRSpecularGlossinessMaterial";
  47671. };
  47672. /**
  47673. * Return the active textures of the material.
  47674. */
  47675. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47676. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47677. if (this.diffuseTexture) {
  47678. activeTextures.push(this.diffuseTexture);
  47679. }
  47680. if (this.specularGlossinessTexture) {
  47681. activeTextures.push(this.specularGlossinessTexture);
  47682. }
  47683. return activeTextures;
  47684. };
  47685. /**
  47686. * Checks to see if a texture is used in the material.
  47687. * @param texture - Base texture to use.
  47688. * @returns - Boolean specifying if a texture is used in the material.
  47689. */
  47690. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47691. if (_super.prototype.hasTexture.call(this, texture)) {
  47692. return true;
  47693. }
  47694. if (this.diffuseTexture === texture) {
  47695. return true;
  47696. }
  47697. if (this.specularGlossinessTexture === texture) {
  47698. return true;
  47699. }
  47700. return false;
  47701. };
  47702. /**
  47703. * Makes a duplicate of the current material.
  47704. * @param name - name to use for the new material.
  47705. */
  47706. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47707. var _this = this;
  47708. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47709. clone.id = name;
  47710. clone.name = name;
  47711. return clone;
  47712. };
  47713. /**
  47714. * Serialize the material to a parsable JSON object.
  47715. */
  47716. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47717. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47718. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47719. return serializationObject;
  47720. };
  47721. /**
  47722. * Parses a JSON object correponding to the serialize function.
  47723. */
  47724. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47725. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47726. };
  47727. __decorate([
  47728. BABYLON.serializeAsColor3("diffuse"),
  47729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47730. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47731. __decorate([
  47732. BABYLON.serializeAsTexture(),
  47733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47734. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47735. __decorate([
  47736. BABYLON.serializeAsColor3("specular"),
  47737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47738. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47739. __decorate([
  47740. BABYLON.serialize(),
  47741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47742. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47743. __decorate([
  47744. BABYLON.serializeAsTexture(),
  47745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47746. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47747. return PBRSpecularGlossinessMaterial;
  47748. }(BABYLON.PBRBaseSimpleMaterial));
  47749. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47750. })(BABYLON || (BABYLON = {}));
  47751. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47752. var BABYLON;
  47753. (function (BABYLON) {
  47754. /**
  47755. * @ignore
  47756. * This is a list of all the different input types that are available in the application.
  47757. * Fo instance: ArcRotateCameraGamepadInput...
  47758. */
  47759. BABYLON.CameraInputTypes = {};
  47760. /**
  47761. * This represents the input manager used within a camera.
  47762. * It helps dealing with all the different kind of input attached to a camera.
  47763. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47764. */
  47765. var CameraInputsManager = /** @class */ (function () {
  47766. /**
  47767. * Instantiate a new Camera Input Manager.
  47768. * @param camera Defines the camera the input manager blongs to
  47769. */
  47770. function CameraInputsManager(camera) {
  47771. this.attached = {};
  47772. this.camera = camera;
  47773. this.checkInputs = function () { };
  47774. }
  47775. /**
  47776. * Add an input method to a camera
  47777. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47778. * @param input camera input method
  47779. */
  47780. CameraInputsManager.prototype.add = function (input) {
  47781. var type = input.getSimpleName();
  47782. if (this.attached[type]) {
  47783. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47784. return;
  47785. }
  47786. this.attached[type] = input;
  47787. input.camera = this.camera;
  47788. //for checkInputs, we are dynamically creating a function
  47789. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47790. if (input.checkInputs) {
  47791. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47792. }
  47793. if (this.attachedElement) {
  47794. input.attachControl(this.attachedElement);
  47795. }
  47796. };
  47797. /**
  47798. * Remove a specific input method from a camera
  47799. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47800. * @param inputToRemove camera input method
  47801. */
  47802. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47803. for (var cam in this.attached) {
  47804. var input = this.attached[cam];
  47805. if (input === inputToRemove) {
  47806. input.detachControl(this.attachedElement);
  47807. input.camera = null;
  47808. delete this.attached[cam];
  47809. this.rebuildInputCheck();
  47810. }
  47811. }
  47812. };
  47813. /**
  47814. * Remove a specific input type from a camera
  47815. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47816. * @param inputType the type of the input to remove
  47817. */
  47818. CameraInputsManager.prototype.removeByType = function (inputType) {
  47819. for (var cam in this.attached) {
  47820. var input = this.attached[cam];
  47821. if (input.getClassName() === inputType) {
  47822. input.detachControl(this.attachedElement);
  47823. input.camera = null;
  47824. delete this.attached[cam];
  47825. this.rebuildInputCheck();
  47826. }
  47827. }
  47828. };
  47829. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47830. var current = this.checkInputs;
  47831. return function () {
  47832. current();
  47833. fn();
  47834. };
  47835. };
  47836. /**
  47837. * Attach the input controls to the currently attached dom element to listen the events from.
  47838. * @param input Defines the input to attach
  47839. */
  47840. CameraInputsManager.prototype.attachInput = function (input) {
  47841. if (this.attachedElement) {
  47842. input.attachControl(this.attachedElement, this.noPreventDefault);
  47843. }
  47844. };
  47845. /**
  47846. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47847. * @param element Defines the dom element to collect the events from
  47848. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47849. */
  47850. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47851. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47852. if (this.attachedElement) {
  47853. return;
  47854. }
  47855. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47856. this.attachedElement = element;
  47857. this.noPreventDefault = noPreventDefault;
  47858. for (var cam in this.attached) {
  47859. this.attached[cam].attachControl(element, noPreventDefault);
  47860. }
  47861. };
  47862. /**
  47863. * Detach the current manager inputs controls from a specific dom element.
  47864. * @param element Defines the dom element to collect the events from
  47865. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47866. */
  47867. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47868. if (disconnect === void 0) { disconnect = false; }
  47869. if (this.attachedElement !== element) {
  47870. return;
  47871. }
  47872. for (var cam in this.attached) {
  47873. this.attached[cam].detachControl(element);
  47874. if (disconnect) {
  47875. this.attached[cam].camera = null;
  47876. }
  47877. }
  47878. this.attachedElement = null;
  47879. };
  47880. /**
  47881. * Rebuild the dynamic inputCheck function from the current list of
  47882. * defined inputs in the manager.
  47883. */
  47884. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47885. this.checkInputs = function () { };
  47886. for (var cam in this.attached) {
  47887. var input = this.attached[cam];
  47888. if (input.checkInputs) {
  47889. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47890. }
  47891. }
  47892. };
  47893. /**
  47894. * Remove all attached input methods from a camera
  47895. */
  47896. CameraInputsManager.prototype.clear = function () {
  47897. if (this.attachedElement) {
  47898. this.detachElement(this.attachedElement, true);
  47899. }
  47900. this.attached = {};
  47901. this.attachedElement = null;
  47902. this.checkInputs = function () { };
  47903. };
  47904. /**
  47905. * Serialize the current input manager attached to a camera.
  47906. * This ensures than once parsed,
  47907. * the input associated to the camera will be identical to the current ones
  47908. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47909. */
  47910. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47911. var inputs = {};
  47912. for (var cam in this.attached) {
  47913. var input = this.attached[cam];
  47914. var res = BABYLON.SerializationHelper.Serialize(input);
  47915. inputs[input.getClassName()] = res;
  47916. }
  47917. serializedCamera.inputsmgr = inputs;
  47918. };
  47919. /**
  47920. * Parses an input manager serialized JSON to restore the previous list of inputs
  47921. * and states associated to a camera.
  47922. * @param parsedCamera Defines the JSON to parse
  47923. */
  47924. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47925. var parsedInputs = parsedCamera.inputsmgr;
  47926. if (parsedInputs) {
  47927. this.clear();
  47928. for (var n in parsedInputs) {
  47929. var construct = BABYLON.CameraInputTypes[n];
  47930. if (construct) {
  47931. var parsedinput = parsedInputs[n];
  47932. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47933. this.add(input);
  47934. }
  47935. }
  47936. }
  47937. else {
  47938. //2016-03-08 this part is for managing backward compatibility
  47939. for (var n in this.attached) {
  47940. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47941. if (construct) {
  47942. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47943. this.remove(this.attached[n]);
  47944. this.add(input);
  47945. }
  47946. }
  47947. }
  47948. };
  47949. return CameraInputsManager;
  47950. }());
  47951. BABYLON.CameraInputsManager = CameraInputsManager;
  47952. })(BABYLON || (BABYLON = {}));
  47953. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47954. var BABYLON;
  47955. (function (BABYLON) {
  47956. /**
  47957. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47958. * This is the base of the follow, arc rotate cameras and Free camera
  47959. * @see http://doc.babylonjs.com/features/cameras
  47960. */
  47961. var TargetCamera = /** @class */ (function (_super) {
  47962. __extends(TargetCamera, _super);
  47963. /**
  47964. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47965. * This is the base of the follow, arc rotate cameras and Free camera
  47966. * @see http://doc.babylonjs.com/features/cameras
  47967. * @param name Defines the name of the camera in the scene
  47968. * @param position Defines the start position of the camera in the scene
  47969. * @param scene Defines the scene the camera belongs to
  47970. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47971. */
  47972. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47973. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47974. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47975. /**
  47976. * Define the current direction the camera is moving to
  47977. */
  47978. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47979. /**
  47980. * Define the current rotation the camera is rotating to
  47981. */
  47982. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47983. /**
  47984. * Define the current rotation of the camera
  47985. */
  47986. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47987. /**
  47988. * Define the current speed of the camera
  47989. */
  47990. _this.speed = 2.0;
  47991. /**
  47992. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47993. * around all axis.
  47994. */
  47995. _this.noRotationConstraint = false;
  47996. /**
  47997. * Define the current target of the camera as an object or a position.
  47998. */
  47999. _this.lockedTarget = null;
  48000. /** @hidden */
  48001. _this._currentTarget = BABYLON.Vector3.Zero();
  48002. /** @hidden */
  48003. _this._viewMatrix = BABYLON.Matrix.Zero();
  48004. /** @hidden */
  48005. _this._camMatrix = BABYLON.Matrix.Zero();
  48006. /** @hidden */
  48007. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  48008. /** @hidden */
  48009. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  48010. /** @hidden */
  48011. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  48012. /** @hidden */
  48013. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  48014. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  48015. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  48016. _this._defaultUp = BABYLON.Vector3.Up();
  48017. _this._cachedRotationZ = 0;
  48018. _this._cachedQuaternionRotationZ = 0;
  48019. return _this;
  48020. }
  48021. /**
  48022. * Gets the position in front of the camera at a given distance.
  48023. * @param distance The distance from the camera we want the position to be
  48024. * @returns the position
  48025. */
  48026. TargetCamera.prototype.getFrontPosition = function (distance) {
  48027. this.getWorldMatrix();
  48028. var direction = this.getTarget().subtract(this.position);
  48029. direction.normalize();
  48030. direction.scaleInPlace(distance);
  48031. return this.globalPosition.add(direction);
  48032. };
  48033. /** @hidden */
  48034. TargetCamera.prototype._getLockedTargetPosition = function () {
  48035. if (!this.lockedTarget) {
  48036. return null;
  48037. }
  48038. if (this.lockedTarget.absolutePosition) {
  48039. this.lockedTarget.computeWorldMatrix();
  48040. }
  48041. return this.lockedTarget.absolutePosition || this.lockedTarget;
  48042. };
  48043. /**
  48044. * Store current camera state of the camera (fov, position, rotation, etc..)
  48045. * @returns the camera
  48046. */
  48047. TargetCamera.prototype.storeState = function () {
  48048. this._storedPosition = this.position.clone();
  48049. this._storedRotation = this.rotation.clone();
  48050. if (this.rotationQuaternion) {
  48051. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  48052. }
  48053. return _super.prototype.storeState.call(this);
  48054. };
  48055. /**
  48056. * Restored camera state. You must call storeState() first
  48057. * @returns whether it was successful or not
  48058. * @hidden
  48059. */
  48060. TargetCamera.prototype._restoreStateValues = function () {
  48061. if (!_super.prototype._restoreStateValues.call(this)) {
  48062. return false;
  48063. }
  48064. this.position = this._storedPosition.clone();
  48065. this.rotation = this._storedRotation.clone();
  48066. if (this.rotationQuaternion) {
  48067. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  48068. }
  48069. this.cameraDirection.copyFromFloats(0, 0, 0);
  48070. this.cameraRotation.copyFromFloats(0, 0);
  48071. return true;
  48072. };
  48073. /** @hidden */
  48074. TargetCamera.prototype._initCache = function () {
  48075. _super.prototype._initCache.call(this);
  48076. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48077. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48078. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48079. };
  48080. /** @hidden */
  48081. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  48082. if (!ignoreParentClass) {
  48083. _super.prototype._updateCache.call(this);
  48084. }
  48085. var lockedTargetPosition = this._getLockedTargetPosition();
  48086. if (!lockedTargetPosition) {
  48087. this._cache.lockedTarget = null;
  48088. }
  48089. else {
  48090. if (!this._cache.lockedTarget) {
  48091. this._cache.lockedTarget = lockedTargetPosition.clone();
  48092. }
  48093. else {
  48094. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  48095. }
  48096. }
  48097. this._cache.rotation.copyFrom(this.rotation);
  48098. if (this.rotationQuaternion) {
  48099. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48100. }
  48101. };
  48102. // Synchronized
  48103. /** @hidden */
  48104. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  48105. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  48106. return false;
  48107. }
  48108. var lockedTargetPosition = this._getLockedTargetPosition();
  48109. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48110. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48111. };
  48112. // Methods
  48113. /** @hidden */
  48114. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48115. var engine = this.getEngine();
  48116. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48117. };
  48118. // Target
  48119. /** @hidden */
  48120. TargetCamera.prototype.setTarget = function (target) {
  48121. this.upVector.normalize();
  48122. if (this.position.z === target.z) {
  48123. this.position.z += BABYLON.Epsilon;
  48124. }
  48125. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48126. this._camMatrix.invert();
  48127. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48128. var vDir = target.subtract(this.position);
  48129. if (vDir.x >= 0.0) {
  48130. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48131. }
  48132. else {
  48133. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48134. }
  48135. this.rotation.z = 0;
  48136. if (isNaN(this.rotation.x)) {
  48137. this.rotation.x = 0;
  48138. }
  48139. if (isNaN(this.rotation.y)) {
  48140. this.rotation.y = 0;
  48141. }
  48142. if (isNaN(this.rotation.z)) {
  48143. this.rotation.z = 0;
  48144. }
  48145. if (this.rotationQuaternion) {
  48146. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48147. }
  48148. };
  48149. /**
  48150. * Return the current target position of the camera. This value is expressed in local space.
  48151. * @returns the target position
  48152. */
  48153. TargetCamera.prototype.getTarget = function () {
  48154. return this._currentTarget;
  48155. };
  48156. /** @hidden */
  48157. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48158. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48159. };
  48160. /** @hidden */
  48161. TargetCamera.prototype._updatePosition = function () {
  48162. if (this.parent) {
  48163. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48164. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48165. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48166. return;
  48167. }
  48168. this.position.addInPlace(this.cameraDirection);
  48169. };
  48170. /** @hidden */
  48171. TargetCamera.prototype._checkInputs = function () {
  48172. var needToMove = this._decideIfNeedsToMove();
  48173. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48174. // Move
  48175. if (needToMove) {
  48176. this._updatePosition();
  48177. }
  48178. // Rotate
  48179. if (needToRotate) {
  48180. this.rotation.x += this.cameraRotation.x;
  48181. this.rotation.y += this.cameraRotation.y;
  48182. //rotate, if quaternion is set and rotation was used
  48183. if (this.rotationQuaternion) {
  48184. var len = this.rotation.lengthSquared();
  48185. if (len) {
  48186. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48187. }
  48188. }
  48189. if (!this.noRotationConstraint) {
  48190. var limit = (Math.PI / 2) * 0.95;
  48191. if (this.rotation.x > limit) {
  48192. this.rotation.x = limit;
  48193. }
  48194. if (this.rotation.x < -limit) {
  48195. this.rotation.x = -limit;
  48196. }
  48197. }
  48198. }
  48199. // Inertia
  48200. if (needToMove) {
  48201. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48202. this.cameraDirection.x = 0;
  48203. }
  48204. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48205. this.cameraDirection.y = 0;
  48206. }
  48207. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48208. this.cameraDirection.z = 0;
  48209. }
  48210. this.cameraDirection.scaleInPlace(this.inertia);
  48211. }
  48212. if (needToRotate) {
  48213. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48214. this.cameraRotation.x = 0;
  48215. }
  48216. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48217. this.cameraRotation.y = 0;
  48218. }
  48219. this.cameraRotation.scaleInPlace(this.inertia);
  48220. }
  48221. _super.prototype._checkInputs.call(this);
  48222. };
  48223. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48224. if (this.rotationQuaternion) {
  48225. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48226. }
  48227. else {
  48228. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48229. }
  48230. };
  48231. /**
  48232. * 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)
  48233. * @returns the current camera
  48234. */
  48235. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48236. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48237. return this;
  48238. };
  48239. /** @hidden */
  48240. TargetCamera.prototype._getViewMatrix = function () {
  48241. if (this.lockedTarget) {
  48242. this.setTarget(this._getLockedTargetPosition());
  48243. }
  48244. // Compute
  48245. this._updateCameraRotationMatrix();
  48246. // Apply the changed rotation to the upVector
  48247. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48248. this._rotateUpVectorWithCameraRotationMatrix();
  48249. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48250. }
  48251. else if (this._cachedRotationZ != this.rotation.z) {
  48252. this._rotateUpVectorWithCameraRotationMatrix();
  48253. this._cachedRotationZ = this.rotation.z;
  48254. }
  48255. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48256. // Computing target and final matrix
  48257. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48258. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48259. return this._viewMatrix;
  48260. };
  48261. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48262. if (this.parent) {
  48263. var parentWorldMatrix = this.parent.getWorldMatrix();
  48264. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48265. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48266. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48267. this._markSyncedWithParent();
  48268. }
  48269. else {
  48270. this._globalPosition.copyFrom(position);
  48271. this._globalCurrentTarget.copyFrom(target);
  48272. this._globalCurrentUpVector.copyFrom(up);
  48273. }
  48274. if (this.getScene().useRightHandedSystem) {
  48275. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48276. }
  48277. else {
  48278. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48279. }
  48280. };
  48281. /**
  48282. * @hidden
  48283. */
  48284. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48285. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48286. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48287. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48288. if (!this.rotationQuaternion) {
  48289. this.rotationQuaternion = new BABYLON.Quaternion();
  48290. }
  48291. rigCamera._cameraRigParams = {};
  48292. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48293. }
  48294. return rigCamera;
  48295. }
  48296. return null;
  48297. };
  48298. /**
  48299. * @hidden
  48300. */
  48301. TargetCamera.prototype._updateRigCameras = function () {
  48302. var camLeft = this._rigCameras[0];
  48303. var camRight = this._rigCameras[1];
  48304. switch (this.cameraRigMode) {
  48305. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48306. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48307. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48308. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48309. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48310. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48311. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48312. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48313. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48314. camLeft.setTarget(this.getTarget());
  48315. camRight.setTarget(this.getTarget());
  48316. break;
  48317. case BABYLON.Camera.RIG_MODE_VR:
  48318. if (camLeft.rotationQuaternion) {
  48319. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48320. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48321. }
  48322. else {
  48323. camLeft.rotation.copyFrom(this.rotation);
  48324. camRight.rotation.copyFrom(this.rotation);
  48325. }
  48326. camLeft.position.copyFrom(this.position);
  48327. camRight.position.copyFrom(this.position);
  48328. break;
  48329. }
  48330. _super.prototype._updateRigCameras.call(this);
  48331. };
  48332. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48333. if (!this._rigCamTransformMatrix) {
  48334. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48335. }
  48336. var target = this.getTarget();
  48337. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48338. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48339. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48340. };
  48341. /**
  48342. * Gets the current object class name.
  48343. * @return the class name
  48344. */
  48345. TargetCamera.prototype.getClassName = function () {
  48346. return "TargetCamera";
  48347. };
  48348. __decorate([
  48349. BABYLON.serializeAsVector3()
  48350. ], TargetCamera.prototype, "rotation", void 0);
  48351. __decorate([
  48352. BABYLON.serialize()
  48353. ], TargetCamera.prototype, "speed", void 0);
  48354. __decorate([
  48355. BABYLON.serializeAsMeshReference("lockedTargetId")
  48356. ], TargetCamera.prototype, "lockedTarget", void 0);
  48357. return TargetCamera;
  48358. }(BABYLON.Camera));
  48359. BABYLON.TargetCamera = TargetCamera;
  48360. })(BABYLON || (BABYLON = {}));
  48361. //# sourceMappingURL=babylon.targetCamera.js.map
  48362. var BABYLON;
  48363. (function (BABYLON) {
  48364. /**
  48365. * Manage the mouse inputs to control the movement of a free camera.
  48366. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48367. */
  48368. var FreeCameraMouseInput = /** @class */ (function () {
  48369. /**
  48370. * Manage the mouse inputs to control the movement of a free camera.
  48371. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48372. * @param touchEnabled Defines if touch is enabled or not
  48373. */
  48374. function FreeCameraMouseInput(
  48375. /**
  48376. * Define if touch is enabled in the mouse input
  48377. */
  48378. touchEnabled) {
  48379. if (touchEnabled === void 0) { touchEnabled = true; }
  48380. this.touchEnabled = touchEnabled;
  48381. /**
  48382. * Defines the buttons associated with the input to handle camera move.
  48383. */
  48384. this.buttons = [0, 1, 2];
  48385. /**
  48386. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48387. */
  48388. this.angularSensibility = 2000.0;
  48389. this.previousPosition = null;
  48390. }
  48391. /**
  48392. * Attach the input controls to a specific dom element to get the input from.
  48393. * @param element Defines the element the controls should be listened from
  48394. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48395. */
  48396. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48397. var _this = this;
  48398. var engine = this.camera.getEngine();
  48399. if (!this._pointerInput) {
  48400. this._pointerInput = function (p, s) {
  48401. var evt = p.event;
  48402. if (engine.isInVRExclusivePointerMode) {
  48403. return;
  48404. }
  48405. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48406. return;
  48407. }
  48408. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48409. return;
  48410. }
  48411. var srcElement = (evt.srcElement || evt.target);
  48412. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48413. try {
  48414. srcElement.setPointerCapture(evt.pointerId);
  48415. }
  48416. catch (e) {
  48417. //Nothing to do with the error. Execution will continue.
  48418. }
  48419. _this.previousPosition = {
  48420. x: evt.clientX,
  48421. y: evt.clientY
  48422. };
  48423. if (!noPreventDefault) {
  48424. evt.preventDefault();
  48425. element.focus();
  48426. }
  48427. }
  48428. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48429. try {
  48430. srcElement.releasePointerCapture(evt.pointerId);
  48431. }
  48432. catch (e) {
  48433. //Nothing to do with the error.
  48434. }
  48435. _this.previousPosition = null;
  48436. if (!noPreventDefault) {
  48437. evt.preventDefault();
  48438. }
  48439. }
  48440. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48441. if (!_this.previousPosition || engine.isPointerLock) {
  48442. return;
  48443. }
  48444. var offsetX = evt.clientX - _this.previousPosition.x;
  48445. if (_this.camera.getScene().useRightHandedSystem) {
  48446. offsetX *= -1;
  48447. }
  48448. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48449. offsetX *= -1;
  48450. }
  48451. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48452. var offsetY = evt.clientY - _this.previousPosition.y;
  48453. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48454. _this.previousPosition = {
  48455. x: evt.clientX,
  48456. y: evt.clientY
  48457. };
  48458. if (!noPreventDefault) {
  48459. evt.preventDefault();
  48460. }
  48461. }
  48462. };
  48463. }
  48464. this._onMouseMove = function (evt) {
  48465. if (!engine.isPointerLock) {
  48466. return;
  48467. }
  48468. if (engine.isInVRExclusivePointerMode) {
  48469. return;
  48470. }
  48471. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48472. if (_this.camera.getScene().useRightHandedSystem) {
  48473. offsetX *= -1;
  48474. }
  48475. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48476. offsetX *= -1;
  48477. }
  48478. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48479. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48480. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48481. _this.previousPosition = null;
  48482. if (!noPreventDefault) {
  48483. evt.preventDefault();
  48484. }
  48485. };
  48486. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48487. element.addEventListener("mousemove", this._onMouseMove, false);
  48488. };
  48489. /**
  48490. * Detach the current controls from the specified dom element.
  48491. * @param element Defines the element to stop listening the inputs from
  48492. */
  48493. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48494. if (this._observer && element) {
  48495. this.camera.getScene().onPointerObservable.remove(this._observer);
  48496. if (this._onMouseMove) {
  48497. element.removeEventListener("mousemove", this._onMouseMove);
  48498. }
  48499. this._observer = null;
  48500. this._onMouseMove = null;
  48501. this.previousPosition = null;
  48502. }
  48503. };
  48504. /**
  48505. * Gets the class name of the current intput.
  48506. * @returns the class name
  48507. */
  48508. FreeCameraMouseInput.prototype.getClassName = function () {
  48509. return "FreeCameraMouseInput";
  48510. };
  48511. /**
  48512. * Get the friendly name associated with the input class.
  48513. * @returns the input friendly name
  48514. */
  48515. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48516. return "mouse";
  48517. };
  48518. __decorate([
  48519. BABYLON.serialize()
  48520. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48521. __decorate([
  48522. BABYLON.serialize()
  48523. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48524. return FreeCameraMouseInput;
  48525. }());
  48526. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48527. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48528. })(BABYLON || (BABYLON = {}));
  48529. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48530. var BABYLON;
  48531. (function (BABYLON) {
  48532. /**
  48533. * Manage the keyboard inputs to control the movement of a free camera.
  48534. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48535. */
  48536. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48537. function FreeCameraKeyboardMoveInput() {
  48538. /**
  48539. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48540. */
  48541. this.keysUp = [38];
  48542. /**
  48543. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48544. */
  48545. this.keysDown = [40];
  48546. /**
  48547. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48548. */
  48549. this.keysLeft = [37];
  48550. /**
  48551. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48552. */
  48553. this.keysRight = [39];
  48554. this._keys = new Array();
  48555. }
  48556. /**
  48557. * Attach the input controls to a specific dom element to get the input from.
  48558. * @param element Defines the element the controls should be listened from
  48559. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48560. */
  48561. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48562. var _this = this;
  48563. if (this._onCanvasBlurObserver) {
  48564. return;
  48565. }
  48566. this._scene = this.camera.getScene();
  48567. this._engine = this._scene.getEngine();
  48568. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48569. _this._keys = [];
  48570. });
  48571. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48572. var evt = info.event;
  48573. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48574. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48575. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48576. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48577. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48578. var index = _this._keys.indexOf(evt.keyCode);
  48579. if (index === -1) {
  48580. _this._keys.push(evt.keyCode);
  48581. }
  48582. if (!noPreventDefault) {
  48583. evt.preventDefault();
  48584. }
  48585. }
  48586. }
  48587. else {
  48588. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48589. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48590. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48591. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48592. var index = _this._keys.indexOf(evt.keyCode);
  48593. if (index >= 0) {
  48594. _this._keys.splice(index, 1);
  48595. }
  48596. if (!noPreventDefault) {
  48597. evt.preventDefault();
  48598. }
  48599. }
  48600. }
  48601. });
  48602. };
  48603. /**
  48604. * Detach the current controls from the specified dom element.
  48605. * @param element Defines the element to stop listening the inputs from
  48606. */
  48607. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48608. if (this._scene) {
  48609. if (this._onKeyboardObserver) {
  48610. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48611. }
  48612. if (this._onCanvasBlurObserver) {
  48613. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48614. }
  48615. this._onKeyboardObserver = null;
  48616. this._onCanvasBlurObserver = null;
  48617. }
  48618. this._keys = [];
  48619. };
  48620. /**
  48621. * Update the current camera state depending on the inputs that have been used this frame.
  48622. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48623. */
  48624. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48625. if (this._onKeyboardObserver) {
  48626. var camera = this.camera;
  48627. // Keyboard
  48628. for (var index = 0; index < this._keys.length; index++) {
  48629. var keyCode = this._keys[index];
  48630. var speed = camera._computeLocalCameraSpeed();
  48631. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48632. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48633. }
  48634. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48635. camera._localDirection.copyFromFloats(0, 0, speed);
  48636. }
  48637. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48638. camera._localDirection.copyFromFloats(speed, 0, 0);
  48639. }
  48640. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48641. camera._localDirection.copyFromFloats(0, 0, -speed);
  48642. }
  48643. if (camera.getScene().useRightHandedSystem) {
  48644. camera._localDirection.z *= -1;
  48645. }
  48646. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48647. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48648. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48649. }
  48650. }
  48651. };
  48652. /**
  48653. * Gets the class name of the current intput.
  48654. * @returns the class name
  48655. */
  48656. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48657. return "FreeCameraKeyboardMoveInput";
  48658. };
  48659. /** @hidden */
  48660. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48661. this._keys = [];
  48662. };
  48663. /**
  48664. * Get the friendly name associated with the input class.
  48665. * @returns the input friendly name
  48666. */
  48667. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48668. return "keyboard";
  48669. };
  48670. __decorate([
  48671. BABYLON.serialize()
  48672. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48673. __decorate([
  48674. BABYLON.serialize()
  48675. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48676. __decorate([
  48677. BABYLON.serialize()
  48678. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48679. __decorate([
  48680. BABYLON.serialize()
  48681. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48682. return FreeCameraKeyboardMoveInput;
  48683. }());
  48684. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48685. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48686. })(BABYLON || (BABYLON = {}));
  48687. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48688. var BABYLON;
  48689. (function (BABYLON) {
  48690. /**
  48691. * Default Inputs manager for the FreeCamera.
  48692. * It groups all the default supported inputs for ease of use.
  48693. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48694. */
  48695. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48696. __extends(FreeCameraInputsManager, _super);
  48697. /**
  48698. * Instantiates a new FreeCameraInputsManager.
  48699. * @param camera Defines the camera the inputs belong to
  48700. */
  48701. function FreeCameraInputsManager(camera) {
  48702. return _super.call(this, camera) || this;
  48703. }
  48704. /**
  48705. * Add keyboard input support to the input manager.
  48706. * @returns the current input manager
  48707. */
  48708. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48709. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48710. return this;
  48711. };
  48712. /**
  48713. * Add mouse input support to the input manager.
  48714. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  48715. * @returns the current input manager
  48716. */
  48717. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48718. if (touchEnabled === void 0) { touchEnabled = true; }
  48719. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48720. return this;
  48721. };
  48722. /**
  48723. * Add orientation input support to the input manager.
  48724. * @returns the current input manager
  48725. */
  48726. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48727. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48728. return this;
  48729. };
  48730. /**
  48731. * Add touch input support to the input manager.
  48732. * @returns the current input manager
  48733. */
  48734. FreeCameraInputsManager.prototype.addTouch = function () {
  48735. this.add(new BABYLON.FreeCameraTouchInput());
  48736. return this;
  48737. };
  48738. /**
  48739. * Add virtual joystick input support to the input manager.
  48740. * @returns the current input manager
  48741. */
  48742. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48743. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48744. return this;
  48745. };
  48746. return FreeCameraInputsManager;
  48747. }(BABYLON.CameraInputsManager));
  48748. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48749. })(BABYLON || (BABYLON = {}));
  48750. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48751. var BABYLON;
  48752. (function (BABYLON) {
  48753. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48754. // Forcing to use the Universal camera
  48755. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48756. });
  48757. /**
  48758. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48759. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48760. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48761. */
  48762. var FreeCamera = /** @class */ (function (_super) {
  48763. __extends(FreeCamera, _super);
  48764. /**
  48765. * Instantiates a Free Camera.
  48766. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48767. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48768. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48769. * @param name Define the name of the camera in the scene
  48770. * @param position Define the start position of the camera in the scene
  48771. * @param scene Define the scene the camera belongs to
  48772. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48773. */
  48774. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48775. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48776. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48777. /**
  48778. * Define the collision ellipsoid of the camera.
  48779. * This is helpful to simulate a camera body like the player body around the camera
  48780. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48781. */
  48782. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48783. /**
  48784. * Define an offset for the position of the ellipsoid around the camera.
  48785. * This can be helpful to determine the center of the body near the gravity center of the body
  48786. * instead of its head.
  48787. */
  48788. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48789. /**
  48790. * Enable or disable collisions of the camera with the rest of the scene objects.
  48791. */
  48792. _this.checkCollisions = false;
  48793. /**
  48794. * Enable or disable gravity on the camera.
  48795. */
  48796. _this.applyGravity = false;
  48797. _this._needMoveForGravity = false;
  48798. _this._oldPosition = BABYLON.Vector3.Zero();
  48799. _this._diffPosition = BABYLON.Vector3.Zero();
  48800. _this._newPosition = BABYLON.Vector3.Zero();
  48801. // Collisions
  48802. _this._collisionMask = -1;
  48803. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48804. if (collidedMesh === void 0) { collidedMesh = null; }
  48805. //TODO move this to the collision coordinator!
  48806. if (_this.getScene().workerCollisions) {
  48807. newPosition.multiplyInPlace(_this._collider._radius);
  48808. }
  48809. var updatePosition = function (newPos) {
  48810. _this._newPosition.copyFrom(newPos);
  48811. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48812. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48813. _this.position.addInPlace(_this._diffPosition);
  48814. if (_this.onCollide && collidedMesh) {
  48815. _this.onCollide(collidedMesh);
  48816. }
  48817. }
  48818. };
  48819. updatePosition(newPosition);
  48820. };
  48821. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48822. _this.inputs.addKeyboard().addMouse();
  48823. return _this;
  48824. }
  48825. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48826. /**
  48827. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48828. * Higher values reduce sensitivity.
  48829. */
  48830. get: function () {
  48831. var mouse = this.inputs.attached["mouse"];
  48832. if (mouse) {
  48833. return mouse.angularSensibility;
  48834. }
  48835. return 0;
  48836. },
  48837. /**
  48838. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48839. * Higher values reduce sensitivity.
  48840. */
  48841. set: function (value) {
  48842. var mouse = this.inputs.attached["mouse"];
  48843. if (mouse) {
  48844. mouse.angularSensibility = value;
  48845. }
  48846. },
  48847. enumerable: true,
  48848. configurable: true
  48849. });
  48850. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48851. /**
  48852. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48853. */
  48854. get: function () {
  48855. var keyboard = this.inputs.attached["keyboard"];
  48856. if (keyboard) {
  48857. return keyboard.keysUp;
  48858. }
  48859. return [];
  48860. },
  48861. set: function (value) {
  48862. var keyboard = this.inputs.attached["keyboard"];
  48863. if (keyboard) {
  48864. keyboard.keysUp = value;
  48865. }
  48866. },
  48867. enumerable: true,
  48868. configurable: true
  48869. });
  48870. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48871. /**
  48872. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48873. */
  48874. get: function () {
  48875. var keyboard = this.inputs.attached["keyboard"];
  48876. if (keyboard) {
  48877. return keyboard.keysDown;
  48878. }
  48879. return [];
  48880. },
  48881. set: function (value) {
  48882. var keyboard = this.inputs.attached["keyboard"];
  48883. if (keyboard) {
  48884. keyboard.keysDown = value;
  48885. }
  48886. },
  48887. enumerable: true,
  48888. configurable: true
  48889. });
  48890. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48891. /**
  48892. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48893. */
  48894. get: function () {
  48895. var keyboard = this.inputs.attached["keyboard"];
  48896. if (keyboard) {
  48897. return keyboard.keysLeft;
  48898. }
  48899. return [];
  48900. },
  48901. set: function (value) {
  48902. var keyboard = this.inputs.attached["keyboard"];
  48903. if (keyboard) {
  48904. keyboard.keysLeft = value;
  48905. }
  48906. },
  48907. enumerable: true,
  48908. configurable: true
  48909. });
  48910. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48911. /**
  48912. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48913. */
  48914. get: function () {
  48915. var keyboard = this.inputs.attached["keyboard"];
  48916. if (keyboard) {
  48917. return keyboard.keysRight;
  48918. }
  48919. return [];
  48920. },
  48921. set: function (value) {
  48922. var keyboard = this.inputs.attached["keyboard"];
  48923. if (keyboard) {
  48924. keyboard.keysRight = value;
  48925. }
  48926. },
  48927. enumerable: true,
  48928. configurable: true
  48929. });
  48930. /**
  48931. * Attached controls to the current camera.
  48932. * @param element Defines the element the controls should be listened from
  48933. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48934. */
  48935. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48936. this.inputs.attachElement(element, noPreventDefault);
  48937. };
  48938. /**
  48939. * Detach the current controls from the camera.
  48940. * The camera will stop reacting to inputs.
  48941. * @param element Defines the element to stop listening the inputs from
  48942. */
  48943. FreeCamera.prototype.detachControl = function (element) {
  48944. this.inputs.detachElement(element);
  48945. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48946. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48947. };
  48948. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48949. /**
  48950. * Define a collision mask to limit the list of object the camera can collide with
  48951. */
  48952. get: function () {
  48953. return this._collisionMask;
  48954. },
  48955. set: function (mask) {
  48956. this._collisionMask = !isNaN(mask) ? mask : -1;
  48957. },
  48958. enumerable: true,
  48959. configurable: true
  48960. });
  48961. /** @hidden */
  48962. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48963. var globalPosition;
  48964. if (this.parent) {
  48965. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48966. }
  48967. else {
  48968. globalPosition = this.position;
  48969. }
  48970. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48971. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48972. if (!this._collider) {
  48973. this._collider = new BABYLON.Collider();
  48974. }
  48975. this._collider._radius = this.ellipsoid;
  48976. this._collider.collisionMask = this._collisionMask;
  48977. //no need for clone, as long as gravity is not on.
  48978. var actualDisplacement = displacement;
  48979. //add gravity to the direction to prevent the dual-collision checking
  48980. if (this.applyGravity) {
  48981. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48982. actualDisplacement = displacement.add(this.getScene().gravity);
  48983. }
  48984. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48985. };
  48986. /** @hidden */
  48987. FreeCamera.prototype._checkInputs = function () {
  48988. if (!this._localDirection) {
  48989. this._localDirection = BABYLON.Vector3.Zero();
  48990. this._transformedDirection = BABYLON.Vector3.Zero();
  48991. }
  48992. this.inputs.checkInputs();
  48993. _super.prototype._checkInputs.call(this);
  48994. };
  48995. /** @hidden */
  48996. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48997. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48998. };
  48999. /** @hidden */
  49000. FreeCamera.prototype._updatePosition = function () {
  49001. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  49002. this._collideWithWorld(this.cameraDirection);
  49003. }
  49004. else {
  49005. _super.prototype._updatePosition.call(this);
  49006. }
  49007. };
  49008. /**
  49009. * Destroy the camera and release the current resources hold by it.
  49010. */
  49011. FreeCamera.prototype.dispose = function () {
  49012. this.inputs.clear();
  49013. _super.prototype.dispose.call(this);
  49014. };
  49015. /**
  49016. * Gets the current object class name.
  49017. * @return the class name
  49018. */
  49019. FreeCamera.prototype.getClassName = function () {
  49020. return "FreeCamera";
  49021. };
  49022. __decorate([
  49023. BABYLON.serializeAsVector3()
  49024. ], FreeCamera.prototype, "ellipsoid", void 0);
  49025. __decorate([
  49026. BABYLON.serializeAsVector3()
  49027. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  49028. __decorate([
  49029. BABYLON.serialize()
  49030. ], FreeCamera.prototype, "checkCollisions", void 0);
  49031. __decorate([
  49032. BABYLON.serialize()
  49033. ], FreeCamera.prototype, "applyGravity", void 0);
  49034. return FreeCamera;
  49035. }(BABYLON.TargetCamera));
  49036. BABYLON.FreeCamera = FreeCamera;
  49037. })(BABYLON || (BABYLON = {}));
  49038. //# sourceMappingURL=babylon.freeCamera.js.map
  49039. var BABYLON;
  49040. (function (BABYLON) {
  49041. /**
  49042. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  49043. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49044. */
  49045. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  49046. function ArcRotateCameraKeyboardMoveInput() {
  49047. /**
  49048. * Defines the list of key codes associated with the up action (increase alpha)
  49049. */
  49050. this.keysUp = [38];
  49051. /**
  49052. * Defines the list of key codes associated with the down action (decrease alpha)
  49053. */
  49054. this.keysDown = [40];
  49055. /**
  49056. * Defines the list of key codes associated with the left action (increase beta)
  49057. */
  49058. this.keysLeft = [37];
  49059. /**
  49060. * Defines the list of key codes associated with the right action (decrease beta)
  49061. */
  49062. this.keysRight = [39];
  49063. /**
  49064. * Defines the list of key codes associated with the reset action.
  49065. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  49066. */
  49067. this.keysReset = [220];
  49068. /**
  49069. * Defines the panning sensibility of the inputs.
  49070. * (How fast is the camera paning)
  49071. */
  49072. this.panningSensibility = 50.0;
  49073. /**
  49074. * Defines the zooming sensibility of the inputs.
  49075. * (How fast is the camera zooming)
  49076. */
  49077. this.zoomingSensibility = 25.0;
  49078. /**
  49079. * Defines wether maintaining the alt key down switch the movement mode from
  49080. * orientation to zoom.
  49081. */
  49082. this.useAltToZoom = true;
  49083. /**
  49084. * Rotation speed of the camera
  49085. */
  49086. this.angularSpeed = 0.01;
  49087. this._keys = new Array();
  49088. }
  49089. /**
  49090. * Attach the input controls to a specific dom element to get the input from.
  49091. * @param element Defines the element the controls should be listened from
  49092. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49093. */
  49094. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  49095. var _this = this;
  49096. if (this._onCanvasBlurObserver) {
  49097. return;
  49098. }
  49099. this._scene = this.camera.getScene();
  49100. this._engine = this._scene.getEngine();
  49101. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49102. _this._keys = [];
  49103. });
  49104. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49105. var evt = info.event;
  49106. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49107. _this._ctrlPressed = evt.ctrlKey;
  49108. _this._altPressed = evt.altKey;
  49109. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49110. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49111. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49112. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  49113. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  49114. var index = _this._keys.indexOf(evt.keyCode);
  49115. if (index === -1) {
  49116. _this._keys.push(evt.keyCode);
  49117. }
  49118. if (evt.preventDefault) {
  49119. if (!noPreventDefault) {
  49120. evt.preventDefault();
  49121. }
  49122. }
  49123. }
  49124. }
  49125. else {
  49126. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49127. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49128. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49129. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  49130. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  49131. var index = _this._keys.indexOf(evt.keyCode);
  49132. if (index >= 0) {
  49133. _this._keys.splice(index, 1);
  49134. }
  49135. if (evt.preventDefault) {
  49136. if (!noPreventDefault) {
  49137. evt.preventDefault();
  49138. }
  49139. }
  49140. }
  49141. }
  49142. });
  49143. };
  49144. /**
  49145. * Detach the current controls from the specified dom element.
  49146. * @param element Defines the element to stop listening the inputs from
  49147. */
  49148. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  49149. if (this._scene) {
  49150. if (this._onKeyboardObserver) {
  49151. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49152. }
  49153. if (this._onCanvasBlurObserver) {
  49154. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49155. }
  49156. this._onKeyboardObserver = null;
  49157. this._onCanvasBlurObserver = null;
  49158. }
  49159. this._keys = [];
  49160. };
  49161. /**
  49162. * Update the current camera state depending on the inputs that have been used this frame.
  49163. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49164. */
  49165. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  49166. if (this._onKeyboardObserver) {
  49167. var camera = this.camera;
  49168. for (var index = 0; index < this._keys.length; index++) {
  49169. var keyCode = this._keys[index];
  49170. if (this.keysLeft.indexOf(keyCode) !== -1) {
  49171. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49172. camera.inertialPanningX -= 1 / this.panningSensibility;
  49173. }
  49174. else {
  49175. camera.inertialAlphaOffset -= this.angularSpeed;
  49176. }
  49177. }
  49178. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49179. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49180. camera.inertialPanningY += 1 / this.panningSensibility;
  49181. }
  49182. else if (this._altPressed && this.useAltToZoom) {
  49183. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  49184. }
  49185. else {
  49186. camera.inertialBetaOffset -= this.angularSpeed;
  49187. }
  49188. }
  49189. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49190. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49191. camera.inertialPanningX += 1 / this.panningSensibility;
  49192. }
  49193. else {
  49194. camera.inertialAlphaOffset += this.angularSpeed;
  49195. }
  49196. }
  49197. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49198. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49199. camera.inertialPanningY -= 1 / this.panningSensibility;
  49200. }
  49201. else if (this._altPressed && this.useAltToZoom) {
  49202. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  49203. }
  49204. else {
  49205. camera.inertialBetaOffset += this.angularSpeed;
  49206. }
  49207. }
  49208. else if (this.keysReset.indexOf(keyCode) !== -1) {
  49209. if (camera.useInputToRestoreState) {
  49210. camera.restoreState();
  49211. }
  49212. }
  49213. }
  49214. }
  49215. };
  49216. /**
  49217. * Gets the class name of the current intput.
  49218. * @returns the class name
  49219. */
  49220. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  49221. return "ArcRotateCameraKeyboardMoveInput";
  49222. };
  49223. /**
  49224. * Get the friendly name associated with the input class.
  49225. * @returns the input friendly name
  49226. */
  49227. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49228. return "keyboard";
  49229. };
  49230. __decorate([
  49231. BABYLON.serialize()
  49232. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49233. __decorate([
  49234. BABYLON.serialize()
  49235. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49236. __decorate([
  49237. BABYLON.serialize()
  49238. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49239. __decorate([
  49240. BABYLON.serialize()
  49241. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49242. __decorate([
  49243. BABYLON.serialize()
  49244. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  49245. __decorate([
  49246. BABYLON.serialize()
  49247. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  49248. __decorate([
  49249. BABYLON.serialize()
  49250. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  49251. __decorate([
  49252. BABYLON.serialize()
  49253. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  49254. __decorate([
  49255. BABYLON.serialize()
  49256. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  49257. return ArcRotateCameraKeyboardMoveInput;
  49258. }());
  49259. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  49260. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  49261. })(BABYLON || (BABYLON = {}));
  49262. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  49263. var BABYLON;
  49264. (function (BABYLON) {
  49265. /**
  49266. * Manage the mouse wheel inputs to control an arc rotate camera.
  49267. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49268. */
  49269. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  49270. function ArcRotateCameraMouseWheelInput() {
  49271. /**
  49272. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49273. */
  49274. this.wheelPrecision = 3.0;
  49275. /**
  49276. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  49277. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  49278. */
  49279. this.wheelDeltaPercentage = 0;
  49280. }
  49281. /**
  49282. * Attach the input controls to a specific dom element to get the input from.
  49283. * @param element Defines the element the controls should be listened from
  49284. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49285. */
  49286. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  49287. var _this = this;
  49288. this._wheel = function (p, s) {
  49289. //sanity check - this should be a PointerWheel event.
  49290. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  49291. return;
  49292. }
  49293. var event = p.event;
  49294. var delta = 0;
  49295. if (event.wheelDelta) {
  49296. if (_this.wheelDeltaPercentage) {
  49297. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  49298. if (event.wheelDelta > 0) {
  49299. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  49300. }
  49301. else {
  49302. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  49303. }
  49304. }
  49305. else {
  49306. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  49307. }
  49308. }
  49309. else if (event.detail) {
  49310. delta = -event.detail / _this.wheelPrecision;
  49311. }
  49312. if (delta) {
  49313. _this.camera.inertialRadiusOffset += delta;
  49314. }
  49315. if (event.preventDefault) {
  49316. if (!noPreventDefault) {
  49317. event.preventDefault();
  49318. }
  49319. }
  49320. };
  49321. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  49322. };
  49323. /**
  49324. * Detach the current controls from the specified dom element.
  49325. * @param element Defines the element to stop listening the inputs from
  49326. */
  49327. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  49328. if (this._observer && element) {
  49329. this.camera.getScene().onPointerObservable.remove(this._observer);
  49330. this._observer = null;
  49331. this._wheel = null;
  49332. }
  49333. };
  49334. /**
  49335. * Gets the class name of the current intput.
  49336. * @returns the class name
  49337. */
  49338. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  49339. return "ArcRotateCameraMouseWheelInput";
  49340. };
  49341. /**
  49342. * Get the friendly name associated with the input class.
  49343. * @returns the input friendly name
  49344. */
  49345. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  49346. return "mousewheel";
  49347. };
  49348. __decorate([
  49349. BABYLON.serialize()
  49350. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  49351. __decorate([
  49352. BABYLON.serialize()
  49353. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  49354. return ArcRotateCameraMouseWheelInput;
  49355. }());
  49356. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  49357. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  49358. })(BABYLON || (BABYLON = {}));
  49359. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  49360. var BABYLON;
  49361. (function (BABYLON) {
  49362. /**
  49363. * Manage the pointers inputs to control an arc rotate camera.
  49364. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49365. */
  49366. var ArcRotateCameraPointersInput = /** @class */ (function () {
  49367. function ArcRotateCameraPointersInput() {
  49368. /**
  49369. * Defines the buttons associated with the input to handle camera move.
  49370. */
  49371. this.buttons = [0, 1, 2];
  49372. /**
  49373. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49374. */
  49375. this.angularSensibilityX = 1000.0;
  49376. /**
  49377. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49378. */
  49379. this.angularSensibilityY = 1000.0;
  49380. /**
  49381. * Defines the pointer pinch precision or how fast is the camera zooming.
  49382. */
  49383. this.pinchPrecision = 12.0;
  49384. /**
  49385. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  49386. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49387. */
  49388. this.pinchDeltaPercentage = 0;
  49389. /**
  49390. * Defines the pointer panning sensibility or how fast is the camera moving.
  49391. */
  49392. this.panningSensibility = 1000.0;
  49393. /**
  49394. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  49395. */
  49396. this.multiTouchPanning = true;
  49397. /**
  49398. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  49399. */
  49400. this.multiTouchPanAndZoom = true;
  49401. /**
  49402. * Revers pinch action direction.
  49403. */
  49404. this.pinchInwards = true;
  49405. this._isPanClick = false;
  49406. }
  49407. /**
  49408. * Attach the input controls to a specific dom element to get the input from.
  49409. * @param element Defines the element the controls should be listened from
  49410. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49411. */
  49412. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  49413. var _this = this;
  49414. var engine = this.camera.getEngine();
  49415. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  49416. var pointA = null;
  49417. var pointB = null;
  49418. var previousPinchSquaredDistance = 0;
  49419. var initialDistance = 0;
  49420. var twoFingerActivityCount = 0;
  49421. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  49422. this._pointerInput = function (p, s) {
  49423. var evt = p.event;
  49424. var isTouch = p.event.pointerType === "touch";
  49425. if (engine.isInVRExclusivePointerMode) {
  49426. return;
  49427. }
  49428. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  49429. return;
  49430. }
  49431. var srcElement = (evt.srcElement || evt.target);
  49432. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49433. try {
  49434. srcElement.setPointerCapture(evt.pointerId);
  49435. }
  49436. catch (e) {
  49437. //Nothing to do with the error. Execution will continue.
  49438. }
  49439. // Manage panning with pan button click
  49440. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  49441. // manage pointers
  49442. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  49443. if (pointA === null) {
  49444. pointA = cacheSoloPointer;
  49445. }
  49446. else if (pointB === null) {
  49447. pointB = cacheSoloPointer;
  49448. }
  49449. if (!noPreventDefault) {
  49450. evt.preventDefault();
  49451. element.focus();
  49452. }
  49453. }
  49454. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  49455. if (_this.camera.useInputToRestoreState) {
  49456. _this.camera.restoreState();
  49457. }
  49458. }
  49459. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49460. try {
  49461. srcElement.releasePointerCapture(evt.pointerId);
  49462. }
  49463. catch (e) {
  49464. //Nothing to do with the error.
  49465. }
  49466. cacheSoloPointer = null;
  49467. previousPinchSquaredDistance = 0;
  49468. previousMultiTouchPanPosition.isPaning = false;
  49469. previousMultiTouchPanPosition.isPinching = false;
  49470. twoFingerActivityCount = 0;
  49471. initialDistance = 0;
  49472. if (!isTouch) {
  49473. pointB = null; // Mouse and pen are mono pointer
  49474. }
  49475. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  49476. //but emptying completly pointers collection is required to fix a bug on iPhone :
  49477. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  49478. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  49479. if (engine._badOS) {
  49480. pointA = pointB = null;
  49481. }
  49482. else {
  49483. //only remove the impacted pointer in case of multitouch allowing on most
  49484. //platforms switching from rotate to zoom and pan seamlessly.
  49485. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  49486. pointA = pointB;
  49487. pointB = null;
  49488. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49489. }
  49490. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  49491. pointB = null;
  49492. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49493. }
  49494. else {
  49495. pointA = pointB = null;
  49496. }
  49497. }
  49498. if (!noPreventDefault) {
  49499. evt.preventDefault();
  49500. }
  49501. }
  49502. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49503. if (!noPreventDefault) {
  49504. evt.preventDefault();
  49505. }
  49506. // One button down
  49507. if (pointA && pointB === null && cacheSoloPointer) {
  49508. if (_this.panningSensibility !== 0 &&
  49509. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  49510. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  49511. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  49512. }
  49513. else {
  49514. var offsetX = evt.clientX - cacheSoloPointer.x;
  49515. var offsetY = evt.clientY - cacheSoloPointer.y;
  49516. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49517. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49518. }
  49519. cacheSoloPointer.x = evt.clientX;
  49520. cacheSoloPointer.y = evt.clientY;
  49521. }
  49522. // Two buttons down: pinch/pan
  49523. else if (pointA && pointB) {
  49524. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  49525. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  49526. ed.x = evt.clientX;
  49527. ed.y = evt.clientY;
  49528. var direction = _this.pinchInwards ? 1 : -1;
  49529. var distX = pointA.x - pointB.x;
  49530. var distY = pointA.y - pointB.y;
  49531. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  49532. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  49533. if (previousPinchSquaredDistance === 0) {
  49534. initialDistance = pinchDistance;
  49535. previousPinchSquaredDistance = pinchSquaredDistance;
  49536. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  49537. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  49538. return;
  49539. }
  49540. if (_this.multiTouchPanAndZoom) {
  49541. if (_this.pinchDeltaPercentage) {
  49542. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49543. }
  49544. else {
  49545. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49546. (_this.pinchPrecision *
  49547. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49548. direction);
  49549. }
  49550. if (_this.panningSensibility !== 0) {
  49551. var pointersCenterX = (pointA.x + pointB.x) / 2;
  49552. var pointersCenterY = (pointA.y + pointB.y) / 2;
  49553. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  49554. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  49555. previousMultiTouchPanPosition.x = pointersCenterX;
  49556. previousMultiTouchPanPosition.y = pointersCenterY;
  49557. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  49558. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  49559. }
  49560. }
  49561. else {
  49562. twoFingerActivityCount++;
  49563. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  49564. if (_this.pinchDeltaPercentage) {
  49565. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49566. }
  49567. else {
  49568. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49569. (_this.pinchPrecision *
  49570. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49571. direction);
  49572. }
  49573. previousMultiTouchPanPosition.isPaning = false;
  49574. previousMultiTouchPanPosition.isPinching = true;
  49575. }
  49576. else {
  49577. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  49578. if (!previousMultiTouchPanPosition.isPaning) {
  49579. previousMultiTouchPanPosition.isPaning = true;
  49580. previousMultiTouchPanPosition.isPinching = false;
  49581. previousMultiTouchPanPosition.x = ed.x;
  49582. previousMultiTouchPanPosition.y = ed.y;
  49583. return;
  49584. }
  49585. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  49586. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  49587. }
  49588. }
  49589. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  49590. previousMultiTouchPanPosition.x = ed.x;
  49591. previousMultiTouchPanPosition.y = ed.y;
  49592. }
  49593. }
  49594. previousPinchSquaredDistance = pinchSquaredDistance;
  49595. }
  49596. }
  49597. };
  49598. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  49599. this._onContextMenu = function (evt) {
  49600. evt.preventDefault();
  49601. };
  49602. if (!this.camera._useCtrlForPanning) {
  49603. element.addEventListener("contextmenu", this._onContextMenu, false);
  49604. }
  49605. this._onLostFocus = function () {
  49606. //this._keys = [];
  49607. pointA = pointB = null;
  49608. previousPinchSquaredDistance = 0;
  49609. previousMultiTouchPanPosition.isPaning = false;
  49610. previousMultiTouchPanPosition.isPinching = false;
  49611. twoFingerActivityCount = 0;
  49612. cacheSoloPointer = null;
  49613. initialDistance = 0;
  49614. };
  49615. this._onMouseMove = function (evt) {
  49616. if (!engine.isPointerLock) {
  49617. return;
  49618. }
  49619. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49620. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49621. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49622. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49623. if (!noPreventDefault) {
  49624. evt.preventDefault();
  49625. }
  49626. };
  49627. this._onGestureStart = function (e) {
  49628. if (window.MSGesture === undefined) {
  49629. return;
  49630. }
  49631. if (!_this._MSGestureHandler) {
  49632. _this._MSGestureHandler = new MSGesture();
  49633. _this._MSGestureHandler.target = element;
  49634. }
  49635. _this._MSGestureHandler.addPointer(e.pointerId);
  49636. };
  49637. this._onGesture = function (e) {
  49638. _this.camera.radius *= e.scale;
  49639. if (e.preventDefault) {
  49640. if (!noPreventDefault) {
  49641. e.stopPropagation();
  49642. e.preventDefault();
  49643. }
  49644. }
  49645. };
  49646. element.addEventListener("mousemove", this._onMouseMove, false);
  49647. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49648. element.addEventListener("MSGestureChange", this._onGesture, false);
  49649. BABYLON.Tools.RegisterTopRootEvents([
  49650. { name: "blur", handler: this._onLostFocus }
  49651. ]);
  49652. };
  49653. /**
  49654. * Detach the current controls from the specified dom element.
  49655. * @param element Defines the element to stop listening the inputs from
  49656. */
  49657. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49658. if (this._onLostFocus) {
  49659. BABYLON.Tools.UnregisterTopRootEvents([
  49660. { name: "blur", handler: this._onLostFocus }
  49661. ]);
  49662. }
  49663. if (element && this._observer) {
  49664. this.camera.getScene().onPointerObservable.remove(this._observer);
  49665. this._observer = null;
  49666. if (this._onContextMenu) {
  49667. element.removeEventListener("contextmenu", this._onContextMenu);
  49668. }
  49669. if (this._onMouseMove) {
  49670. element.removeEventListener("mousemove", this._onMouseMove);
  49671. }
  49672. if (this._onGestureStart) {
  49673. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49674. }
  49675. if (this._onGesture) {
  49676. element.removeEventListener("MSGestureChange", this._onGesture);
  49677. }
  49678. this._isPanClick = false;
  49679. this.pinchInwards = true;
  49680. this._onMouseMove = null;
  49681. this._onGestureStart = null;
  49682. this._onGesture = null;
  49683. this._MSGestureHandler = null;
  49684. this._onLostFocus = null;
  49685. this._onContextMenu = null;
  49686. }
  49687. };
  49688. /**
  49689. * Gets the class name of the current intput.
  49690. * @returns the class name
  49691. */
  49692. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49693. return "ArcRotateCameraPointersInput";
  49694. };
  49695. /**
  49696. * Get the friendly name associated with the input class.
  49697. * @returns the input friendly name
  49698. */
  49699. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49700. return "pointers";
  49701. };
  49702. __decorate([
  49703. BABYLON.serialize()
  49704. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49705. __decorate([
  49706. BABYLON.serialize()
  49707. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49708. __decorate([
  49709. BABYLON.serialize()
  49710. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49711. __decorate([
  49712. BABYLON.serialize()
  49713. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49714. __decorate([
  49715. BABYLON.serialize()
  49716. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49717. __decorate([
  49718. BABYLON.serialize()
  49719. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49720. __decorate([
  49721. BABYLON.serialize()
  49722. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49723. __decorate([
  49724. BABYLON.serialize()
  49725. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49726. return ArcRotateCameraPointersInput;
  49727. }());
  49728. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49729. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49730. })(BABYLON || (BABYLON = {}));
  49731. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49732. var BABYLON;
  49733. (function (BABYLON) {
  49734. /**
  49735. * Default Inputs manager for the ArcRotateCamera.
  49736. * It groups all the default supported inputs for ease of use.
  49737. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49738. */
  49739. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49740. __extends(ArcRotateCameraInputsManager, _super);
  49741. /**
  49742. * Instantiates a new ArcRotateCameraInputsManager.
  49743. * @param camera Defines the camera the inputs belong to
  49744. */
  49745. function ArcRotateCameraInputsManager(camera) {
  49746. return _super.call(this, camera) || this;
  49747. }
  49748. /**
  49749. * Add mouse wheel input support to the input manager.
  49750. * @returns the current input manager
  49751. */
  49752. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49753. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49754. return this;
  49755. };
  49756. /**
  49757. * Add pointers input support to the input manager.
  49758. * @returns the current input manager
  49759. */
  49760. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49761. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49762. return this;
  49763. };
  49764. /**
  49765. * Add keyboard input support to the input manager.
  49766. * @returns the current input manager
  49767. */
  49768. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49769. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49770. return this;
  49771. };
  49772. /**
  49773. * Add orientation input support to the input manager.
  49774. * @returns the current input manager
  49775. */
  49776. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49777. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49778. return this;
  49779. };
  49780. return ArcRotateCameraInputsManager;
  49781. }(BABYLON.CameraInputsManager));
  49782. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49783. })(BABYLON || (BABYLON = {}));
  49784. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49785. var BABYLON;
  49786. (function (BABYLON) {
  49787. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49788. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49789. });
  49790. /**
  49791. * This represents an orbital type of camera.
  49792. *
  49793. * 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.
  49794. * 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.
  49795. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49796. */
  49797. var ArcRotateCamera = /** @class */ (function (_super) {
  49798. __extends(ArcRotateCamera, _super);
  49799. /**
  49800. * Instantiates a new ArcRotateCamera in a given scene
  49801. * @param name Defines the name of the camera
  49802. * @param alpha Defines the camera rotation along the logitudinal axis
  49803. * @param beta Defines the camera rotation along the latitudinal axis
  49804. * @param radius Defines the camera distance from its target
  49805. * @param target Defines the camera target
  49806. * @param scene Defines the scene the camera belongs to
  49807. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49808. */
  49809. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49810. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49811. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49812. /**
  49813. * Current inertia value on the longitudinal axis.
  49814. * The bigger this number the longer it will take for the camera to stop.
  49815. */
  49816. _this.inertialAlphaOffset = 0;
  49817. /**
  49818. * Current inertia value on the latitudinal axis.
  49819. * The bigger this number the longer it will take for the camera to stop.
  49820. */
  49821. _this.inertialBetaOffset = 0;
  49822. /**
  49823. * Current inertia value on the radius axis.
  49824. * The bigger this number the longer it will take for the camera to stop.
  49825. */
  49826. _this.inertialRadiusOffset = 0;
  49827. /**
  49828. * Minimum allowed angle on the longitudinal axis.
  49829. * This can help limiting how the Camera is able to move in the scene.
  49830. */
  49831. _this.lowerAlphaLimit = null;
  49832. /**
  49833. * Maximum allowed angle on the longitudinal axis.
  49834. * This can help limiting how the Camera is able to move in the scene.
  49835. */
  49836. _this.upperAlphaLimit = null;
  49837. /**
  49838. * Minimum allowed angle on the latitudinal axis.
  49839. * This can help limiting how the Camera is able to move in the scene.
  49840. */
  49841. _this.lowerBetaLimit = 0.01;
  49842. /**
  49843. * Maximum allowed angle on the latitudinal axis.
  49844. * This can help limiting how the Camera is able to move in the scene.
  49845. */
  49846. _this.upperBetaLimit = Math.PI;
  49847. /**
  49848. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49849. * This can help limiting how the Camera is able to move in the scene.
  49850. */
  49851. _this.lowerRadiusLimit = null;
  49852. /**
  49853. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49854. * This can help limiting how the Camera is able to move in the scene.
  49855. */
  49856. _this.upperRadiusLimit = null;
  49857. /**
  49858. * Defines the current inertia value used during panning of the camera along the X axis.
  49859. */
  49860. _this.inertialPanningX = 0;
  49861. /**
  49862. * Defines the current inertia value used during panning of the camera along the Y axis.
  49863. */
  49864. _this.inertialPanningY = 0;
  49865. /**
  49866. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49867. * Basically if your fingers moves away from more than this distance you will be considered
  49868. * in pinch mode.
  49869. */
  49870. _this.pinchToPanMaxDistance = 20;
  49871. /**
  49872. * Defines the maximum distance the camera can pan.
  49873. * This could help keeping the cammera always in your scene.
  49874. */
  49875. _this.panningDistanceLimit = null;
  49876. /**
  49877. * Defines the target of the camera before paning.
  49878. */
  49879. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49880. /**
  49881. * Defines the value of the inertia used during panning.
  49882. * 0 would mean stop inertia and one would mean no decelleration at all.
  49883. */
  49884. _this.panningInertia = 0.9;
  49885. //-- end properties for backward compatibility for inputs
  49886. /**
  49887. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49888. */
  49889. _this.zoomOnFactor = 1;
  49890. /**
  49891. * Defines a screen offset for the camera position.
  49892. */
  49893. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49894. /**
  49895. * Allows the camera to be completely reversed.
  49896. * If false the camera can not arrive upside down.
  49897. */
  49898. _this.allowUpsideDown = true;
  49899. /**
  49900. * Define if double tap/click is used to restore the previously saved state of the camera.
  49901. */
  49902. _this.useInputToRestoreState = true;
  49903. /** @hidden */
  49904. _this._viewMatrix = new BABYLON.Matrix();
  49905. /**
  49906. * Defines the allowed panning axis.
  49907. */
  49908. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49909. /**
  49910. * Observable triggered when the mesh target has been changed on the camera.
  49911. */
  49912. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49913. /**
  49914. * Defines whether the camera should check collision with the objects oh the scene.
  49915. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49916. */
  49917. _this.checkCollisions = false;
  49918. /**
  49919. * Defines the collision radius of the camera.
  49920. * This simulates a sphere around the camera.
  49921. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49922. */
  49923. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49924. _this._previousPosition = BABYLON.Vector3.Zero();
  49925. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49926. _this._newPosition = BABYLON.Vector3.Zero();
  49927. _this._computationVector = BABYLON.Vector3.Zero();
  49928. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49929. if (collidedMesh === void 0) { collidedMesh = null; }
  49930. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49931. newPosition.multiplyInPlace(_this._collider._radius);
  49932. }
  49933. if (!collidedMesh) {
  49934. _this._previousPosition.copyFrom(_this.position);
  49935. }
  49936. else {
  49937. _this.setPosition(newPosition);
  49938. if (_this.onCollide) {
  49939. _this.onCollide(collidedMesh);
  49940. }
  49941. }
  49942. // Recompute because of constraints
  49943. var cosa = Math.cos(_this.alpha);
  49944. var sina = Math.sin(_this.alpha);
  49945. var cosb = Math.cos(_this.beta);
  49946. var sinb = Math.sin(_this.beta);
  49947. if (sinb === 0) {
  49948. sinb = 0.0001;
  49949. }
  49950. var target = _this._getTargetPosition();
  49951. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49952. target.addToRef(_this._computationVector, _this._newPosition);
  49953. _this.position.copyFrom(_this._newPosition);
  49954. var up = _this.upVector;
  49955. if (_this.allowUpsideDown && _this.beta < 0) {
  49956. up = up.clone();
  49957. up = up.negate();
  49958. }
  49959. _this._computeViewMatrix(_this.position, target, up);
  49960. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49961. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49962. _this._collisionTriggered = false;
  49963. };
  49964. _this._target = BABYLON.Vector3.Zero();
  49965. if (target) {
  49966. _this.setTarget(target);
  49967. }
  49968. _this.alpha = alpha;
  49969. _this.beta = beta;
  49970. _this.radius = radius;
  49971. _this.getViewMatrix();
  49972. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49973. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49974. return _this;
  49975. }
  49976. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49977. /**
  49978. * Defines the target point of the camera.
  49979. * The camera looks towards it form the radius distance.
  49980. */
  49981. get: function () {
  49982. return this._target;
  49983. },
  49984. set: function (value) {
  49985. this.setTarget(value);
  49986. },
  49987. enumerable: true,
  49988. configurable: true
  49989. });
  49990. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49991. //-- begin properties for backward compatibility for inputs
  49992. /**
  49993. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49994. */
  49995. get: function () {
  49996. var pointers = this.inputs.attached["pointers"];
  49997. if (pointers) {
  49998. return pointers.angularSensibilityX;
  49999. }
  50000. return 0;
  50001. },
  50002. set: function (value) {
  50003. var pointers = this.inputs.attached["pointers"];
  50004. if (pointers) {
  50005. pointers.angularSensibilityX = value;
  50006. }
  50007. },
  50008. enumerable: true,
  50009. configurable: true
  50010. });
  50011. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  50012. /**
  50013. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  50014. */
  50015. get: function () {
  50016. var pointers = this.inputs.attached["pointers"];
  50017. if (pointers) {
  50018. return pointers.angularSensibilityY;
  50019. }
  50020. return 0;
  50021. },
  50022. set: function (value) {
  50023. var pointers = this.inputs.attached["pointers"];
  50024. if (pointers) {
  50025. pointers.angularSensibilityY = value;
  50026. }
  50027. },
  50028. enumerable: true,
  50029. configurable: true
  50030. });
  50031. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  50032. /**
  50033. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  50034. */
  50035. get: function () {
  50036. var pointers = this.inputs.attached["pointers"];
  50037. if (pointers) {
  50038. return pointers.pinchPrecision;
  50039. }
  50040. return 0;
  50041. },
  50042. set: function (value) {
  50043. var pointers = this.inputs.attached["pointers"];
  50044. if (pointers) {
  50045. pointers.pinchPrecision = value;
  50046. }
  50047. },
  50048. enumerable: true,
  50049. configurable: true
  50050. });
  50051. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  50052. /**
  50053. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  50054. * It will be used instead of pinchDeltaPrecision if different from 0.
  50055. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50056. */
  50057. get: function () {
  50058. var pointers = this.inputs.attached["pointers"];
  50059. if (pointers) {
  50060. return pointers.pinchDeltaPercentage;
  50061. }
  50062. return 0;
  50063. },
  50064. set: function (value) {
  50065. var pointers = this.inputs.attached["pointers"];
  50066. if (pointers) {
  50067. pointers.pinchDeltaPercentage = value;
  50068. }
  50069. },
  50070. enumerable: true,
  50071. configurable: true
  50072. });
  50073. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  50074. /**
  50075. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  50076. */
  50077. get: function () {
  50078. var pointers = this.inputs.attached["pointers"];
  50079. if (pointers) {
  50080. return pointers.panningSensibility;
  50081. }
  50082. return 0;
  50083. },
  50084. set: function (value) {
  50085. var pointers = this.inputs.attached["pointers"];
  50086. if (pointers) {
  50087. pointers.panningSensibility = value;
  50088. }
  50089. },
  50090. enumerable: true,
  50091. configurable: true
  50092. });
  50093. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  50094. /**
  50095. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  50096. */
  50097. get: function () {
  50098. var keyboard = this.inputs.attached["keyboard"];
  50099. if (keyboard) {
  50100. return keyboard.keysUp;
  50101. }
  50102. return [];
  50103. },
  50104. set: function (value) {
  50105. var keyboard = this.inputs.attached["keyboard"];
  50106. if (keyboard) {
  50107. keyboard.keysUp = value;
  50108. }
  50109. },
  50110. enumerable: true,
  50111. configurable: true
  50112. });
  50113. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  50114. /**
  50115. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  50116. */
  50117. get: function () {
  50118. var keyboard = this.inputs.attached["keyboard"];
  50119. if (keyboard) {
  50120. return keyboard.keysDown;
  50121. }
  50122. return [];
  50123. },
  50124. set: function (value) {
  50125. var keyboard = this.inputs.attached["keyboard"];
  50126. if (keyboard) {
  50127. keyboard.keysDown = value;
  50128. }
  50129. },
  50130. enumerable: true,
  50131. configurable: true
  50132. });
  50133. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  50134. /**
  50135. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  50136. */
  50137. get: function () {
  50138. var keyboard = this.inputs.attached["keyboard"];
  50139. if (keyboard) {
  50140. return keyboard.keysLeft;
  50141. }
  50142. return [];
  50143. },
  50144. set: function (value) {
  50145. var keyboard = this.inputs.attached["keyboard"];
  50146. if (keyboard) {
  50147. keyboard.keysLeft = value;
  50148. }
  50149. },
  50150. enumerable: true,
  50151. configurable: true
  50152. });
  50153. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  50154. /**
  50155. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  50156. */
  50157. get: function () {
  50158. var keyboard = this.inputs.attached["keyboard"];
  50159. if (keyboard) {
  50160. return keyboard.keysRight;
  50161. }
  50162. return [];
  50163. },
  50164. set: function (value) {
  50165. var keyboard = this.inputs.attached["keyboard"];
  50166. if (keyboard) {
  50167. keyboard.keysRight = value;
  50168. }
  50169. },
  50170. enumerable: true,
  50171. configurable: true
  50172. });
  50173. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  50174. /**
  50175. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50176. */
  50177. get: function () {
  50178. var mousewheel = this.inputs.attached["mousewheel"];
  50179. if (mousewheel) {
  50180. return mousewheel.wheelPrecision;
  50181. }
  50182. return 0;
  50183. },
  50184. set: function (value) {
  50185. var mousewheel = this.inputs.attached["mousewheel"];
  50186. if (mousewheel) {
  50187. mousewheel.wheelPrecision = value;
  50188. }
  50189. },
  50190. enumerable: true,
  50191. configurable: true
  50192. });
  50193. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  50194. /**
  50195. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  50196. * It will be used instead of pinchDeltaPrecision if different from 0.
  50197. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50198. */
  50199. get: function () {
  50200. var mousewheel = this.inputs.attached["mousewheel"];
  50201. if (mousewheel) {
  50202. return mousewheel.wheelDeltaPercentage;
  50203. }
  50204. return 0;
  50205. },
  50206. set: function (value) {
  50207. var mousewheel = this.inputs.attached["mousewheel"];
  50208. if (mousewheel) {
  50209. mousewheel.wheelDeltaPercentage = value;
  50210. }
  50211. },
  50212. enumerable: true,
  50213. configurable: true
  50214. });
  50215. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  50216. /**
  50217. * Gets the bouncing behavior of the camera if it has been enabled.
  50218. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50219. */
  50220. get: function () {
  50221. return this._bouncingBehavior;
  50222. },
  50223. enumerable: true,
  50224. configurable: true
  50225. });
  50226. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  50227. /**
  50228. * Defines if the bouncing behavior of the camera is enabled on the camera.
  50229. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50230. */
  50231. get: function () {
  50232. return this._bouncingBehavior != null;
  50233. },
  50234. set: function (value) {
  50235. if (value === this.useBouncingBehavior) {
  50236. return;
  50237. }
  50238. if (value) {
  50239. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  50240. this.addBehavior(this._bouncingBehavior);
  50241. }
  50242. else if (this._bouncingBehavior) {
  50243. this.removeBehavior(this._bouncingBehavior);
  50244. this._bouncingBehavior = null;
  50245. }
  50246. },
  50247. enumerable: true,
  50248. configurable: true
  50249. });
  50250. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  50251. /**
  50252. * Gets the framing behavior of the camera if it has been enabled.
  50253. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50254. */
  50255. get: function () {
  50256. return this._framingBehavior;
  50257. },
  50258. enumerable: true,
  50259. configurable: true
  50260. });
  50261. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  50262. /**
  50263. * Defines if the framing behavior of the camera is enabled on the camera.
  50264. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50265. */
  50266. get: function () {
  50267. return this._framingBehavior != null;
  50268. },
  50269. set: function (value) {
  50270. if (value === this.useFramingBehavior) {
  50271. return;
  50272. }
  50273. if (value) {
  50274. this._framingBehavior = new BABYLON.FramingBehavior();
  50275. this.addBehavior(this._framingBehavior);
  50276. }
  50277. else if (this._framingBehavior) {
  50278. this.removeBehavior(this._framingBehavior);
  50279. this._framingBehavior = null;
  50280. }
  50281. },
  50282. enumerable: true,
  50283. configurable: true
  50284. });
  50285. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  50286. /**
  50287. * Gets the auto rotation behavior of the camera if it has been enabled.
  50288. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50289. */
  50290. get: function () {
  50291. return this._autoRotationBehavior;
  50292. },
  50293. enumerable: true,
  50294. configurable: true
  50295. });
  50296. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  50297. /**
  50298. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  50299. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50300. */
  50301. get: function () {
  50302. return this._autoRotationBehavior != null;
  50303. },
  50304. set: function (value) {
  50305. if (value === this.useAutoRotationBehavior) {
  50306. return;
  50307. }
  50308. if (value) {
  50309. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  50310. this.addBehavior(this._autoRotationBehavior);
  50311. }
  50312. else if (this._autoRotationBehavior) {
  50313. this.removeBehavior(this._autoRotationBehavior);
  50314. this._autoRotationBehavior = null;
  50315. }
  50316. },
  50317. enumerable: true,
  50318. configurable: true
  50319. });
  50320. // Cache
  50321. /** @hidden */
  50322. ArcRotateCamera.prototype._initCache = function () {
  50323. _super.prototype._initCache.call(this);
  50324. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  50325. this._cache.alpha = undefined;
  50326. this._cache.beta = undefined;
  50327. this._cache.radius = undefined;
  50328. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  50329. };
  50330. /** @hidden */
  50331. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  50332. if (!ignoreParentClass) {
  50333. _super.prototype._updateCache.call(this);
  50334. }
  50335. this._cache._target.copyFrom(this._getTargetPosition());
  50336. this._cache.alpha = this.alpha;
  50337. this._cache.beta = this.beta;
  50338. this._cache.radius = this.radius;
  50339. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  50340. };
  50341. ArcRotateCamera.prototype._getTargetPosition = function () {
  50342. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  50343. var pos = this._targetHost.getAbsolutePosition();
  50344. if (this._targetBoundingCenter) {
  50345. pos.addToRef(this._targetBoundingCenter, this._target);
  50346. }
  50347. else {
  50348. this._target.copyFrom(pos);
  50349. }
  50350. }
  50351. var lockedTargetPosition = this._getLockedTargetPosition();
  50352. if (lockedTargetPosition) {
  50353. return lockedTargetPosition;
  50354. }
  50355. return this._target;
  50356. };
  50357. /**
  50358. * Stores the current state of the camera (alpha, beta, radius and target)
  50359. * @returns the camera itself
  50360. */
  50361. ArcRotateCamera.prototype.storeState = function () {
  50362. this._storedAlpha = this.alpha;
  50363. this._storedBeta = this.beta;
  50364. this._storedRadius = this.radius;
  50365. this._storedTarget = this._getTargetPosition().clone();
  50366. return _super.prototype.storeState.call(this);
  50367. };
  50368. /**
  50369. * @hidden
  50370. * Restored camera state. You must call storeState() first
  50371. */
  50372. ArcRotateCamera.prototype._restoreStateValues = function () {
  50373. if (!_super.prototype._restoreStateValues.call(this)) {
  50374. return false;
  50375. }
  50376. this.alpha = this._storedAlpha;
  50377. this.beta = this._storedBeta;
  50378. this.radius = this._storedRadius;
  50379. this.setTarget(this._storedTarget.clone());
  50380. this.inertialAlphaOffset = 0;
  50381. this.inertialBetaOffset = 0;
  50382. this.inertialRadiusOffset = 0;
  50383. this.inertialPanningX = 0;
  50384. this.inertialPanningY = 0;
  50385. return true;
  50386. };
  50387. // Synchronized
  50388. /** @hidden */
  50389. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  50390. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  50391. return false;
  50392. }
  50393. return this._cache._target.equals(this._getTargetPosition())
  50394. && this._cache.alpha === this.alpha
  50395. && this._cache.beta === this.beta
  50396. && this._cache.radius === this.radius
  50397. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  50398. };
  50399. /**
  50400. * Attached controls to the current camera.
  50401. * @param element Defines the element the controls should be listened from
  50402. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50403. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  50404. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  50405. */
  50406. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  50407. var _this = this;
  50408. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  50409. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  50410. this._useCtrlForPanning = useCtrlForPanning;
  50411. this._panningMouseButton = panningMouseButton;
  50412. this.inputs.attachElement(element, noPreventDefault);
  50413. this._reset = function () {
  50414. _this.inertialAlphaOffset = 0;
  50415. _this.inertialBetaOffset = 0;
  50416. _this.inertialRadiusOffset = 0;
  50417. _this.inertialPanningX = 0;
  50418. _this.inertialPanningY = 0;
  50419. };
  50420. };
  50421. /**
  50422. * Detach the current controls from the camera.
  50423. * The camera will stop reacting to inputs.
  50424. * @param element Defines the element to stop listening the inputs from
  50425. */
  50426. ArcRotateCamera.prototype.detachControl = function (element) {
  50427. this.inputs.detachElement(element);
  50428. if (this._reset) {
  50429. this._reset();
  50430. }
  50431. };
  50432. /** @hidden */
  50433. ArcRotateCamera.prototype._checkInputs = function () {
  50434. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  50435. if (this._collisionTriggered) {
  50436. return;
  50437. }
  50438. this.inputs.checkInputs();
  50439. // Inertia
  50440. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  50441. var inertialAlphaOffset = this.inertialAlphaOffset;
  50442. if (this.beta <= 0) {
  50443. inertialAlphaOffset *= -1;
  50444. }
  50445. if (this.getScene().useRightHandedSystem) {
  50446. inertialAlphaOffset *= -1;
  50447. }
  50448. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  50449. inertialAlphaOffset *= -1;
  50450. }
  50451. this.alpha += inertialAlphaOffset;
  50452. this.beta += this.inertialBetaOffset;
  50453. this.radius -= this.inertialRadiusOffset;
  50454. this.inertialAlphaOffset *= this.inertia;
  50455. this.inertialBetaOffset *= this.inertia;
  50456. this.inertialRadiusOffset *= this.inertia;
  50457. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  50458. this.inertialAlphaOffset = 0;
  50459. }
  50460. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  50461. this.inertialBetaOffset = 0;
  50462. }
  50463. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  50464. this.inertialRadiusOffset = 0;
  50465. }
  50466. }
  50467. // Panning inertia
  50468. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  50469. if (!this._localDirection) {
  50470. this._localDirection = BABYLON.Vector3.Zero();
  50471. this._transformedDirection = BABYLON.Vector3.Zero();
  50472. }
  50473. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  50474. this._localDirection.multiplyInPlace(this.panningAxis);
  50475. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  50476. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  50477. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  50478. if (!this.panningAxis.y) {
  50479. this._transformedDirection.y = 0;
  50480. }
  50481. if (!this._targetHost) {
  50482. if (this.panningDistanceLimit) {
  50483. this._transformedDirection.addInPlace(this._target);
  50484. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  50485. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  50486. this._target.copyFrom(this._transformedDirection);
  50487. }
  50488. }
  50489. else {
  50490. this._target.addInPlace(this._transformedDirection);
  50491. }
  50492. }
  50493. this.inertialPanningX *= this.panningInertia;
  50494. this.inertialPanningY *= this.panningInertia;
  50495. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  50496. this.inertialPanningX = 0;
  50497. }
  50498. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  50499. this.inertialPanningY = 0;
  50500. }
  50501. }
  50502. // Limits
  50503. this._checkLimits();
  50504. _super.prototype._checkInputs.call(this);
  50505. };
  50506. ArcRotateCamera.prototype._checkLimits = function () {
  50507. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  50508. if (this.allowUpsideDown && this.beta > Math.PI) {
  50509. this.beta = this.beta - (2 * Math.PI);
  50510. }
  50511. }
  50512. else {
  50513. if (this.beta < this.lowerBetaLimit) {
  50514. this.beta = this.lowerBetaLimit;
  50515. }
  50516. }
  50517. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  50518. if (this.allowUpsideDown && this.beta < -Math.PI) {
  50519. this.beta = this.beta + (2 * Math.PI);
  50520. }
  50521. }
  50522. else {
  50523. if (this.beta > this.upperBetaLimit) {
  50524. this.beta = this.upperBetaLimit;
  50525. }
  50526. }
  50527. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  50528. this.alpha = this.lowerAlphaLimit;
  50529. }
  50530. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  50531. this.alpha = this.upperAlphaLimit;
  50532. }
  50533. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  50534. this.radius = this.lowerRadiusLimit;
  50535. }
  50536. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  50537. this.radius = this.upperRadiusLimit;
  50538. }
  50539. };
  50540. /**
  50541. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  50542. */
  50543. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  50544. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  50545. this.radius = this._computationVector.length();
  50546. if (this.radius === 0) {
  50547. this.radius = 0.0001; // Just to avoid division by zero
  50548. }
  50549. // Alpha
  50550. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  50551. if (this._computationVector.z < 0) {
  50552. this.alpha = 2 * Math.PI - this.alpha;
  50553. }
  50554. // Beta
  50555. this.beta = Math.acos(this._computationVector.y / this.radius);
  50556. this._checkLimits();
  50557. };
  50558. /**
  50559. * Use a position to define the current camera related information like aplha, beta and radius
  50560. * @param position Defines the position to set the camera at
  50561. */
  50562. ArcRotateCamera.prototype.setPosition = function (position) {
  50563. if (this.position.equals(position)) {
  50564. return;
  50565. }
  50566. this.position.copyFrom(position);
  50567. this.rebuildAnglesAndRadius();
  50568. };
  50569. /**
  50570. * Defines the target the camera should look at.
  50571. * This will automatically adapt alpha beta and radius to fit within the new target.
  50572. * @param target Defines the new target as a Vector or a mesh
  50573. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  50574. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  50575. */
  50576. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  50577. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  50578. if (allowSamePosition === void 0) { allowSamePosition = false; }
  50579. if (target.getBoundingInfo) {
  50580. if (toBoundingCenter) {
  50581. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  50582. }
  50583. else {
  50584. this._targetBoundingCenter = null;
  50585. }
  50586. this._targetHost = target;
  50587. this._target = this._getTargetPosition();
  50588. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  50589. }
  50590. else {
  50591. var newTarget = target;
  50592. var currentTarget = this._getTargetPosition();
  50593. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  50594. return;
  50595. }
  50596. this._targetHost = null;
  50597. this._target = newTarget;
  50598. this._targetBoundingCenter = null;
  50599. this.onMeshTargetChangedObservable.notifyObservers(null);
  50600. }
  50601. this.rebuildAnglesAndRadius();
  50602. };
  50603. /** @hidden */
  50604. ArcRotateCamera.prototype._getViewMatrix = function () {
  50605. // Compute
  50606. var cosa = Math.cos(this.alpha);
  50607. var sina = Math.sin(this.alpha);
  50608. var cosb = Math.cos(this.beta);
  50609. var sinb = Math.sin(this.beta);
  50610. if (sinb === 0) {
  50611. sinb = 0.0001;
  50612. }
  50613. var target = this._getTargetPosition();
  50614. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  50615. target.addToRef(this._computationVector, this._newPosition);
  50616. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  50617. if (!this._collider) {
  50618. this._collider = new BABYLON.Collider();
  50619. }
  50620. this._collider._radius = this.collisionRadius;
  50621. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  50622. this._collisionTriggered = true;
  50623. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50624. }
  50625. else {
  50626. this.position.copyFrom(this._newPosition);
  50627. var up = this.upVector;
  50628. if (this.allowUpsideDown && sinb < 0) {
  50629. up = up.clone();
  50630. up = up.negate();
  50631. }
  50632. this._computeViewMatrix(this.position, target, up);
  50633. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  50634. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  50635. }
  50636. this._currentTarget = target;
  50637. return this._viewMatrix;
  50638. };
  50639. /**
  50640. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  50641. * @param meshes Defines the mesh to zoom on
  50642. * @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)
  50643. */
  50644. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  50645. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50646. meshes = meshes || this.getScene().meshes;
  50647. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  50648. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  50649. this.radius = distance * this.zoomOnFactor;
  50650. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  50651. };
  50652. /**
  50653. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50654. * The target will be changed but the radius
  50655. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50656. * @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)
  50657. */
  50658. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50659. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50660. var meshesOrMinMaxVector;
  50661. var distance;
  50662. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50663. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50664. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50665. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50666. }
  50667. else { //minMaxVector and distance
  50668. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50669. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50670. distance = minMaxVectorAndDistance.distance;
  50671. }
  50672. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50673. if (!doNotUpdateMaxZ) {
  50674. this.maxZ = distance * 2;
  50675. }
  50676. };
  50677. /**
  50678. * @override
  50679. * Override Camera.createRigCamera
  50680. */
  50681. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50682. var alphaShift = 0;
  50683. switch (this.cameraRigMode) {
  50684. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50685. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50686. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50687. case BABYLON.Camera.RIG_MODE_VR:
  50688. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50689. break;
  50690. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50691. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50692. break;
  50693. }
  50694. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50695. rigCam._cameraRigParams = {};
  50696. return rigCam;
  50697. };
  50698. /**
  50699. * @hidden
  50700. * @override
  50701. * Override Camera._updateRigCameras
  50702. */
  50703. ArcRotateCamera.prototype._updateRigCameras = function () {
  50704. var camLeft = this._rigCameras[0];
  50705. var camRight = this._rigCameras[1];
  50706. camLeft.beta = camRight.beta = this.beta;
  50707. camLeft.radius = camRight.radius = this.radius;
  50708. switch (this.cameraRigMode) {
  50709. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50710. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50711. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50712. case BABYLON.Camera.RIG_MODE_VR:
  50713. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50714. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50715. break;
  50716. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50717. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50718. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50719. break;
  50720. }
  50721. _super.prototype._updateRigCameras.call(this);
  50722. };
  50723. /**
  50724. * Destroy the camera and release the current resources hold by it.
  50725. */
  50726. ArcRotateCamera.prototype.dispose = function () {
  50727. this.inputs.clear();
  50728. _super.prototype.dispose.call(this);
  50729. };
  50730. /**
  50731. * Gets the current object class name.
  50732. * @return the class name
  50733. */
  50734. ArcRotateCamera.prototype.getClassName = function () {
  50735. return "ArcRotateCamera";
  50736. };
  50737. __decorate([
  50738. BABYLON.serialize()
  50739. ], ArcRotateCamera.prototype, "alpha", void 0);
  50740. __decorate([
  50741. BABYLON.serialize()
  50742. ], ArcRotateCamera.prototype, "beta", void 0);
  50743. __decorate([
  50744. BABYLON.serialize()
  50745. ], ArcRotateCamera.prototype, "radius", void 0);
  50746. __decorate([
  50747. BABYLON.serializeAsVector3("target")
  50748. ], ArcRotateCamera.prototype, "_target", void 0);
  50749. __decorate([
  50750. BABYLON.serialize()
  50751. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50752. __decorate([
  50753. BABYLON.serialize()
  50754. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50755. __decorate([
  50756. BABYLON.serialize()
  50757. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50758. __decorate([
  50759. BABYLON.serialize()
  50760. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50761. __decorate([
  50762. BABYLON.serialize()
  50763. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50764. __decorate([
  50765. BABYLON.serialize()
  50766. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50767. __decorate([
  50768. BABYLON.serialize()
  50769. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50770. __decorate([
  50771. BABYLON.serialize()
  50772. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50773. __decorate([
  50774. BABYLON.serialize()
  50775. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50776. __decorate([
  50777. BABYLON.serialize()
  50778. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50779. __decorate([
  50780. BABYLON.serialize()
  50781. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50782. __decorate([
  50783. BABYLON.serialize()
  50784. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50785. __decorate([
  50786. BABYLON.serialize()
  50787. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50788. __decorate([
  50789. BABYLON.serializeAsVector3()
  50790. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50791. __decorate([
  50792. BABYLON.serialize()
  50793. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50794. __decorate([
  50795. BABYLON.serialize()
  50796. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50797. __decorate([
  50798. BABYLON.serialize()
  50799. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50800. __decorate([
  50801. BABYLON.serialize()
  50802. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50803. __decorate([
  50804. BABYLON.serialize()
  50805. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50806. return ArcRotateCamera;
  50807. }(BABYLON.TargetCamera));
  50808. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50809. })(BABYLON || (BABYLON = {}));
  50810. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50811. var BABYLON;
  50812. (function (BABYLON) {
  50813. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50814. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50815. });
  50816. /**
  50817. * The HemisphericLight simulates the ambient environment light,
  50818. * so the passed direction is the light reflection direction, not the incoming direction.
  50819. */
  50820. var HemisphericLight = /** @class */ (function (_super) {
  50821. __extends(HemisphericLight, _super);
  50822. /**
  50823. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50824. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50825. * The HemisphericLight can't cast shadows.
  50826. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50827. * @param name The friendly name of the light
  50828. * @param direction The direction of the light reflection
  50829. * @param scene The scene the light belongs to
  50830. */
  50831. function HemisphericLight(name, direction, scene) {
  50832. var _this = _super.call(this, name, scene) || this;
  50833. /**
  50834. * The groundColor is the light in the opposite direction to the one specified during creation.
  50835. * 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.
  50836. */
  50837. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50838. _this.direction = direction || BABYLON.Vector3.Up();
  50839. return _this;
  50840. }
  50841. HemisphericLight.prototype._buildUniformLayout = function () {
  50842. this._uniformBuffer.addUniform("vLightData", 4);
  50843. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50844. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50845. this._uniformBuffer.addUniform("vLightGround", 3);
  50846. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50847. this._uniformBuffer.addUniform("depthValues", 2);
  50848. this._uniformBuffer.create();
  50849. };
  50850. /**
  50851. * Returns the string "HemisphericLight".
  50852. * @return The class name
  50853. */
  50854. HemisphericLight.prototype.getClassName = function () {
  50855. return "HemisphericLight";
  50856. };
  50857. /**
  50858. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50859. * Returns the updated direction.
  50860. * @param target The target the direction should point to
  50861. * @return The computed direction
  50862. */
  50863. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50864. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50865. return this.direction;
  50866. };
  50867. /**
  50868. * Returns the shadow generator associated to the light.
  50869. * @returns Always null for hemispheric lights because it does not support shadows.
  50870. */
  50871. HemisphericLight.prototype.getShadowGenerator = function () {
  50872. return null;
  50873. };
  50874. /**
  50875. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50876. * @param effect The effect to update
  50877. * @param lightIndex The index of the light in the effect to update
  50878. * @returns The hemispheric light
  50879. */
  50880. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50881. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50882. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50883. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50884. return this;
  50885. };
  50886. /**
  50887. * Computes the world matrix of the node
  50888. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50889. * @param useWasUpdatedFlag defines a reserved property
  50890. * @returns the world matrix
  50891. */
  50892. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50893. if (!this._worldMatrix) {
  50894. this._worldMatrix = BABYLON.Matrix.Identity();
  50895. }
  50896. return this._worldMatrix;
  50897. };
  50898. /**
  50899. * Returns the integer 3.
  50900. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50901. */
  50902. HemisphericLight.prototype.getTypeID = function () {
  50903. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50904. };
  50905. /**
  50906. * Prepares the list of defines specific to the light type.
  50907. * @param defines the list of defines
  50908. * @param lightIndex defines the index of the light for the effect
  50909. */
  50910. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50911. defines["HEMILIGHT" + lightIndex] = true;
  50912. };
  50913. __decorate([
  50914. BABYLON.serializeAsColor3()
  50915. ], HemisphericLight.prototype, "groundColor", void 0);
  50916. __decorate([
  50917. BABYLON.serializeAsVector3()
  50918. ], HemisphericLight.prototype, "direction", void 0);
  50919. return HemisphericLight;
  50920. }(BABYLON.Light));
  50921. BABYLON.HemisphericLight = HemisphericLight;
  50922. })(BABYLON || (BABYLON = {}));
  50923. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50924. var BABYLON;
  50925. (function (BABYLON) {
  50926. /**
  50927. * Base implementation IShadowLight
  50928. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50929. */
  50930. var ShadowLight = /** @class */ (function (_super) {
  50931. __extends(ShadowLight, _super);
  50932. function ShadowLight() {
  50933. var _this = _super !== null && _super.apply(this, arguments) || this;
  50934. _this._needProjectionMatrixCompute = true;
  50935. return _this;
  50936. }
  50937. ShadowLight.prototype._setPosition = function (value) {
  50938. this._position = value;
  50939. };
  50940. Object.defineProperty(ShadowLight.prototype, "position", {
  50941. /**
  50942. * Sets the position the shadow will be casted from. Also use as the light position for both
  50943. * point and spot lights.
  50944. */
  50945. get: function () {
  50946. return this._position;
  50947. },
  50948. /**
  50949. * Sets the position the shadow will be casted from. Also use as the light position for both
  50950. * point and spot lights.
  50951. */
  50952. set: function (value) {
  50953. this._setPosition(value);
  50954. },
  50955. enumerable: true,
  50956. configurable: true
  50957. });
  50958. ShadowLight.prototype._setDirection = function (value) {
  50959. this._direction = value;
  50960. };
  50961. Object.defineProperty(ShadowLight.prototype, "direction", {
  50962. /**
  50963. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50964. * Also use as the light direction on spot and directional lights.
  50965. */
  50966. get: function () {
  50967. return this._direction;
  50968. },
  50969. /**
  50970. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50971. * Also use as the light direction on spot and directional lights.
  50972. */
  50973. set: function (value) {
  50974. this._setDirection(value);
  50975. },
  50976. enumerable: true,
  50977. configurable: true
  50978. });
  50979. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50980. /**
  50981. * Gets the shadow projection clipping minimum z value.
  50982. */
  50983. get: function () {
  50984. return this._shadowMinZ;
  50985. },
  50986. /**
  50987. * Sets the shadow projection clipping minimum z value.
  50988. */
  50989. set: function (value) {
  50990. this._shadowMinZ = value;
  50991. this.forceProjectionMatrixCompute();
  50992. },
  50993. enumerable: true,
  50994. configurable: true
  50995. });
  50996. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  50997. /**
  50998. * Sets the shadow projection clipping maximum z value.
  50999. */
  51000. get: function () {
  51001. return this._shadowMaxZ;
  51002. },
  51003. /**
  51004. * Gets the shadow projection clipping maximum z value.
  51005. */
  51006. set: function (value) {
  51007. this._shadowMaxZ = value;
  51008. this.forceProjectionMatrixCompute();
  51009. },
  51010. enumerable: true,
  51011. configurable: true
  51012. });
  51013. /**
  51014. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  51015. * @returns true if the information has been computed, false if it does not need to (no parenting)
  51016. */
  51017. ShadowLight.prototype.computeTransformedInformation = function () {
  51018. if (this.parent && this.parent.getWorldMatrix) {
  51019. if (!this.transformedPosition) {
  51020. this.transformedPosition = BABYLON.Vector3.Zero();
  51021. }
  51022. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  51023. // In case the direction is present.
  51024. if (this.direction) {
  51025. if (!this.transformedDirection) {
  51026. this.transformedDirection = BABYLON.Vector3.Zero();
  51027. }
  51028. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  51029. }
  51030. return true;
  51031. }
  51032. return false;
  51033. };
  51034. /**
  51035. * Return the depth scale used for the shadow map.
  51036. * @returns the depth scale.
  51037. */
  51038. ShadowLight.prototype.getDepthScale = function () {
  51039. return 50.0;
  51040. };
  51041. /**
  51042. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  51043. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51044. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51045. */
  51046. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  51047. return this.transformedDirection ? this.transformedDirection : this.direction;
  51048. };
  51049. /**
  51050. * Returns the ShadowLight absolute position in the World.
  51051. * @returns the position vector in world space
  51052. */
  51053. ShadowLight.prototype.getAbsolutePosition = function () {
  51054. return this.transformedPosition ? this.transformedPosition : this.position;
  51055. };
  51056. /**
  51057. * Sets the ShadowLight direction toward the passed target.
  51058. * @param target The point tot target in local space
  51059. * @returns the updated ShadowLight direction
  51060. */
  51061. ShadowLight.prototype.setDirectionToTarget = function (target) {
  51062. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  51063. return this.direction;
  51064. };
  51065. /**
  51066. * Returns the light rotation in euler definition.
  51067. * @returns the x y z rotation in local space.
  51068. */
  51069. ShadowLight.prototype.getRotation = function () {
  51070. this.direction.normalize();
  51071. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  51072. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  51073. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  51074. };
  51075. /**
  51076. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  51077. * @returns true if a cube texture needs to be use
  51078. */
  51079. ShadowLight.prototype.needCube = function () {
  51080. return false;
  51081. };
  51082. /**
  51083. * Detects if the projection matrix requires to be recomputed this frame.
  51084. * @returns true if it requires to be recomputed otherwise, false.
  51085. */
  51086. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  51087. return this._needProjectionMatrixCompute;
  51088. };
  51089. /**
  51090. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  51091. */
  51092. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  51093. this._needProjectionMatrixCompute = true;
  51094. };
  51095. /** @hidden */
  51096. ShadowLight.prototype._initCache = function () {
  51097. _super.prototype._initCache.call(this);
  51098. this._cache.position = BABYLON.Vector3.Zero();
  51099. };
  51100. /** @hidden */
  51101. ShadowLight.prototype._isSynchronized = function () {
  51102. if (!this._cache.position.equals(this.position)) {
  51103. return false;
  51104. }
  51105. return true;
  51106. };
  51107. /**
  51108. * Computes the world matrix of the node
  51109. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  51110. * @returns the world matrix
  51111. */
  51112. ShadowLight.prototype.computeWorldMatrix = function (force) {
  51113. if (!force && this.isSynchronized()) {
  51114. this._currentRenderId = this.getScene().getRenderId();
  51115. return this._worldMatrix;
  51116. }
  51117. this._updateCache();
  51118. this._cache.position.copyFrom(this.position);
  51119. if (!this._worldMatrix) {
  51120. this._worldMatrix = BABYLON.Matrix.Identity();
  51121. }
  51122. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  51123. if (this.parent && this.parent.getWorldMatrix) {
  51124. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  51125. this._markSyncedWithParent();
  51126. }
  51127. // Cache the determinant
  51128. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  51129. return this._worldMatrix;
  51130. };
  51131. /**
  51132. * Gets the minZ used for shadow according to both the scene and the light.
  51133. * @param activeCamera The camera we are returning the min for
  51134. * @returns the depth min z
  51135. */
  51136. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  51137. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  51138. };
  51139. /**
  51140. * Gets the maxZ used for shadow according to both the scene and the light.
  51141. * @param activeCamera The camera we are returning the max for
  51142. * @returns the depth max z
  51143. */
  51144. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  51145. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  51146. };
  51147. /**
  51148. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  51149. * @param matrix The materix to updated with the projection information
  51150. * @param viewMatrix The transform matrix of the light
  51151. * @param renderList The list of mesh to render in the map
  51152. * @returns The current light
  51153. */
  51154. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51155. if (this.customProjectionMatrixBuilder) {
  51156. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  51157. }
  51158. else {
  51159. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51160. }
  51161. return this;
  51162. };
  51163. __decorate([
  51164. BABYLON.serializeAsVector3()
  51165. ], ShadowLight.prototype, "position", null);
  51166. __decorate([
  51167. BABYLON.serializeAsVector3()
  51168. ], ShadowLight.prototype, "direction", null);
  51169. __decorate([
  51170. BABYLON.serialize()
  51171. ], ShadowLight.prototype, "shadowMinZ", null);
  51172. __decorate([
  51173. BABYLON.serialize()
  51174. ], ShadowLight.prototype, "shadowMaxZ", null);
  51175. return ShadowLight;
  51176. }(BABYLON.Light));
  51177. BABYLON.ShadowLight = ShadowLight;
  51178. })(BABYLON || (BABYLON = {}));
  51179. //# sourceMappingURL=babylon.shadowLight.js.map
  51180. var BABYLON;
  51181. (function (BABYLON) {
  51182. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  51183. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  51184. });
  51185. /**
  51186. * A point light is a light defined by an unique point in world space.
  51187. * The light is emitted in every direction from this point.
  51188. * A good example of a point light is a standard light bulb.
  51189. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51190. */
  51191. var PointLight = /** @class */ (function (_super) {
  51192. __extends(PointLight, _super);
  51193. /**
  51194. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  51195. * A PointLight emits the light in every direction.
  51196. * It can cast shadows.
  51197. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  51198. * ```javascript
  51199. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  51200. * ```
  51201. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51202. * @param name The light friendly name
  51203. * @param position The position of the point light in the scene
  51204. * @param scene The scene the lights belongs to
  51205. */
  51206. function PointLight(name, position, scene) {
  51207. var _this = _super.call(this, name, scene) || this;
  51208. _this._shadowAngle = Math.PI / 2;
  51209. _this.position = position;
  51210. return _this;
  51211. }
  51212. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  51213. /**
  51214. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51215. * This specifies what angle the shadow will use to be created.
  51216. *
  51217. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51218. */
  51219. get: function () {
  51220. return this._shadowAngle;
  51221. },
  51222. /**
  51223. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51224. * This specifies what angle the shadow will use to be created.
  51225. *
  51226. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51227. */
  51228. set: function (value) {
  51229. this._shadowAngle = value;
  51230. this.forceProjectionMatrixCompute();
  51231. },
  51232. enumerable: true,
  51233. configurable: true
  51234. });
  51235. Object.defineProperty(PointLight.prototype, "direction", {
  51236. /**
  51237. * Gets the direction if it has been set.
  51238. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51239. */
  51240. get: function () {
  51241. return this._direction;
  51242. },
  51243. /**
  51244. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51245. */
  51246. set: function (value) {
  51247. var previousNeedCube = this.needCube();
  51248. this._direction = value;
  51249. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  51250. this._shadowGenerator.recreateShadowMap();
  51251. }
  51252. },
  51253. enumerable: true,
  51254. configurable: true
  51255. });
  51256. /**
  51257. * Returns the string "PointLight"
  51258. * @returns the class name
  51259. */
  51260. PointLight.prototype.getClassName = function () {
  51261. return "PointLight";
  51262. };
  51263. /**
  51264. * Returns the integer 0.
  51265. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51266. */
  51267. PointLight.prototype.getTypeID = function () {
  51268. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  51269. };
  51270. /**
  51271. * Specifies wether or not the shadowmap should be a cube texture.
  51272. * @returns true if the shadowmap needs to be a cube texture.
  51273. */
  51274. PointLight.prototype.needCube = function () {
  51275. return !this.direction;
  51276. };
  51277. /**
  51278. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  51279. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51280. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51281. */
  51282. PointLight.prototype.getShadowDirection = function (faceIndex) {
  51283. if (this.direction) {
  51284. return _super.prototype.getShadowDirection.call(this, faceIndex);
  51285. }
  51286. else {
  51287. switch (faceIndex) {
  51288. case 0:
  51289. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  51290. case 1:
  51291. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  51292. case 2:
  51293. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  51294. case 3:
  51295. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  51296. case 4:
  51297. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  51298. case 5:
  51299. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  51300. }
  51301. }
  51302. return BABYLON.Vector3.Zero();
  51303. };
  51304. /**
  51305. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  51306. * - fov = PI / 2
  51307. * - aspect ratio : 1.0
  51308. * - z-near and far equal to the active camera minZ and maxZ.
  51309. * Returns the PointLight.
  51310. */
  51311. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51312. var activeCamera = this.getScene().activeCamera;
  51313. if (!activeCamera) {
  51314. return;
  51315. }
  51316. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51317. };
  51318. PointLight.prototype._buildUniformLayout = function () {
  51319. this._uniformBuffer.addUniform("vLightData", 4);
  51320. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51321. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51322. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51323. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51324. this._uniformBuffer.addUniform("depthValues", 2);
  51325. this._uniformBuffer.create();
  51326. };
  51327. /**
  51328. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  51329. * @param effect The effect to update
  51330. * @param lightIndex The index of the light in the effect to update
  51331. * @returns The point light
  51332. */
  51333. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  51334. if (this.computeTransformedInformation()) {
  51335. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  51336. }
  51337. else {
  51338. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  51339. }
  51340. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  51341. return this;
  51342. };
  51343. /**
  51344. * Prepares the list of defines specific to the light type.
  51345. * @param defines the list of defines
  51346. * @param lightIndex defines the index of the light for the effect
  51347. */
  51348. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51349. defines["POINTLIGHT" + lightIndex] = true;
  51350. };
  51351. __decorate([
  51352. BABYLON.serialize()
  51353. ], PointLight.prototype, "shadowAngle", null);
  51354. return PointLight;
  51355. }(BABYLON.ShadowLight));
  51356. BABYLON.PointLight = PointLight;
  51357. })(BABYLON || (BABYLON = {}));
  51358. //# sourceMappingURL=babylon.pointLight.js.map
  51359. var BABYLON;
  51360. (function (BABYLON) {
  51361. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  51362. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  51363. });
  51364. /**
  51365. * A directional light is defined by a direction (what a surprise!).
  51366. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  51367. * 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.
  51368. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51369. */
  51370. var DirectionalLight = /** @class */ (function (_super) {
  51371. __extends(DirectionalLight, _super);
  51372. /**
  51373. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  51374. * The directional light is emitted from everywhere in the given direction.
  51375. * It can cast shadows.
  51376. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51377. * @param name The friendly name of the light
  51378. * @param direction The direction of the light
  51379. * @param scene The scene the light belongs to
  51380. */
  51381. function DirectionalLight(name, direction, scene) {
  51382. var _this = _super.call(this, name, scene) || this;
  51383. _this._shadowFrustumSize = 0;
  51384. _this._shadowOrthoScale = 0.1;
  51385. /**
  51386. * Automatically compute the projection matrix to best fit (including all the casters)
  51387. * on each frame.
  51388. */
  51389. _this.autoUpdateExtends = true;
  51390. // Cache
  51391. _this._orthoLeft = Number.MAX_VALUE;
  51392. _this._orthoRight = Number.MIN_VALUE;
  51393. _this._orthoTop = Number.MIN_VALUE;
  51394. _this._orthoBottom = Number.MAX_VALUE;
  51395. _this.position = direction.scale(-1.0);
  51396. _this.direction = direction;
  51397. return _this;
  51398. }
  51399. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  51400. /**
  51401. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  51402. */
  51403. get: function () {
  51404. return this._shadowFrustumSize;
  51405. },
  51406. /**
  51407. * Specifies a fix frustum size for the shadow generation.
  51408. */
  51409. set: function (value) {
  51410. this._shadowFrustumSize = value;
  51411. this.forceProjectionMatrixCompute();
  51412. },
  51413. enumerable: true,
  51414. configurable: true
  51415. });
  51416. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  51417. /**
  51418. * Gets the shadow projection scale against the optimal computed one.
  51419. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51420. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51421. */
  51422. get: function () {
  51423. return this._shadowOrthoScale;
  51424. },
  51425. /**
  51426. * Sets the shadow projection scale against the optimal computed one.
  51427. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51428. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51429. */
  51430. set: function (value) {
  51431. this._shadowOrthoScale = value;
  51432. this.forceProjectionMatrixCompute();
  51433. },
  51434. enumerable: true,
  51435. configurable: true
  51436. });
  51437. /**
  51438. * Returns the string "DirectionalLight".
  51439. * @return The class name
  51440. */
  51441. DirectionalLight.prototype.getClassName = function () {
  51442. return "DirectionalLight";
  51443. };
  51444. /**
  51445. * Returns the integer 1.
  51446. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51447. */
  51448. DirectionalLight.prototype.getTypeID = function () {
  51449. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  51450. };
  51451. /**
  51452. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  51453. * Returns the DirectionalLight Shadow projection matrix.
  51454. */
  51455. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51456. if (this.shadowFrustumSize > 0) {
  51457. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  51458. }
  51459. else {
  51460. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51461. }
  51462. };
  51463. /**
  51464. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  51465. * Returns the DirectionalLight Shadow projection matrix.
  51466. */
  51467. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  51468. var activeCamera = this.getScene().activeCamera;
  51469. if (!activeCamera) {
  51470. return;
  51471. }
  51472. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  51473. };
  51474. /**
  51475. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  51476. * Returns the DirectionalLight Shadow projection matrix.
  51477. */
  51478. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51479. var activeCamera = this.getScene().activeCamera;
  51480. if (!activeCamera) {
  51481. return;
  51482. }
  51483. // Check extends
  51484. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  51485. var tempVector3 = BABYLON.Vector3.Zero();
  51486. this._orthoLeft = Number.MAX_VALUE;
  51487. this._orthoRight = Number.MIN_VALUE;
  51488. this._orthoTop = Number.MIN_VALUE;
  51489. this._orthoBottom = Number.MAX_VALUE;
  51490. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  51491. var mesh = renderList[meshIndex];
  51492. if (!mesh) {
  51493. continue;
  51494. }
  51495. var boundingInfo = mesh.getBoundingInfo();
  51496. var boundingBox = boundingInfo.boundingBox;
  51497. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  51498. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  51499. if (tempVector3.x < this._orthoLeft) {
  51500. this._orthoLeft = tempVector3.x;
  51501. }
  51502. if (tempVector3.y < this._orthoBottom) {
  51503. this._orthoBottom = tempVector3.y;
  51504. }
  51505. if (tempVector3.x > this._orthoRight) {
  51506. this._orthoRight = tempVector3.x;
  51507. }
  51508. if (tempVector3.y > this._orthoTop) {
  51509. this._orthoTop = tempVector3.y;
  51510. }
  51511. }
  51512. }
  51513. }
  51514. var xOffset = this._orthoRight - this._orthoLeft;
  51515. var yOffset = this._orthoTop - this._orthoBottom;
  51516. 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);
  51517. };
  51518. DirectionalLight.prototype._buildUniformLayout = function () {
  51519. this._uniformBuffer.addUniform("vLightData", 4);
  51520. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51521. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51522. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51523. this._uniformBuffer.addUniform("depthValues", 2);
  51524. this._uniformBuffer.create();
  51525. };
  51526. /**
  51527. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  51528. * @param effect The effect to update
  51529. * @param lightIndex The index of the light in the effect to update
  51530. * @returns The directional light
  51531. */
  51532. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  51533. if (this.computeTransformedInformation()) {
  51534. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  51535. return this;
  51536. }
  51537. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  51538. return this;
  51539. };
  51540. /**
  51541. * Gets the minZ used for shadow according to both the scene and the light.
  51542. *
  51543. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51544. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51545. * @param activeCamera The camera we are returning the min for
  51546. * @returns the depth min z
  51547. */
  51548. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  51549. return 1;
  51550. };
  51551. /**
  51552. * Gets the maxZ used for shadow according to both the scene and the light.
  51553. *
  51554. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51555. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51556. * @param activeCamera The camera we are returning the max for
  51557. * @returns the depth max z
  51558. */
  51559. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  51560. return 1;
  51561. };
  51562. /**
  51563. * Prepares the list of defines specific to the light type.
  51564. * @param defines the list of defines
  51565. * @param lightIndex defines the index of the light for the effect
  51566. */
  51567. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51568. defines["DIRLIGHT" + lightIndex] = true;
  51569. };
  51570. __decorate([
  51571. BABYLON.serialize()
  51572. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  51573. __decorate([
  51574. BABYLON.serialize()
  51575. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  51576. __decorate([
  51577. BABYLON.serialize()
  51578. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  51579. return DirectionalLight;
  51580. }(BABYLON.ShadowLight));
  51581. BABYLON.DirectionalLight = DirectionalLight;
  51582. })(BABYLON || (BABYLON = {}));
  51583. //# sourceMappingURL=babylon.directionalLight.js.map
  51584. var BABYLON;
  51585. (function (BABYLON) {
  51586. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  51587. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  51588. });
  51589. /**
  51590. * A spot light is defined by a position, a direction, an angle, and an exponent.
  51591. * These values define a cone of light starting from the position, emitting toward the direction.
  51592. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  51593. * and the exponent defines the speed of the decay of the light with distance (reach).
  51594. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51595. */
  51596. var SpotLight = /** @class */ (function (_super) {
  51597. __extends(SpotLight, _super);
  51598. /**
  51599. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  51600. * It can cast shadows.
  51601. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51602. * @param name The light friendly name
  51603. * @param position The position of the spot light in the scene
  51604. * @param direction The direction of the light in the scene
  51605. * @param angle The cone angle of the light in Radians
  51606. * @param exponent The light decay speed with the distance from the emission spot
  51607. * @param scene The scene the lights belongs to
  51608. */
  51609. function SpotLight(name, position, direction, angle, exponent, scene) {
  51610. var _this = _super.call(this, name, scene) || this;
  51611. _this._innerAngle = 0;
  51612. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  51613. _this._projectionTextureLightNear = 1e-6;
  51614. _this._projectionTextureLightFar = 1000.0;
  51615. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  51616. _this._projectionTextureViewLightDirty = true;
  51617. _this._projectionTextureProjectionLightDirty = true;
  51618. _this._projectionTextureDirty = true;
  51619. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  51620. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  51621. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  51622. _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);
  51623. _this.position = position;
  51624. _this.direction = direction;
  51625. _this.angle = angle;
  51626. _this.exponent = exponent;
  51627. return _this;
  51628. }
  51629. Object.defineProperty(SpotLight.prototype, "angle", {
  51630. /**
  51631. * Gets the cone angle of the spot light in Radians.
  51632. */
  51633. get: function () {
  51634. return this._angle;
  51635. },
  51636. /**
  51637. * Sets the cone angle of the spot light in Radians.
  51638. */
  51639. set: function (value) {
  51640. this._angle = value;
  51641. this._cosHalfAngle = Math.cos(value * 0.5);
  51642. this._projectionTextureProjectionLightDirty = true;
  51643. this.forceProjectionMatrixCompute();
  51644. this._computeAngleValues();
  51645. },
  51646. enumerable: true,
  51647. configurable: true
  51648. });
  51649. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  51650. /**
  51651. * Only used in gltf falloff mode, this defines the angle where
  51652. * the directional falloff will start before cutting at angle which could be seen
  51653. * as outer angle.
  51654. */
  51655. get: function () {
  51656. return this._innerAngle;
  51657. },
  51658. /**
  51659. * Only used in gltf falloff mode, this defines the angle where
  51660. * the directional falloff will start before cutting at angle which could be seen
  51661. * as outer angle.
  51662. */
  51663. set: function (value) {
  51664. this._innerAngle = value;
  51665. this._computeAngleValues();
  51666. },
  51667. enumerable: true,
  51668. configurable: true
  51669. });
  51670. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51671. /**
  51672. * Allows scaling the angle of the light for shadow generation only.
  51673. */
  51674. get: function () {
  51675. return this._shadowAngleScale;
  51676. },
  51677. /**
  51678. * Allows scaling the angle of the light for shadow generation only.
  51679. */
  51680. set: function (value) {
  51681. this._shadowAngleScale = value;
  51682. this.forceProjectionMatrixCompute();
  51683. },
  51684. enumerable: true,
  51685. configurable: true
  51686. });
  51687. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51688. /**
  51689. * Allows reading the projecton texture
  51690. */
  51691. get: function () {
  51692. return this._projectionTextureMatrix;
  51693. },
  51694. enumerable: true,
  51695. configurable: true
  51696. });
  51697. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51698. /**
  51699. * Gets the near clip of the Spotlight for texture projection.
  51700. */
  51701. get: function () {
  51702. return this._projectionTextureLightNear;
  51703. },
  51704. /**
  51705. * Sets the near clip of the Spotlight for texture projection.
  51706. */
  51707. set: function (value) {
  51708. this._projectionTextureLightNear = value;
  51709. this._projectionTextureProjectionLightDirty = true;
  51710. },
  51711. enumerable: true,
  51712. configurable: true
  51713. });
  51714. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51715. /**
  51716. * Gets the far clip of the Spotlight for texture projection.
  51717. */
  51718. get: function () {
  51719. return this._projectionTextureLightFar;
  51720. },
  51721. /**
  51722. * Sets the far clip of the Spotlight for texture projection.
  51723. */
  51724. set: function (value) {
  51725. this._projectionTextureLightFar = value;
  51726. this._projectionTextureProjectionLightDirty = true;
  51727. },
  51728. enumerable: true,
  51729. configurable: true
  51730. });
  51731. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51732. /**
  51733. * Gets the Up vector of the Spotlight for texture projection.
  51734. */
  51735. get: function () {
  51736. return this._projectionTextureUpDirection;
  51737. },
  51738. /**
  51739. * Sets the Up vector of the Spotlight for texture projection.
  51740. */
  51741. set: function (value) {
  51742. this._projectionTextureUpDirection = value;
  51743. this._projectionTextureProjectionLightDirty = true;
  51744. },
  51745. enumerable: true,
  51746. configurable: true
  51747. });
  51748. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51749. /**
  51750. * Gets the projection texture of the light.
  51751. */
  51752. get: function () {
  51753. return this._projectionTexture;
  51754. },
  51755. /**
  51756. * Sets the projection texture of the light.
  51757. */
  51758. set: function (value) {
  51759. this._projectionTexture = value;
  51760. this._projectionTextureDirty = true;
  51761. },
  51762. enumerable: true,
  51763. configurable: true
  51764. });
  51765. /**
  51766. * Returns the string "SpotLight".
  51767. * @returns the class name
  51768. */
  51769. SpotLight.prototype.getClassName = function () {
  51770. return "SpotLight";
  51771. };
  51772. /**
  51773. * Returns the integer 2.
  51774. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51775. */
  51776. SpotLight.prototype.getTypeID = function () {
  51777. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51778. };
  51779. /**
  51780. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51781. */
  51782. SpotLight.prototype._setDirection = function (value) {
  51783. _super.prototype._setDirection.call(this, value);
  51784. this._projectionTextureViewLightDirty = true;
  51785. };
  51786. /**
  51787. * Overrides the position setter to recompute the projection texture view light Matrix.
  51788. */
  51789. SpotLight.prototype._setPosition = function (value) {
  51790. _super.prototype._setPosition.call(this, value);
  51791. this._projectionTextureViewLightDirty = true;
  51792. };
  51793. /**
  51794. * 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.
  51795. * Returns the SpotLight.
  51796. */
  51797. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51798. var activeCamera = this.getScene().activeCamera;
  51799. if (!activeCamera) {
  51800. return;
  51801. }
  51802. this._shadowAngleScale = this._shadowAngleScale || 1;
  51803. var angle = this._shadowAngleScale * this._angle;
  51804. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51805. };
  51806. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51807. this._projectionTextureViewLightDirty = false;
  51808. this._projectionTextureDirty = true;
  51809. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51810. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51811. };
  51812. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51813. this._projectionTextureProjectionLightDirty = false;
  51814. this._projectionTextureDirty = true;
  51815. var light_far = this.projectionTextureLightFar;
  51816. var light_near = this.projectionTextureLightNear;
  51817. var P = light_far / (light_far - light_near);
  51818. var Q = -P * light_near;
  51819. var S = 1.0 / Math.tan(this._angle / 2.0);
  51820. var A = 1.0;
  51821. 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);
  51822. };
  51823. /**
  51824. * Main function for light texture projection matrix computing.
  51825. */
  51826. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51827. this._projectionTextureDirty = false;
  51828. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51829. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51830. };
  51831. SpotLight.prototype._buildUniformLayout = function () {
  51832. this._uniformBuffer.addUniform("vLightData", 4);
  51833. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51834. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51835. this._uniformBuffer.addUniform("vLightDirection", 3);
  51836. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51837. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51838. this._uniformBuffer.addUniform("depthValues", 2);
  51839. this._uniformBuffer.create();
  51840. };
  51841. SpotLight.prototype._computeAngleValues = function () {
  51842. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51843. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51844. };
  51845. /**
  51846. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51847. * @param effect The effect to update
  51848. * @param lightIndex The index of the light in the effect to update
  51849. * @returns The spot light
  51850. */
  51851. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51852. var normalizeDirection;
  51853. if (this.computeTransformedInformation()) {
  51854. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51855. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51856. }
  51857. else {
  51858. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51859. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51860. }
  51861. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51862. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51863. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51864. if (this._projectionTextureViewLightDirty) {
  51865. this._computeProjectionTextureViewLightMatrix();
  51866. }
  51867. if (this._projectionTextureProjectionLightDirty) {
  51868. this._computeProjectionTextureProjectionLightMatrix();
  51869. }
  51870. if (this._projectionTextureDirty) {
  51871. this._computeProjectionTextureMatrix();
  51872. }
  51873. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51874. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51875. }
  51876. return this;
  51877. };
  51878. /**
  51879. * Disposes the light and the associated resources.
  51880. */
  51881. SpotLight.prototype.dispose = function () {
  51882. _super.prototype.dispose.call(this);
  51883. if (this._projectionTexture) {
  51884. this._projectionTexture.dispose();
  51885. }
  51886. };
  51887. /**
  51888. * Prepares the list of defines specific to the light type.
  51889. * @param defines the list of defines
  51890. * @param lightIndex defines the index of the light for the effect
  51891. */
  51892. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51893. defines["SPOTLIGHT" + lightIndex] = true;
  51894. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51895. };
  51896. __decorate([
  51897. BABYLON.serialize()
  51898. ], SpotLight.prototype, "angle", null);
  51899. __decorate([
  51900. BABYLON.serialize()
  51901. ], SpotLight.prototype, "innerAngle", null);
  51902. __decorate([
  51903. BABYLON.serialize()
  51904. ], SpotLight.prototype, "shadowAngleScale", null);
  51905. __decorate([
  51906. BABYLON.serialize()
  51907. ], SpotLight.prototype, "exponent", void 0);
  51908. __decorate([
  51909. BABYLON.serialize()
  51910. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51911. __decorate([
  51912. BABYLON.serialize()
  51913. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51914. __decorate([
  51915. BABYLON.serialize()
  51916. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51917. __decorate([
  51918. BABYLON.serializeAsTexture("projectedLightTexture")
  51919. ], SpotLight.prototype, "_projectionTexture", void 0);
  51920. return SpotLight;
  51921. }(BABYLON.ShadowLight));
  51922. BABYLON.SpotLight = SpotLight;
  51923. })(BABYLON || (BABYLON = {}));
  51924. //# sourceMappingURL=babylon.spotLight.js.map
  51925. var BABYLON;
  51926. (function (BABYLON) {
  51927. /**
  51928. * Class used to override all child animations of a given target
  51929. */
  51930. var AnimationPropertiesOverride = /** @class */ (function () {
  51931. function AnimationPropertiesOverride() {
  51932. /**
  51933. * Gets or sets a value indicating if animation blending must be used
  51934. */
  51935. this.enableBlending = false;
  51936. /**
  51937. * Gets or sets the blending speed to use when enableBlending is true
  51938. */
  51939. this.blendingSpeed = 0.01;
  51940. /**
  51941. * Gets or sets the default loop mode to use
  51942. */
  51943. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51944. }
  51945. return AnimationPropertiesOverride;
  51946. }());
  51947. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51948. })(BABYLON || (BABYLON = {}));
  51949. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51950. var BABYLON;
  51951. (function (BABYLON) {
  51952. /**
  51953. * Represents the range of an animation
  51954. */
  51955. var AnimationRange = /** @class */ (function () {
  51956. /**
  51957. * Initializes the range of an animation
  51958. * @param name The name of the animation range
  51959. * @param from The starting frame of the animation
  51960. * @param to The ending frame of the animation
  51961. */
  51962. function AnimationRange(
  51963. /**The name of the animation range**/
  51964. name,
  51965. /**The starting frame of the animation */
  51966. from,
  51967. /**The ending frame of the animation*/
  51968. to) {
  51969. this.name = name;
  51970. this.from = from;
  51971. this.to = to;
  51972. }
  51973. /**
  51974. * Makes a copy of the animation range
  51975. * @returns A copy of the animation range
  51976. */
  51977. AnimationRange.prototype.clone = function () {
  51978. return new AnimationRange(this.name, this.from, this.to);
  51979. };
  51980. return AnimationRange;
  51981. }());
  51982. BABYLON.AnimationRange = AnimationRange;
  51983. /**
  51984. * Composed of a frame, and an action function
  51985. */
  51986. var AnimationEvent = /** @class */ (function () {
  51987. /**
  51988. * Initializes the animation event
  51989. * @param frame The frame for which the event is triggered
  51990. * @param action The event to perform when triggered
  51991. * @param onlyOnce Specifies if the event should be triggered only once
  51992. */
  51993. function AnimationEvent(
  51994. /** The frame for which the event is triggered **/
  51995. frame,
  51996. /** The event to perform when triggered **/
  51997. action,
  51998. /** Specifies if the event should be triggered only once**/
  51999. onlyOnce) {
  52000. this.frame = frame;
  52001. this.action = action;
  52002. this.onlyOnce = onlyOnce;
  52003. /**
  52004. * Specifies if the animation event is done
  52005. */
  52006. this.isDone = false;
  52007. }
  52008. /** @hidden */
  52009. AnimationEvent.prototype._clone = function () {
  52010. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  52011. };
  52012. return AnimationEvent;
  52013. }());
  52014. BABYLON.AnimationEvent = AnimationEvent;
  52015. /**
  52016. * A cursor which tracks a point on a path
  52017. */
  52018. var PathCursor = /** @class */ (function () {
  52019. /**
  52020. * Initializes the path cursor
  52021. * @param path The path to track
  52022. */
  52023. function PathCursor(path) {
  52024. this.path = path;
  52025. /**
  52026. * Stores path cursor callbacks for when an onchange event is triggered
  52027. */
  52028. this._onchange = new Array();
  52029. /**
  52030. * The value of the path cursor
  52031. */
  52032. this.value = 0;
  52033. /**
  52034. * The animation array of the path cursor
  52035. */
  52036. this.animations = new Array();
  52037. }
  52038. /**
  52039. * Gets the cursor point on the path
  52040. * @returns A point on the path cursor at the cursor location
  52041. */
  52042. PathCursor.prototype.getPoint = function () {
  52043. var point = this.path.getPointAtLengthPosition(this.value);
  52044. return new BABYLON.Vector3(point.x, 0, point.y);
  52045. };
  52046. /**
  52047. * Moves the cursor ahead by the step amount
  52048. * @param step The amount to move the cursor forward
  52049. * @returns This path cursor
  52050. */
  52051. PathCursor.prototype.moveAhead = function (step) {
  52052. if (step === void 0) { step = 0.002; }
  52053. this.move(step);
  52054. return this;
  52055. };
  52056. /**
  52057. * Moves the cursor behind by the step amount
  52058. * @param step The amount to move the cursor back
  52059. * @returns This path cursor
  52060. */
  52061. PathCursor.prototype.moveBack = function (step) {
  52062. if (step === void 0) { step = 0.002; }
  52063. this.move(-step);
  52064. return this;
  52065. };
  52066. /**
  52067. * Moves the cursor by the step amount
  52068. * If the step amount is greater than one, an exception is thrown
  52069. * @param step The amount to move the cursor
  52070. * @returns This path cursor
  52071. */
  52072. PathCursor.prototype.move = function (step) {
  52073. if (Math.abs(step) > 1) {
  52074. throw "step size should be less than 1.";
  52075. }
  52076. this.value += step;
  52077. this.ensureLimits();
  52078. this.raiseOnChange();
  52079. return this;
  52080. };
  52081. /**
  52082. * Ensures that the value is limited between zero and one
  52083. * @returns This path cursor
  52084. */
  52085. PathCursor.prototype.ensureLimits = function () {
  52086. while (this.value > 1) {
  52087. this.value -= 1;
  52088. }
  52089. while (this.value < 0) {
  52090. this.value += 1;
  52091. }
  52092. return this;
  52093. };
  52094. /**
  52095. * Runs onchange callbacks on change (used by the animation engine)
  52096. * @returns This path cursor
  52097. */
  52098. PathCursor.prototype.raiseOnChange = function () {
  52099. var _this = this;
  52100. this._onchange.forEach(function (f) { return f(_this); });
  52101. return this;
  52102. };
  52103. /**
  52104. * Executes a function on change
  52105. * @param f A path cursor onchange callback
  52106. * @returns This path cursor
  52107. */
  52108. PathCursor.prototype.onchange = function (f) {
  52109. this._onchange.push(f);
  52110. return this;
  52111. };
  52112. return PathCursor;
  52113. }());
  52114. BABYLON.PathCursor = PathCursor;
  52115. /**
  52116. * Enum for the animation key frame interpolation type
  52117. */
  52118. var AnimationKeyInterpolation;
  52119. (function (AnimationKeyInterpolation) {
  52120. /**
  52121. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  52122. */
  52123. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  52124. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  52125. /**
  52126. * Class used to store any kind of animation
  52127. */
  52128. var Animation = /** @class */ (function () {
  52129. /**
  52130. * Initializes the animation
  52131. * @param name Name of the animation
  52132. * @param targetProperty Property to animate
  52133. * @param framePerSecond The frames per second of the animation
  52134. * @param dataType The data type of the animation
  52135. * @param loopMode The loop mode of the animation
  52136. * @param enableBlendings Specifies if blending should be enabled
  52137. */
  52138. function Animation(
  52139. /**Name of the animation */
  52140. name,
  52141. /**Property to animate */
  52142. targetProperty,
  52143. /**The frames per second of the animation */
  52144. framePerSecond,
  52145. /**The data type of the animation */
  52146. dataType,
  52147. /**The loop mode of the animation */
  52148. loopMode,
  52149. /**Specifies if blending should be enabled */
  52150. enableBlending) {
  52151. this.name = name;
  52152. this.targetProperty = targetProperty;
  52153. this.framePerSecond = framePerSecond;
  52154. this.dataType = dataType;
  52155. this.loopMode = loopMode;
  52156. this.enableBlending = enableBlending;
  52157. /**
  52158. * @hidden Internal use only
  52159. */
  52160. this._runtimeAnimations = new Array();
  52161. /**
  52162. * The set of event that will be linked to this animation
  52163. */
  52164. this._events = new Array();
  52165. /**
  52166. * Stores the blending speed of the animation
  52167. */
  52168. this.blendingSpeed = 0.01;
  52169. /**
  52170. * Stores the animation ranges for the animation
  52171. */
  52172. this._ranges = {};
  52173. this.targetPropertyPath = targetProperty.split(".");
  52174. this.dataType = dataType;
  52175. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  52176. }
  52177. /**
  52178. * @hidden Internal use
  52179. */
  52180. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  52181. var dataType = undefined;
  52182. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  52183. dataType = Animation.ANIMATIONTYPE_FLOAT;
  52184. }
  52185. else if (from instanceof BABYLON.Quaternion) {
  52186. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  52187. }
  52188. else if (from instanceof BABYLON.Vector3) {
  52189. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  52190. }
  52191. else if (from instanceof BABYLON.Vector2) {
  52192. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  52193. }
  52194. else if (from instanceof BABYLON.Color3) {
  52195. dataType = Animation.ANIMATIONTYPE_COLOR3;
  52196. }
  52197. else if (from instanceof BABYLON.Size) {
  52198. dataType = Animation.ANIMATIONTYPE_SIZE;
  52199. }
  52200. if (dataType == undefined) {
  52201. return null;
  52202. }
  52203. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  52204. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  52205. animation.setKeys(keys);
  52206. if (easingFunction !== undefined) {
  52207. animation.setEasingFunction(easingFunction);
  52208. }
  52209. return animation;
  52210. };
  52211. /**
  52212. * Sets up an animation
  52213. * @param property The property to animate
  52214. * @param animationType The animation type to apply
  52215. * @param framePerSecond The frames per second of the animation
  52216. * @param easingFunction The easing function used in the animation
  52217. * @returns The created animation
  52218. */
  52219. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  52220. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  52221. animation.setEasingFunction(easingFunction);
  52222. return animation;
  52223. };
  52224. /**
  52225. * Create and start an animation on a node
  52226. * @param name defines the name of the global animation that will be run on all nodes
  52227. * @param node defines the root node where the animation will take place
  52228. * @param targetProperty defines property to animate
  52229. * @param framePerSecond defines the number of frame per second yo use
  52230. * @param totalFrame defines the number of frames in total
  52231. * @param from defines the initial value
  52232. * @param to defines the final value
  52233. * @param loopMode defines which loop mode you want to use (off by default)
  52234. * @param easingFunction defines the easing function to use (linear by default)
  52235. * @param onAnimationEnd defines the callback to call when animation end
  52236. * @returns the animatable created for this animation
  52237. */
  52238. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52239. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52240. if (!animation) {
  52241. return null;
  52242. }
  52243. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52244. };
  52245. /**
  52246. * Create and start an animation on a node and its descendants
  52247. * @param name defines the name of the global animation that will be run on all nodes
  52248. * @param node defines the root node where the animation will take place
  52249. * @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
  52250. * @param targetProperty defines property to animate
  52251. * @param framePerSecond defines the number of frame per second to use
  52252. * @param totalFrame defines the number of frames in total
  52253. * @param from defines the initial value
  52254. * @param to defines the final value
  52255. * @param loopMode defines which loop mode you want to use (off by default)
  52256. * @param easingFunction defines the easing function to use (linear by default)
  52257. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  52258. * @returns the list of animatables created for all nodes
  52259. * @example https://www.babylonjs-playground.com/#MH0VLI
  52260. */
  52261. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52262. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52263. if (!animation) {
  52264. return null;
  52265. }
  52266. var scene = node.getScene();
  52267. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52268. };
  52269. /**
  52270. * Creates a new animation, merges it with the existing animations and starts it
  52271. * @param name Name of the animation
  52272. * @param node Node which contains the scene that begins the animations
  52273. * @param targetProperty Specifies which property to animate
  52274. * @param framePerSecond The frames per second of the animation
  52275. * @param totalFrame The total number of frames
  52276. * @param from The frame at the beginning of the animation
  52277. * @param to The frame at the end of the animation
  52278. * @param loopMode Specifies the loop mode of the animation
  52279. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  52280. * @param onAnimationEnd Callback to run once the animation is complete
  52281. * @returns Nullable animation
  52282. */
  52283. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52284. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52285. if (!animation) {
  52286. return null;
  52287. }
  52288. node.animations.push(animation);
  52289. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52290. };
  52291. /**
  52292. * Transition property of an host to the target Value
  52293. * @param property The property to transition
  52294. * @param targetValue The target Value of the property
  52295. * @param host The object where the property to animate belongs
  52296. * @param scene Scene used to run the animation
  52297. * @param frameRate Framerate (in frame/s) to use
  52298. * @param transition The transition type we want to use
  52299. * @param duration The duration of the animation, in milliseconds
  52300. * @param onAnimationEnd Callback trigger at the end of the animation
  52301. * @returns Nullable animation
  52302. */
  52303. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  52304. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  52305. if (duration <= 0) {
  52306. host[property] = targetValue;
  52307. if (onAnimationEnd) {
  52308. onAnimationEnd();
  52309. }
  52310. return null;
  52311. }
  52312. var endFrame = frameRate * (duration / 1000);
  52313. transition.setKeys([{
  52314. frame: 0,
  52315. value: host[property].clone ? host[property].clone() : host[property]
  52316. },
  52317. {
  52318. frame: endFrame,
  52319. value: targetValue
  52320. }]);
  52321. if (!host.animations) {
  52322. host.animations = [];
  52323. }
  52324. host.animations.push(transition);
  52325. var animation = scene.beginAnimation(host, 0, endFrame, false);
  52326. animation.onAnimationEnd = onAnimationEnd;
  52327. return animation;
  52328. };
  52329. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  52330. /**
  52331. * Return the array of runtime animations currently using this animation
  52332. */
  52333. get: function () {
  52334. return this._runtimeAnimations;
  52335. },
  52336. enumerable: true,
  52337. configurable: true
  52338. });
  52339. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  52340. /**
  52341. * Specifies if any of the runtime animations are currently running
  52342. */
  52343. get: function () {
  52344. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  52345. var runtimeAnimation = _a[_i];
  52346. if (!runtimeAnimation.isStopped) {
  52347. return true;
  52348. }
  52349. }
  52350. return false;
  52351. },
  52352. enumerable: true,
  52353. configurable: true
  52354. });
  52355. // Methods
  52356. /**
  52357. * Converts the animation to a string
  52358. * @param fullDetails support for multiple levels of logging within scene loading
  52359. * @returns String form of the animation
  52360. */
  52361. Animation.prototype.toString = function (fullDetails) {
  52362. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  52363. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  52364. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  52365. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  52366. if (fullDetails) {
  52367. ret += ", Ranges: {";
  52368. var first = true;
  52369. for (var name in this._ranges) {
  52370. if (first) {
  52371. ret += ", ";
  52372. first = false;
  52373. }
  52374. ret += name;
  52375. }
  52376. ret += "}";
  52377. }
  52378. return ret;
  52379. };
  52380. /**
  52381. * Add an event to this animation
  52382. * @param event Event to add
  52383. */
  52384. Animation.prototype.addEvent = function (event) {
  52385. this._events.push(event);
  52386. };
  52387. /**
  52388. * Remove all events found at the given frame
  52389. * @param frame The frame to remove events from
  52390. */
  52391. Animation.prototype.removeEvents = function (frame) {
  52392. for (var index = 0; index < this._events.length; index++) {
  52393. if (this._events[index].frame === frame) {
  52394. this._events.splice(index, 1);
  52395. index--;
  52396. }
  52397. }
  52398. };
  52399. /**
  52400. * Retrieves all the events from the animation
  52401. * @returns Events from the animation
  52402. */
  52403. Animation.prototype.getEvents = function () {
  52404. return this._events;
  52405. };
  52406. /**
  52407. * Creates an animation range
  52408. * @param name Name of the animation range
  52409. * @param from Starting frame of the animation range
  52410. * @param to Ending frame of the animation
  52411. */
  52412. Animation.prototype.createRange = function (name, from, to) {
  52413. // check name not already in use; could happen for bones after serialized
  52414. if (!this._ranges[name]) {
  52415. this._ranges[name] = new AnimationRange(name, from, to);
  52416. }
  52417. };
  52418. /**
  52419. * Deletes an animation range by name
  52420. * @param name Name of the animation range to delete
  52421. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  52422. */
  52423. Animation.prototype.deleteRange = function (name, deleteFrames) {
  52424. if (deleteFrames === void 0) { deleteFrames = true; }
  52425. var range = this._ranges[name];
  52426. if (!range) {
  52427. return;
  52428. }
  52429. if (deleteFrames) {
  52430. var from = range.from;
  52431. var to = range.to;
  52432. // this loop MUST go high to low for multiple splices to work
  52433. for (var key = this._keys.length - 1; key >= 0; key--) {
  52434. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  52435. this._keys.splice(key, 1);
  52436. }
  52437. }
  52438. }
  52439. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  52440. };
  52441. /**
  52442. * Gets the animation range by name, or null if not defined
  52443. * @param name Name of the animation range
  52444. * @returns Nullable animation range
  52445. */
  52446. Animation.prototype.getRange = function (name) {
  52447. return this._ranges[name];
  52448. };
  52449. /**
  52450. * Gets the key frames from the animation
  52451. * @returns The key frames of the animation
  52452. */
  52453. Animation.prototype.getKeys = function () {
  52454. return this._keys;
  52455. };
  52456. /**
  52457. * Gets the highest frame rate of the animation
  52458. * @returns Highest frame rate of the animation
  52459. */
  52460. Animation.prototype.getHighestFrame = function () {
  52461. var ret = 0;
  52462. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  52463. if (ret < this._keys[key].frame) {
  52464. ret = this._keys[key].frame;
  52465. }
  52466. }
  52467. return ret;
  52468. };
  52469. /**
  52470. * Gets the easing function of the animation
  52471. * @returns Easing function of the animation
  52472. */
  52473. Animation.prototype.getEasingFunction = function () {
  52474. return this._easingFunction;
  52475. };
  52476. /**
  52477. * Sets the easing function of the animation
  52478. * @param easingFunction A custom mathematical formula for animation
  52479. */
  52480. Animation.prototype.setEasingFunction = function (easingFunction) {
  52481. this._easingFunction = easingFunction;
  52482. };
  52483. /**
  52484. * Interpolates a scalar linearly
  52485. * @param startValue Start value of the animation curve
  52486. * @param endValue End value of the animation curve
  52487. * @param gradient Scalar amount to interpolate
  52488. * @returns Interpolated scalar value
  52489. */
  52490. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  52491. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  52492. };
  52493. /**
  52494. * Interpolates a scalar cubically
  52495. * @param startValue Start value of the animation curve
  52496. * @param outTangent End tangent of the animation
  52497. * @param endValue End value of the animation curve
  52498. * @param inTangent Start tangent of the animation curve
  52499. * @param gradient Scalar amount to interpolate
  52500. * @returns Interpolated scalar value
  52501. */
  52502. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52503. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52504. };
  52505. /**
  52506. * Interpolates a quaternion using a spherical linear interpolation
  52507. * @param startValue Start value of the animation curve
  52508. * @param endValue End value of the animation curve
  52509. * @param gradient Scalar amount to interpolate
  52510. * @returns Interpolated quaternion value
  52511. */
  52512. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  52513. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  52514. };
  52515. /**
  52516. * Interpolates a quaternion cubically
  52517. * @param startValue Start value of the animation curve
  52518. * @param outTangent End tangent of the animation curve
  52519. * @param endValue End value of the animation curve
  52520. * @param inTangent Start tangent of the animation curve
  52521. * @param gradient Scalar amount to interpolate
  52522. * @returns Interpolated quaternion value
  52523. */
  52524. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52525. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  52526. };
  52527. /**
  52528. * Interpolates a Vector3 linearl
  52529. * @param startValue Start value of the animation curve
  52530. * @param endValue End value of the animation curve
  52531. * @param gradient Scalar amount to interpolate
  52532. * @returns Interpolated scalar value
  52533. */
  52534. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  52535. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  52536. };
  52537. /**
  52538. * Interpolates a Vector3 cubically
  52539. * @param startValue Start value of the animation curve
  52540. * @param outTangent End tangent of the animation
  52541. * @param endValue End value of the animation curve
  52542. * @param inTangent Start tangent of the animation curve
  52543. * @param gradient Scalar amount to interpolate
  52544. * @returns InterpolatedVector3 value
  52545. */
  52546. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52547. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52548. };
  52549. /**
  52550. * Interpolates a Vector2 linearly
  52551. * @param startValue Start value of the animation curve
  52552. * @param endValue End value of the animation curve
  52553. * @param gradient Scalar amount to interpolate
  52554. * @returns Interpolated Vector2 value
  52555. */
  52556. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  52557. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  52558. };
  52559. /**
  52560. * Interpolates a Vector2 cubically
  52561. * @param startValue Start value of the animation curve
  52562. * @param outTangent End tangent of the animation
  52563. * @param endValue End value of the animation curve
  52564. * @param inTangent Start tangent of the animation curve
  52565. * @param gradient Scalar amount to interpolate
  52566. * @returns Interpolated Vector2 value
  52567. */
  52568. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52569. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52570. };
  52571. /**
  52572. * Interpolates a size linearly
  52573. * @param startValue Start value of the animation curve
  52574. * @param endValue End value of the animation curve
  52575. * @param gradient Scalar amount to interpolate
  52576. * @returns Interpolated Size value
  52577. */
  52578. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  52579. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  52580. };
  52581. /**
  52582. * Interpolates a Color3 linearly
  52583. * @param startValue Start value of the animation curve
  52584. * @param endValue End value of the animation curve
  52585. * @param gradient Scalar amount to interpolate
  52586. * @returns Interpolated Color3 value
  52587. */
  52588. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  52589. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  52590. };
  52591. /**
  52592. * @hidden Internal use only
  52593. */
  52594. Animation.prototype._getKeyValue = function (value) {
  52595. if (typeof value === "function") {
  52596. return value();
  52597. }
  52598. return value;
  52599. };
  52600. /**
  52601. * @hidden Internal use only
  52602. */
  52603. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  52604. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  52605. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  52606. }
  52607. var keys = this.getKeys();
  52608. // Try to get a hash to find the right key
  52609. 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));
  52610. if (keys[startKeyIndex].frame >= currentFrame) {
  52611. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  52612. startKeyIndex--;
  52613. }
  52614. }
  52615. for (var key = startKeyIndex; key < keys.length; key++) {
  52616. var endKey = keys[key + 1];
  52617. if (endKey.frame >= currentFrame) {
  52618. var startKey = keys[key];
  52619. var startValue = this._getKeyValue(startKey.value);
  52620. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  52621. return startValue;
  52622. }
  52623. var endValue = this._getKeyValue(endKey.value);
  52624. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  52625. var frameDelta = endKey.frame - startKey.frame;
  52626. // gradient : percent of currentFrame between the frame inf and the frame sup
  52627. var gradient = (currentFrame - startKey.frame) / frameDelta;
  52628. // check for easingFunction and correction of gradient
  52629. var easingFunction = this.getEasingFunction();
  52630. if (easingFunction != null) {
  52631. gradient = easingFunction.ease(gradient);
  52632. }
  52633. switch (this.dataType) {
  52634. // Float
  52635. case Animation.ANIMATIONTYPE_FLOAT:
  52636. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  52637. switch (loopMode) {
  52638. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52639. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52640. return floatValue;
  52641. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52642. return offsetValue * repeatCount + floatValue;
  52643. }
  52644. break;
  52645. // Quaternion
  52646. case Animation.ANIMATIONTYPE_QUATERNION:
  52647. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  52648. switch (loopMode) {
  52649. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52650. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52651. return quatValue;
  52652. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52653. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  52654. }
  52655. return quatValue;
  52656. // Vector3
  52657. case Animation.ANIMATIONTYPE_VECTOR3:
  52658. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52659. switch (loopMode) {
  52660. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52661. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52662. return vec3Value;
  52663. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52664. return vec3Value.add(offsetValue.scale(repeatCount));
  52665. }
  52666. // Vector2
  52667. case Animation.ANIMATIONTYPE_VECTOR2:
  52668. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52669. switch (loopMode) {
  52670. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52671. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52672. return vec2Value;
  52673. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52674. return vec2Value.add(offsetValue.scale(repeatCount));
  52675. }
  52676. // Size
  52677. case Animation.ANIMATIONTYPE_SIZE:
  52678. switch (loopMode) {
  52679. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52680. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52681. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52682. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52683. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52684. }
  52685. // Color3
  52686. case Animation.ANIMATIONTYPE_COLOR3:
  52687. switch (loopMode) {
  52688. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52689. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52690. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52691. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52692. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52693. }
  52694. // Matrix
  52695. case Animation.ANIMATIONTYPE_MATRIX:
  52696. switch (loopMode) {
  52697. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52698. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52699. if (Animation.AllowMatricesInterpolation) {
  52700. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52701. }
  52702. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52703. return startValue;
  52704. }
  52705. default:
  52706. break;
  52707. }
  52708. break;
  52709. }
  52710. }
  52711. return this._getKeyValue(keys[keys.length - 1].value);
  52712. };
  52713. /**
  52714. * Defines the function to use to interpolate matrices
  52715. * @param startValue defines the start matrix
  52716. * @param endValue defines the end matrix
  52717. * @param gradient defines the gradient between both matrices
  52718. * @param result defines an optional target matrix where to store the interpolation
  52719. * @returns the interpolated matrix
  52720. */
  52721. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52722. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52723. if (result) {
  52724. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52725. return result;
  52726. }
  52727. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52728. }
  52729. if (result) {
  52730. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52731. return result;
  52732. }
  52733. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52734. };
  52735. /**
  52736. * Makes a copy of the animation
  52737. * @returns Cloned animation
  52738. */
  52739. Animation.prototype.clone = function () {
  52740. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52741. clone.enableBlending = this.enableBlending;
  52742. clone.blendingSpeed = this.blendingSpeed;
  52743. if (this._keys) {
  52744. clone.setKeys(this._keys);
  52745. }
  52746. if (this._ranges) {
  52747. clone._ranges = {};
  52748. for (var name in this._ranges) {
  52749. var range = this._ranges[name];
  52750. if (!range) {
  52751. continue;
  52752. }
  52753. clone._ranges[name] = range.clone();
  52754. }
  52755. }
  52756. return clone;
  52757. };
  52758. /**
  52759. * Sets the key frames of the animation
  52760. * @param values The animation key frames to set
  52761. */
  52762. Animation.prototype.setKeys = function (values) {
  52763. this._keys = values.slice(0);
  52764. };
  52765. /**
  52766. * Serializes the animation to an object
  52767. * @returns Serialized object
  52768. */
  52769. Animation.prototype.serialize = function () {
  52770. var serializationObject = {};
  52771. serializationObject.name = this.name;
  52772. serializationObject.property = this.targetProperty;
  52773. serializationObject.framePerSecond = this.framePerSecond;
  52774. serializationObject.dataType = this.dataType;
  52775. serializationObject.loopBehavior = this.loopMode;
  52776. serializationObject.enableBlending = this.enableBlending;
  52777. serializationObject.blendingSpeed = this.blendingSpeed;
  52778. var dataType = this.dataType;
  52779. serializationObject.keys = [];
  52780. var keys = this.getKeys();
  52781. for (var index = 0; index < keys.length; index++) {
  52782. var animationKey = keys[index];
  52783. var key = {};
  52784. key.frame = animationKey.frame;
  52785. switch (dataType) {
  52786. case Animation.ANIMATIONTYPE_FLOAT:
  52787. key.values = [animationKey.value];
  52788. break;
  52789. case Animation.ANIMATIONTYPE_QUATERNION:
  52790. case Animation.ANIMATIONTYPE_MATRIX:
  52791. case Animation.ANIMATIONTYPE_VECTOR3:
  52792. case Animation.ANIMATIONTYPE_COLOR3:
  52793. key.values = animationKey.value.asArray();
  52794. break;
  52795. }
  52796. serializationObject.keys.push(key);
  52797. }
  52798. serializationObject.ranges = [];
  52799. for (var name in this._ranges) {
  52800. var source = this._ranges[name];
  52801. if (!source) {
  52802. continue;
  52803. }
  52804. var range = {};
  52805. range.name = name;
  52806. range.from = source.from;
  52807. range.to = source.to;
  52808. serializationObject.ranges.push(range);
  52809. }
  52810. return serializationObject;
  52811. };
  52812. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52813. /**
  52814. * Get the float animation type
  52815. */
  52816. get: function () {
  52817. return Animation._ANIMATIONTYPE_FLOAT;
  52818. },
  52819. enumerable: true,
  52820. configurable: true
  52821. });
  52822. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52823. /**
  52824. * Get the Vector3 animation type
  52825. */
  52826. get: function () {
  52827. return Animation._ANIMATIONTYPE_VECTOR3;
  52828. },
  52829. enumerable: true,
  52830. configurable: true
  52831. });
  52832. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52833. /**
  52834. * Get the Vector2 animation type
  52835. */
  52836. get: function () {
  52837. return Animation._ANIMATIONTYPE_VECTOR2;
  52838. },
  52839. enumerable: true,
  52840. configurable: true
  52841. });
  52842. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52843. /**
  52844. * Get the Size animation type
  52845. */
  52846. get: function () {
  52847. return Animation._ANIMATIONTYPE_SIZE;
  52848. },
  52849. enumerable: true,
  52850. configurable: true
  52851. });
  52852. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52853. /**
  52854. * Get the Quaternion animation type
  52855. */
  52856. get: function () {
  52857. return Animation._ANIMATIONTYPE_QUATERNION;
  52858. },
  52859. enumerable: true,
  52860. configurable: true
  52861. });
  52862. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52863. /**
  52864. * Get the Matrix animation type
  52865. */
  52866. get: function () {
  52867. return Animation._ANIMATIONTYPE_MATRIX;
  52868. },
  52869. enumerable: true,
  52870. configurable: true
  52871. });
  52872. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52873. /**
  52874. * Get the Color3 animation type
  52875. */
  52876. get: function () {
  52877. return Animation._ANIMATIONTYPE_COLOR3;
  52878. },
  52879. enumerable: true,
  52880. configurable: true
  52881. });
  52882. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52883. /**
  52884. * Get the Relative Loop Mode
  52885. */
  52886. get: function () {
  52887. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52888. },
  52889. enumerable: true,
  52890. configurable: true
  52891. });
  52892. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52893. /**
  52894. * Get the Cycle Loop Mode
  52895. */
  52896. get: function () {
  52897. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52898. },
  52899. enumerable: true,
  52900. configurable: true
  52901. });
  52902. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52903. /**
  52904. * Get the Constant Loop Mode
  52905. */
  52906. get: function () {
  52907. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52908. },
  52909. enumerable: true,
  52910. configurable: true
  52911. });
  52912. /** @hidden */
  52913. Animation._UniversalLerp = function (left, right, amount) {
  52914. var constructor = left.constructor;
  52915. if (constructor.Lerp) { // Lerp supported
  52916. return constructor.Lerp(left, right, amount);
  52917. }
  52918. else if (constructor.Slerp) { // Slerp supported
  52919. return constructor.Slerp(left, right, amount);
  52920. }
  52921. else if (left.toFixed) { // Number
  52922. return left * (1.0 - amount) + amount * right;
  52923. }
  52924. else { // Blending not supported
  52925. return right;
  52926. }
  52927. };
  52928. /**
  52929. * Parses an animation object and creates an animation
  52930. * @param parsedAnimation Parsed animation object
  52931. * @returns Animation object
  52932. */
  52933. Animation.Parse = function (parsedAnimation) {
  52934. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52935. var dataType = parsedAnimation.dataType;
  52936. var keys = [];
  52937. var data;
  52938. var index;
  52939. if (parsedAnimation.enableBlending) {
  52940. animation.enableBlending = parsedAnimation.enableBlending;
  52941. }
  52942. if (parsedAnimation.blendingSpeed) {
  52943. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52944. }
  52945. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52946. var key = parsedAnimation.keys[index];
  52947. var inTangent;
  52948. var outTangent;
  52949. switch (dataType) {
  52950. case Animation.ANIMATIONTYPE_FLOAT:
  52951. data = key.values[0];
  52952. if (key.values.length >= 1) {
  52953. inTangent = key.values[1];
  52954. }
  52955. if (key.values.length >= 2) {
  52956. outTangent = key.values[2];
  52957. }
  52958. break;
  52959. case Animation.ANIMATIONTYPE_QUATERNION:
  52960. data = BABYLON.Quaternion.FromArray(key.values);
  52961. if (key.values.length >= 8) {
  52962. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52963. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52964. inTangent = _inTangent;
  52965. }
  52966. }
  52967. if (key.values.length >= 12) {
  52968. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52969. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52970. outTangent = _outTangent;
  52971. }
  52972. }
  52973. break;
  52974. case Animation.ANIMATIONTYPE_MATRIX:
  52975. data = BABYLON.Matrix.FromArray(key.values);
  52976. break;
  52977. case Animation.ANIMATIONTYPE_COLOR3:
  52978. data = BABYLON.Color3.FromArray(key.values);
  52979. break;
  52980. case Animation.ANIMATIONTYPE_VECTOR3:
  52981. default:
  52982. data = BABYLON.Vector3.FromArray(key.values);
  52983. break;
  52984. }
  52985. var keyData = {};
  52986. keyData.frame = key.frame;
  52987. keyData.value = data;
  52988. if (inTangent != undefined) {
  52989. keyData.inTangent = inTangent;
  52990. }
  52991. if (outTangent != undefined) {
  52992. keyData.outTangent = outTangent;
  52993. }
  52994. keys.push(keyData);
  52995. }
  52996. animation.setKeys(keys);
  52997. if (parsedAnimation.ranges) {
  52998. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  52999. data = parsedAnimation.ranges[index];
  53000. animation.createRange(data.name, data.from, data.to);
  53001. }
  53002. }
  53003. return animation;
  53004. };
  53005. /**
  53006. * Appends the serialized animations from the source animations
  53007. * @param source Source containing the animations
  53008. * @param destination Target to store the animations
  53009. */
  53010. Animation.AppendSerializedAnimations = function (source, destination) {
  53011. if (source.animations) {
  53012. destination.animations = [];
  53013. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  53014. var animation = source.animations[animationIndex];
  53015. destination.animations.push(animation.serialize());
  53016. }
  53017. }
  53018. };
  53019. /**
  53020. * Use matrix interpolation instead of using direct key value when animating matrices
  53021. */
  53022. Animation.AllowMatricesInterpolation = false;
  53023. /**
  53024. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  53025. */
  53026. Animation.AllowMatrixDecomposeForInterpolation = true;
  53027. // Statics
  53028. /**
  53029. * Float animation type
  53030. */
  53031. Animation._ANIMATIONTYPE_FLOAT = 0;
  53032. /**
  53033. * Vector3 animation type
  53034. */
  53035. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  53036. /**
  53037. * Quaternion animation type
  53038. */
  53039. Animation._ANIMATIONTYPE_QUATERNION = 2;
  53040. /**
  53041. * Matrix animation type
  53042. */
  53043. Animation._ANIMATIONTYPE_MATRIX = 3;
  53044. /**
  53045. * Color3 animation type
  53046. */
  53047. Animation._ANIMATIONTYPE_COLOR3 = 4;
  53048. /**
  53049. * Vector2 animation type
  53050. */
  53051. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  53052. /**
  53053. * Size animation type
  53054. */
  53055. Animation._ANIMATIONTYPE_SIZE = 6;
  53056. /**
  53057. * Relative Loop Mode
  53058. */
  53059. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  53060. /**
  53061. * Cycle Loop Mode
  53062. */
  53063. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  53064. /**
  53065. * Constant Loop Mode
  53066. */
  53067. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  53068. return Animation;
  53069. }());
  53070. BABYLON.Animation = Animation;
  53071. })(BABYLON || (BABYLON = {}));
  53072. //# sourceMappingURL=babylon.animation.js.map
  53073. var BABYLON;
  53074. (function (BABYLON) {
  53075. /**
  53076. * This class defines the direct association between an animation and a target
  53077. */
  53078. var TargetedAnimation = /** @class */ (function () {
  53079. function TargetedAnimation() {
  53080. }
  53081. return TargetedAnimation;
  53082. }());
  53083. BABYLON.TargetedAnimation = TargetedAnimation;
  53084. /**
  53085. * Use this class to create coordinated animations on multiple targets
  53086. */
  53087. var AnimationGroup = /** @class */ (function () {
  53088. /**
  53089. * Instantiates a new Animation Group.
  53090. * This helps managing several animations at once.
  53091. * @see http://doc.babylonjs.com/how_to/group
  53092. * @param name Defines the name of the group
  53093. * @param scene Defines the scene the group belongs to
  53094. */
  53095. function AnimationGroup(
  53096. /** The name of the animation group */
  53097. name, scene) {
  53098. if (scene === void 0) { scene = null; }
  53099. this.name = name;
  53100. this._targetedAnimations = new Array();
  53101. this._animatables = new Array();
  53102. this._from = Number.MAX_VALUE;
  53103. this._to = -Number.MAX_VALUE;
  53104. this._speedRatio = 1;
  53105. /**
  53106. * This observable will notify when one animation have ended.
  53107. */
  53108. this.onAnimationEndObservable = new BABYLON.Observable();
  53109. /**
  53110. * This observable will notify when all animations have ended.
  53111. */
  53112. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  53113. /**
  53114. * This observable will notify when all animations have paused.
  53115. */
  53116. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  53117. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53118. this._scene.animationGroups.push(this);
  53119. }
  53120. Object.defineProperty(AnimationGroup.prototype, "from", {
  53121. /**
  53122. * Gets the first frame
  53123. */
  53124. get: function () {
  53125. return this._from;
  53126. },
  53127. enumerable: true,
  53128. configurable: true
  53129. });
  53130. Object.defineProperty(AnimationGroup.prototype, "to", {
  53131. /**
  53132. * Gets the last frame
  53133. */
  53134. get: function () {
  53135. return this._to;
  53136. },
  53137. enumerable: true,
  53138. configurable: true
  53139. });
  53140. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  53141. /**
  53142. * Define if the animations are started
  53143. */
  53144. get: function () {
  53145. return this._isStarted;
  53146. },
  53147. enumerable: true,
  53148. configurable: true
  53149. });
  53150. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  53151. /**
  53152. * Gets or sets the speed ratio to use for all animations
  53153. */
  53154. get: function () {
  53155. return this._speedRatio;
  53156. },
  53157. /**
  53158. * Gets or sets the speed ratio to use for all animations
  53159. */
  53160. set: function (value) {
  53161. if (this._speedRatio === value) {
  53162. return;
  53163. }
  53164. this._speedRatio = value;
  53165. for (var index = 0; index < this._animatables.length; index++) {
  53166. var animatable = this._animatables[index];
  53167. animatable.speedRatio = this._speedRatio;
  53168. }
  53169. },
  53170. enumerable: true,
  53171. configurable: true
  53172. });
  53173. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  53174. /**
  53175. * Gets the targeted animations for this animation group
  53176. */
  53177. get: function () {
  53178. return this._targetedAnimations;
  53179. },
  53180. enumerable: true,
  53181. configurable: true
  53182. });
  53183. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  53184. /**
  53185. * returning the list of animatables controlled by this animation group.
  53186. */
  53187. get: function () {
  53188. return this._animatables;
  53189. },
  53190. enumerable: true,
  53191. configurable: true
  53192. });
  53193. /**
  53194. * Add an animation (with its target) in the group
  53195. * @param animation defines the animation we want to add
  53196. * @param target defines the target of the animation
  53197. * @returns the TargetedAnimation object
  53198. */
  53199. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  53200. var targetedAnimation = {
  53201. animation: animation,
  53202. target: target
  53203. };
  53204. var keys = animation.getKeys();
  53205. if (this._from > keys[0].frame) {
  53206. this._from = keys[0].frame;
  53207. }
  53208. if (this._to < keys[keys.length - 1].frame) {
  53209. this._to = keys[keys.length - 1].frame;
  53210. }
  53211. this._targetedAnimations.push(targetedAnimation);
  53212. return targetedAnimation;
  53213. };
  53214. /**
  53215. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  53216. * It can add constant keys at begin or end
  53217. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  53218. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  53219. * @returns the animation group
  53220. */
  53221. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  53222. if (beginFrame === void 0) { beginFrame = null; }
  53223. if (endFrame === void 0) { endFrame = null; }
  53224. if (beginFrame == null) {
  53225. beginFrame = this._from;
  53226. }
  53227. if (endFrame == null) {
  53228. endFrame = this._to;
  53229. }
  53230. for (var index = 0; index < this._targetedAnimations.length; index++) {
  53231. var targetedAnimation = this._targetedAnimations[index];
  53232. var keys = targetedAnimation.animation.getKeys();
  53233. var startKey = keys[0];
  53234. var endKey = keys[keys.length - 1];
  53235. if (startKey.frame > beginFrame) {
  53236. var newKey = {
  53237. frame: beginFrame,
  53238. value: startKey.value,
  53239. inTangent: startKey.inTangent,
  53240. outTangent: startKey.outTangent,
  53241. interpolation: startKey.interpolation
  53242. };
  53243. keys.splice(0, 0, newKey);
  53244. }
  53245. if (endKey.frame < endFrame) {
  53246. var newKey = {
  53247. frame: endFrame,
  53248. value: endKey.value,
  53249. inTangent: endKey.outTangent,
  53250. outTangent: endKey.outTangent,
  53251. interpolation: endKey.interpolation
  53252. };
  53253. keys.push(newKey);
  53254. }
  53255. }
  53256. this._from = beginFrame;
  53257. this._to = endFrame;
  53258. return this;
  53259. };
  53260. /**
  53261. * Start all animations on given targets
  53262. * @param loop defines if animations must loop
  53263. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  53264. * @param from defines the from key (optional)
  53265. * @param to defines the to key (optional)
  53266. * @returns the current animation group
  53267. */
  53268. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  53269. var _this = this;
  53270. if (loop === void 0) { loop = false; }
  53271. if (speedRatio === void 0) { speedRatio = 1; }
  53272. if (this._isStarted || this._targetedAnimations.length === 0) {
  53273. return this;
  53274. }
  53275. var _loop_1 = function (targetedAnimation) {
  53276. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  53277. animatable.onAnimationEnd = function () {
  53278. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  53279. _this._checkAnimationGroupEnded(animatable);
  53280. };
  53281. this_1._animatables.push(animatable);
  53282. };
  53283. var this_1 = this;
  53284. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  53285. var targetedAnimation = _a[_i];
  53286. _loop_1(targetedAnimation);
  53287. }
  53288. this._speedRatio = speedRatio;
  53289. this._isStarted = true;
  53290. return this;
  53291. };
  53292. /**
  53293. * Pause all animations
  53294. * @returns the animation group
  53295. */
  53296. AnimationGroup.prototype.pause = function () {
  53297. if (!this._isStarted) {
  53298. return this;
  53299. }
  53300. for (var index = 0; index < this._animatables.length; index++) {
  53301. var animatable = this._animatables[index];
  53302. animatable.pause();
  53303. }
  53304. this.onAnimationGroupPauseObservable.notifyObservers(this);
  53305. return this;
  53306. };
  53307. /**
  53308. * Play all animations to initial state
  53309. * This function will start() the animations if they were not started or will restart() them if they were paused
  53310. * @param loop defines if animations must loop
  53311. * @returns the animation group
  53312. */
  53313. AnimationGroup.prototype.play = function (loop) {
  53314. // only if all animatables are ready and exist
  53315. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  53316. if (loop !== undefined) {
  53317. for (var index = 0; index < this._animatables.length; index++) {
  53318. var animatable = this._animatables[index];
  53319. animatable.loopAnimation = loop;
  53320. }
  53321. }
  53322. this.restart();
  53323. }
  53324. else {
  53325. this.stop();
  53326. this.start(loop, this._speedRatio);
  53327. }
  53328. return this;
  53329. };
  53330. /**
  53331. * Reset all animations to initial state
  53332. * @returns the animation group
  53333. */
  53334. AnimationGroup.prototype.reset = function () {
  53335. if (!this._isStarted) {
  53336. return this;
  53337. }
  53338. for (var index = 0; index < this._animatables.length; index++) {
  53339. var animatable = this._animatables[index];
  53340. animatable.reset();
  53341. }
  53342. return this;
  53343. };
  53344. /**
  53345. * Restart animations from key 0
  53346. * @returns the animation group
  53347. */
  53348. AnimationGroup.prototype.restart = function () {
  53349. if (!this._isStarted) {
  53350. return this;
  53351. }
  53352. for (var index = 0; index < this._animatables.length; index++) {
  53353. var animatable = this._animatables[index];
  53354. animatable.restart();
  53355. }
  53356. return this;
  53357. };
  53358. /**
  53359. * Stop all animations
  53360. * @returns the animation group
  53361. */
  53362. AnimationGroup.prototype.stop = function () {
  53363. if (!this._isStarted) {
  53364. return this;
  53365. }
  53366. var list = this._animatables.slice();
  53367. for (var index = 0; index < list.length; index++) {
  53368. list[index].stop();
  53369. }
  53370. this._isStarted = false;
  53371. return this;
  53372. };
  53373. /**
  53374. * Set animation weight for all animatables
  53375. * @param weight defines the weight to use
  53376. * @return the animationGroup
  53377. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53378. */
  53379. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  53380. for (var index = 0; index < this._animatables.length; index++) {
  53381. var animatable = this._animatables[index];
  53382. animatable.weight = weight;
  53383. }
  53384. return this;
  53385. };
  53386. /**
  53387. * Synchronize and normalize all animatables with a source animatable
  53388. * @param root defines the root animatable to synchronize with
  53389. * @return the animationGroup
  53390. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53391. */
  53392. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  53393. for (var index = 0; index < this._animatables.length; index++) {
  53394. var animatable = this._animatables[index];
  53395. animatable.syncWith(root);
  53396. }
  53397. return this;
  53398. };
  53399. /**
  53400. * Goes to a specific frame in this animation group
  53401. * @param frame the frame number to go to
  53402. * @return the animationGroup
  53403. */
  53404. AnimationGroup.prototype.goToFrame = function (frame) {
  53405. if (!this._isStarted) {
  53406. return this;
  53407. }
  53408. for (var index = 0; index < this._animatables.length; index++) {
  53409. var animatable = this._animatables[index];
  53410. animatable.goToFrame(frame);
  53411. }
  53412. return this;
  53413. };
  53414. /**
  53415. * Dispose all associated resources
  53416. */
  53417. AnimationGroup.prototype.dispose = function () {
  53418. this._targetedAnimations = [];
  53419. this._animatables = [];
  53420. var index = this._scene.animationGroups.indexOf(this);
  53421. if (index > -1) {
  53422. this._scene.animationGroups.splice(index, 1);
  53423. }
  53424. };
  53425. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  53426. // animatable should be taken out of the array
  53427. var idx = this._animatables.indexOf(animatable);
  53428. if (idx > -1) {
  53429. this._animatables.splice(idx, 1);
  53430. }
  53431. // all animatables were removed? animation group ended!
  53432. if (this._animatables.length === 0) {
  53433. this._isStarted = false;
  53434. this.onAnimationGroupEndObservable.notifyObservers(this);
  53435. }
  53436. };
  53437. // Statics
  53438. /**
  53439. * Returns a new AnimationGroup object parsed from the source provided.
  53440. * @param parsedAnimationGroup defines the source
  53441. * @param scene defines the scene that will receive the animationGroup
  53442. * @returns a new AnimationGroup
  53443. */
  53444. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  53445. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  53446. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  53447. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  53448. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  53449. var id = targetedAnimation.targetId;
  53450. var targetNode = scene.getNodeByID(id);
  53451. if (targetNode != null) {
  53452. animationGroup.addTargetedAnimation(animation, targetNode);
  53453. }
  53454. }
  53455. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  53456. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  53457. }
  53458. return animationGroup;
  53459. };
  53460. /**
  53461. * Returns the string "AnimationGroup"
  53462. * @returns "AnimationGroup"
  53463. */
  53464. AnimationGroup.prototype.getClassName = function () {
  53465. return "AnimationGroup";
  53466. };
  53467. /**
  53468. * Creates a detailled string about the object
  53469. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  53470. * @returns a string representing the object
  53471. */
  53472. AnimationGroup.prototype.toString = function (fullDetails) {
  53473. var ret = "Name: " + this.name;
  53474. ret += ", type: " + this.getClassName();
  53475. if (fullDetails) {
  53476. ret += ", from: " + this._from;
  53477. ret += ", to: " + this._to;
  53478. ret += ", isStarted: " + this._isStarted;
  53479. ret += ", speedRatio: " + this._speedRatio;
  53480. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  53481. ret += ", animatables length: " + this._animatables;
  53482. }
  53483. return ret;
  53484. };
  53485. return AnimationGroup;
  53486. }());
  53487. BABYLON.AnimationGroup = AnimationGroup;
  53488. })(BABYLON || (BABYLON = {}));
  53489. //# sourceMappingURL=babylon.animationGroup.js.map
  53490. var BABYLON;
  53491. (function (BABYLON) {
  53492. // Static values to help the garbage collector
  53493. // Quaternion
  53494. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  53495. // Vector3
  53496. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  53497. // Vector2
  53498. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  53499. // Size
  53500. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  53501. // Color3
  53502. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  53503. /**
  53504. * Defines a runtime animation
  53505. */
  53506. var RuntimeAnimation = /** @class */ (function () {
  53507. /**
  53508. * Create a new RuntimeAnimation object
  53509. * @param target defines the target of the animation
  53510. * @param animation defines the source animation object
  53511. * @param scene defines the hosting scene
  53512. * @param host defines the initiating Animatable
  53513. */
  53514. function RuntimeAnimation(target, animation, scene, host) {
  53515. var _this = this;
  53516. this._events = new Array();
  53517. /**
  53518. * The current frame of the runtime animation
  53519. */
  53520. this._currentFrame = 0;
  53521. /**
  53522. * The original value of the runtime animation
  53523. */
  53524. this._originalValue = new Array();
  53525. /**
  53526. * The offsets cache of the runtime animation
  53527. */
  53528. this._offsetsCache = {};
  53529. /**
  53530. * The high limits cache of the runtime animation
  53531. */
  53532. this._highLimitsCache = {};
  53533. /**
  53534. * Specifies if the runtime animation has been stopped
  53535. */
  53536. this._stopped = false;
  53537. /**
  53538. * The blending factor of the runtime animation
  53539. */
  53540. this._blendingFactor = 0;
  53541. /**
  53542. * The target path of the runtime animation
  53543. */
  53544. this._targetPath = "";
  53545. /**
  53546. * The weight of the runtime animation
  53547. */
  53548. this._weight = 1.0;
  53549. /**
  53550. * The ratio offset of the runtime animation
  53551. */
  53552. this._ratioOffset = 0;
  53553. /**
  53554. * The previous delay of the runtime animation
  53555. */
  53556. this._previousDelay = 0;
  53557. /**
  53558. * The previous ratio of the runtime animation
  53559. */
  53560. this._previousRatio = 0;
  53561. this._animation = animation;
  53562. this._target = target;
  53563. this._scene = scene;
  53564. this._host = host;
  53565. animation._runtimeAnimations.push(this);
  53566. // Cloning events locally
  53567. var events = animation.getEvents();
  53568. if (events && events.length > 0) {
  53569. events.forEach(function (e) {
  53570. _this._events.push(e._clone());
  53571. });
  53572. }
  53573. }
  53574. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  53575. /**
  53576. * Gets the current frame of the runtime animation
  53577. */
  53578. get: function () {
  53579. return this._currentFrame;
  53580. },
  53581. enumerable: true,
  53582. configurable: true
  53583. });
  53584. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  53585. /**
  53586. * Gets the weight of the runtime animation
  53587. */
  53588. get: function () {
  53589. return this._weight;
  53590. },
  53591. enumerable: true,
  53592. configurable: true
  53593. });
  53594. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  53595. /**
  53596. * Gets the current value of the runtime animation
  53597. */
  53598. get: function () {
  53599. return this._currentValue;
  53600. },
  53601. enumerable: true,
  53602. configurable: true
  53603. });
  53604. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  53605. /**
  53606. * Gets the target path of the runtime animation
  53607. */
  53608. get: function () {
  53609. return this._targetPath;
  53610. },
  53611. enumerable: true,
  53612. configurable: true
  53613. });
  53614. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  53615. /**
  53616. * Gets the actual target of the runtime animation
  53617. */
  53618. get: function () {
  53619. return this._activeTarget;
  53620. },
  53621. enumerable: true,
  53622. configurable: true
  53623. });
  53624. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  53625. /**
  53626. * Gets the animation from the runtime animation
  53627. */
  53628. get: function () {
  53629. return this._animation;
  53630. },
  53631. enumerable: true,
  53632. configurable: true
  53633. });
  53634. /**
  53635. * Resets the runtime animation to the beginning
  53636. * @param restoreOriginal defines whether to restore the target property to the original value
  53637. */
  53638. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  53639. if (restoreOriginal === void 0) { restoreOriginal = false; }
  53640. if (restoreOriginal) {
  53641. if (this._target instanceof Array) {
  53642. var index = 0;
  53643. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53644. var target = _a[_i];
  53645. if (this._originalValue[index] !== undefined) {
  53646. this._setValue(target, this._originalValue[index], -1);
  53647. }
  53648. index++;
  53649. }
  53650. }
  53651. else {
  53652. if (this._originalValue[0] !== undefined) {
  53653. this._setValue(this._target, this._originalValue[0], -1);
  53654. }
  53655. }
  53656. }
  53657. this._offsetsCache = {};
  53658. this._highLimitsCache = {};
  53659. this._currentFrame = 0;
  53660. this._blendingFactor = 0;
  53661. this._originalValue = new Array();
  53662. // Events
  53663. for (var index = 0; index < this._events.length; index++) {
  53664. this._events[index].isDone = false;
  53665. }
  53666. };
  53667. /**
  53668. * Specifies if the runtime animation is stopped
  53669. * @returns Boolean specifying if the runtime animation is stopped
  53670. */
  53671. RuntimeAnimation.prototype.isStopped = function () {
  53672. return this._stopped;
  53673. };
  53674. /**
  53675. * Disposes of the runtime animation
  53676. */
  53677. RuntimeAnimation.prototype.dispose = function () {
  53678. var index = this._animation.runtimeAnimations.indexOf(this);
  53679. if (index > -1) {
  53680. this._animation.runtimeAnimations.splice(index, 1);
  53681. }
  53682. };
  53683. /**
  53684. * Interpolates the animation from the current frame
  53685. * @param currentFrame The frame to interpolate the animation to
  53686. * @param repeatCount The number of times that the animation should loop
  53687. * @param loopMode The type of looping mode to use
  53688. * @param offsetValue Animation offset value
  53689. * @param highLimitValue The high limit value
  53690. * @returns The interpolated value
  53691. */
  53692. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53693. this._currentFrame = currentFrame;
  53694. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53695. this._workValue = BABYLON.Matrix.Zero();
  53696. }
  53697. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53698. };
  53699. /**
  53700. * Apply the interpolated value to the target
  53701. * @param currentValue defines the value computed by the animation
  53702. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53703. */
  53704. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53705. if (weight === void 0) { weight = 1.0; }
  53706. if (this._target instanceof Array) {
  53707. var index = 0;
  53708. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53709. var target = _a[_i];
  53710. this._setValue(target, currentValue, weight, index);
  53711. index++;
  53712. }
  53713. }
  53714. else {
  53715. this._setValue(this._target, currentValue, weight);
  53716. }
  53717. };
  53718. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53719. if (targetIndex === void 0) { targetIndex = 0; }
  53720. // Set value
  53721. var path;
  53722. var destination;
  53723. var targetPropertyPath = this._animation.targetPropertyPath;
  53724. if (targetPropertyPath.length > 1) {
  53725. var property = target[targetPropertyPath[0]];
  53726. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53727. property = property[targetPropertyPath[index]];
  53728. }
  53729. path = targetPropertyPath[targetPropertyPath.length - 1];
  53730. destination = property;
  53731. }
  53732. else {
  53733. path = targetPropertyPath[0];
  53734. destination = target;
  53735. }
  53736. this._targetPath = path;
  53737. this._activeTarget = destination;
  53738. this._weight = weight;
  53739. if (this._originalValue[targetIndex] === undefined) {
  53740. var originalValue = void 0;
  53741. if (destination.getRestPose && path === "_matrix") { // For bones
  53742. originalValue = destination.getRestPose();
  53743. }
  53744. else {
  53745. originalValue = destination[path];
  53746. }
  53747. if (originalValue && originalValue.clone) {
  53748. this._originalValue[targetIndex] = originalValue.clone();
  53749. }
  53750. else {
  53751. this._originalValue[targetIndex] = originalValue;
  53752. }
  53753. }
  53754. // Blending
  53755. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53756. if (enableBlending && this._blendingFactor <= 1.0) {
  53757. if (!this._originalBlendValue) {
  53758. var originalValue = destination[path];
  53759. if (originalValue.clone) {
  53760. this._originalBlendValue = originalValue.clone();
  53761. }
  53762. else {
  53763. this._originalBlendValue = originalValue;
  53764. }
  53765. }
  53766. if (this._originalBlendValue.m) { // Matrix
  53767. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53768. if (this._currentValue) {
  53769. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53770. }
  53771. else {
  53772. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53773. }
  53774. }
  53775. else {
  53776. if (this._currentValue) {
  53777. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53778. }
  53779. else {
  53780. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53781. }
  53782. }
  53783. }
  53784. else {
  53785. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53786. }
  53787. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53788. this._blendingFactor += blendingSpeed;
  53789. }
  53790. else {
  53791. this._currentValue = currentValue;
  53792. }
  53793. if (weight !== -1.0) {
  53794. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53795. }
  53796. else {
  53797. destination[path] = this._currentValue;
  53798. }
  53799. if (target.markAsDirty) {
  53800. target.markAsDirty(this._animation.targetProperty);
  53801. }
  53802. };
  53803. /**
  53804. * Gets the loop pmode of the runtime animation
  53805. * @returns Loop Mode
  53806. */
  53807. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53808. if (this._target && this._target.animationPropertiesOverride) {
  53809. return this._target.animationPropertiesOverride.loopMode;
  53810. }
  53811. return this._animation.loopMode;
  53812. };
  53813. /**
  53814. * Move the current animation to a given frame
  53815. * @param frame defines the frame to move to
  53816. */
  53817. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53818. var keys = this._animation.getKeys();
  53819. if (frame < keys[0].frame) {
  53820. frame = keys[0].frame;
  53821. }
  53822. else if (frame > keys[keys.length - 1].frame) {
  53823. frame = keys[keys.length - 1].frame;
  53824. }
  53825. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53826. this.setValue(currentValue, -1);
  53827. };
  53828. /**
  53829. * @hidden Internal use only
  53830. */
  53831. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53832. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53833. this._ratioOffset = this._previousRatio - newRatio;
  53834. };
  53835. /**
  53836. * Execute the current animation
  53837. * @param delay defines the delay to add to the current frame
  53838. * @param from defines the lower bound of the animation range
  53839. * @param to defines the upper bound of the animation range
  53840. * @param loop defines if the current animation must loop
  53841. * @param speedRatio defines the current speed ratio
  53842. * @param weight defines the weight of the animation (default is -1 so no weight)
  53843. * @returns a boolean indicating if the animation is running
  53844. */
  53845. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53846. if (weight === void 0) { weight = -1.0; }
  53847. var targetPropertyPath = this._animation.targetPropertyPath;
  53848. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53849. this._stopped = true;
  53850. return false;
  53851. }
  53852. var returnValue = true;
  53853. var keys = this._animation.getKeys();
  53854. // Adding a start key at frame 0 if missing
  53855. if (keys[0].frame !== 0) {
  53856. var newKey = { frame: 0, value: keys[0].value };
  53857. keys.splice(0, 0, newKey);
  53858. }
  53859. // Adding a duplicate key when there is only one key at frame zero
  53860. else if (keys.length === 1) {
  53861. var newKey = { frame: 0.001, value: keys[0].value };
  53862. keys.push(newKey);
  53863. }
  53864. // Check limits
  53865. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53866. from = keys[0].frame;
  53867. }
  53868. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53869. to = keys[keys.length - 1].frame;
  53870. }
  53871. //to and from cannot be the same key
  53872. if (from === to) {
  53873. if (from > keys[0].frame) {
  53874. from--;
  53875. }
  53876. else if (to < keys[keys.length - 1].frame) {
  53877. to++;
  53878. }
  53879. }
  53880. // Compute ratio
  53881. var range = to - from;
  53882. var offsetValue;
  53883. // ratio represents the frame delta between from and to
  53884. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53885. var highLimitValue = 0;
  53886. this._previousDelay = delay;
  53887. this._previousRatio = ratio;
  53888. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53889. returnValue = false;
  53890. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53891. }
  53892. else {
  53893. // Get max value if required
  53894. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53895. var keyOffset = to.toString() + from.toString();
  53896. if (!this._offsetsCache[keyOffset]) {
  53897. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53898. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53899. switch (this._animation.dataType) {
  53900. // Float
  53901. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53902. this._offsetsCache[keyOffset] = toValue - fromValue;
  53903. break;
  53904. // Quaternion
  53905. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53906. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53907. break;
  53908. // Vector3
  53909. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53910. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53911. // Vector2
  53912. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53913. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53914. // Size
  53915. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53916. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53917. // Color3
  53918. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53919. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53920. default:
  53921. break;
  53922. }
  53923. this._highLimitsCache[keyOffset] = toValue;
  53924. }
  53925. highLimitValue = this._highLimitsCache[keyOffset];
  53926. offsetValue = this._offsetsCache[keyOffset];
  53927. }
  53928. }
  53929. if (offsetValue === undefined) {
  53930. switch (this._animation.dataType) {
  53931. // Float
  53932. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53933. offsetValue = 0;
  53934. break;
  53935. // Quaternion
  53936. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53937. offsetValue = _staticOffsetValueQuaternion;
  53938. break;
  53939. // Vector3
  53940. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53941. offsetValue = _staticOffsetValueVector3;
  53942. break;
  53943. // Vector2
  53944. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53945. offsetValue = _staticOffsetValueVector2;
  53946. break;
  53947. // Size
  53948. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53949. offsetValue = _staticOffsetValueSize;
  53950. break;
  53951. // Color3
  53952. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53953. offsetValue = _staticOffsetValueColor3;
  53954. }
  53955. }
  53956. // Compute value
  53957. var repeatCount = (ratio / range) >> 0;
  53958. var currentFrame = returnValue ? from + ratio % range : to;
  53959. // Need to normalize?
  53960. if (this._host && this._host.syncRoot) {
  53961. var syncRoot = this._host.syncRoot;
  53962. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53963. currentFrame = from + (to - from) * hostNormalizedFrame;
  53964. }
  53965. // Reset events if looping
  53966. var events = this._events;
  53967. if (range > 0 && this.currentFrame > currentFrame ||
  53968. range < 0 && this.currentFrame < currentFrame) {
  53969. // Need to reset animation events
  53970. for (var index = 0; index < events.length; index++) {
  53971. if (!events[index].onlyOnce) {
  53972. // reset event, the animation is looping
  53973. events[index].isDone = false;
  53974. }
  53975. }
  53976. }
  53977. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53978. // Set value
  53979. this.setValue(currentValue, weight);
  53980. // Check events
  53981. for (var index = 0; index < events.length; index++) {
  53982. // Make sure current frame has passed event frame and that event frame is within the current range
  53983. // Also, handle both forward and reverse animations
  53984. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53985. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53986. var event = events[index];
  53987. if (!event.isDone) {
  53988. // If event should be done only once, remove it.
  53989. if (event.onlyOnce) {
  53990. events.splice(index, 1);
  53991. index--;
  53992. }
  53993. event.isDone = true;
  53994. event.action(currentFrame);
  53995. } // Don't do anything if the event has already be done.
  53996. }
  53997. }
  53998. if (!returnValue) {
  53999. this._stopped = true;
  54000. }
  54001. return returnValue;
  54002. };
  54003. return RuntimeAnimation;
  54004. }());
  54005. BABYLON.RuntimeAnimation = RuntimeAnimation;
  54006. })(BABYLON || (BABYLON = {}));
  54007. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  54008. var BABYLON;
  54009. (function (BABYLON) {
  54010. /**
  54011. * Class used to store an actual running animation
  54012. */
  54013. var Animatable = /** @class */ (function () {
  54014. /**
  54015. * Creates a new Animatable
  54016. * @param scene defines the hosting scene
  54017. * @param target defines the target object
  54018. * @param fromFrame defines the starting frame number (default is 0)
  54019. * @param toFrame defines the ending frame number (default is 100)
  54020. * @param loopAnimation defines if the animation must loop (default is false)
  54021. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  54022. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  54023. * @param animations defines a group of animation to add to the new Animatable
  54024. */
  54025. function Animatable(scene,
  54026. /** defines the target object */
  54027. target,
  54028. /** defines the starting frame number (default is 0) */
  54029. fromFrame,
  54030. /** defines the ending frame number (default is 100) */
  54031. toFrame,
  54032. /** defines if the animation must loop (default is false) */
  54033. loopAnimation, speedRatio,
  54034. /** defines a callback to call when animation ends if it is not looping */
  54035. onAnimationEnd, animations) {
  54036. if (fromFrame === void 0) { fromFrame = 0; }
  54037. if (toFrame === void 0) { toFrame = 100; }
  54038. if (loopAnimation === void 0) { loopAnimation = false; }
  54039. if (speedRatio === void 0) { speedRatio = 1.0; }
  54040. this.target = target;
  54041. this.fromFrame = fromFrame;
  54042. this.toFrame = toFrame;
  54043. this.loopAnimation = loopAnimation;
  54044. this.onAnimationEnd = onAnimationEnd;
  54045. this._localDelayOffset = null;
  54046. this._pausedDelay = null;
  54047. this._runtimeAnimations = new Array();
  54048. this._paused = false;
  54049. this._speedRatio = 1;
  54050. this._weight = -1.0;
  54051. /**
  54052. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  54053. * This will only apply for non looping animation (default is true)
  54054. */
  54055. this.disposeOnEnd = true;
  54056. /**
  54057. * Gets a boolean indicating if the animation has started
  54058. */
  54059. this.animationStarted = false;
  54060. /**
  54061. * Observer raised when the animation ends
  54062. */
  54063. this.onAnimationEndObservable = new BABYLON.Observable();
  54064. this._scene = scene;
  54065. if (animations) {
  54066. this.appendAnimations(target, animations);
  54067. }
  54068. this._speedRatio = speedRatio;
  54069. scene._activeAnimatables.push(this);
  54070. }
  54071. Object.defineProperty(Animatable.prototype, "syncRoot", {
  54072. /**
  54073. * Gets the root Animatable used to synchronize and normalize animations
  54074. */
  54075. get: function () {
  54076. return this._syncRoot;
  54077. },
  54078. enumerable: true,
  54079. configurable: true
  54080. });
  54081. Object.defineProperty(Animatable.prototype, "masterFrame", {
  54082. /**
  54083. * Gets the current frame of the first RuntimeAnimation
  54084. * Used to synchronize Animatables
  54085. */
  54086. get: function () {
  54087. if (this._runtimeAnimations.length === 0) {
  54088. return 0;
  54089. }
  54090. return this._runtimeAnimations[0].currentFrame;
  54091. },
  54092. enumerable: true,
  54093. configurable: true
  54094. });
  54095. Object.defineProperty(Animatable.prototype, "weight", {
  54096. /**
  54097. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  54098. */
  54099. get: function () {
  54100. return this._weight;
  54101. },
  54102. set: function (value) {
  54103. if (value === -1) { // -1 is ok and means no weight
  54104. this._weight = -1;
  54105. return;
  54106. }
  54107. // Else weight must be in [0, 1] range
  54108. this._weight = Math.min(Math.max(value, 0), 1.0);
  54109. },
  54110. enumerable: true,
  54111. configurable: true
  54112. });
  54113. Object.defineProperty(Animatable.prototype, "speedRatio", {
  54114. /**
  54115. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  54116. */
  54117. get: function () {
  54118. return this._speedRatio;
  54119. },
  54120. set: function (value) {
  54121. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  54122. var animation = this._runtimeAnimations[index];
  54123. animation._prepareForSpeedRatioChange(value);
  54124. }
  54125. this._speedRatio = value;
  54126. },
  54127. enumerable: true,
  54128. configurable: true
  54129. });
  54130. // Methods
  54131. /**
  54132. * Synchronize and normalize current Animatable with a source Animatable
  54133. * This is useful when using animation weights and when animations are not of the same length
  54134. * @param root defines the root Animatable to synchronize with
  54135. * @returns the current Animatable
  54136. */
  54137. Animatable.prototype.syncWith = function (root) {
  54138. this._syncRoot = root;
  54139. if (root) {
  54140. // Make sure this animatable will animate after the root
  54141. var index = this._scene._activeAnimatables.indexOf(this);
  54142. if (index > -1) {
  54143. this._scene._activeAnimatables.splice(index, 1);
  54144. this._scene._activeAnimatables.push(this);
  54145. }
  54146. }
  54147. return this;
  54148. };
  54149. /**
  54150. * Gets the list of runtime animations
  54151. * @returns an array of RuntimeAnimation
  54152. */
  54153. Animatable.prototype.getAnimations = function () {
  54154. return this._runtimeAnimations;
  54155. };
  54156. /**
  54157. * Adds more animations to the current animatable
  54158. * @param target defines the target of the animations
  54159. * @param animations defines the new animations to add
  54160. */
  54161. Animatable.prototype.appendAnimations = function (target, animations) {
  54162. for (var index = 0; index < animations.length; index++) {
  54163. var animation = animations[index];
  54164. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  54165. }
  54166. };
  54167. /**
  54168. * Gets the source animation for a specific property
  54169. * @param property defines the propertyu to look for
  54170. * @returns null or the source animation for the given property
  54171. */
  54172. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  54173. var runtimeAnimations = this._runtimeAnimations;
  54174. for (var index = 0; index < runtimeAnimations.length; index++) {
  54175. if (runtimeAnimations[index].animation.targetProperty === property) {
  54176. return runtimeAnimations[index].animation;
  54177. }
  54178. }
  54179. return null;
  54180. };
  54181. /**
  54182. * Gets the runtime animation for a specific property
  54183. * @param property defines the propertyu to look for
  54184. * @returns null or the runtime animation for the given property
  54185. */
  54186. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  54187. var runtimeAnimations = this._runtimeAnimations;
  54188. for (var index = 0; index < runtimeAnimations.length; index++) {
  54189. if (runtimeAnimations[index].animation.targetProperty === property) {
  54190. return runtimeAnimations[index];
  54191. }
  54192. }
  54193. return null;
  54194. };
  54195. /**
  54196. * Resets the animatable to its original state
  54197. */
  54198. Animatable.prototype.reset = function () {
  54199. var runtimeAnimations = this._runtimeAnimations;
  54200. for (var index = 0; index < runtimeAnimations.length; index++) {
  54201. runtimeAnimations[index].reset(true);
  54202. }
  54203. this._localDelayOffset = null;
  54204. this._pausedDelay = null;
  54205. };
  54206. /**
  54207. * Allows the animatable to blend with current running animations
  54208. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54209. * @param blendingSpeed defines the blending speed to use
  54210. */
  54211. Animatable.prototype.enableBlending = function (blendingSpeed) {
  54212. var runtimeAnimations = this._runtimeAnimations;
  54213. for (var index = 0; index < runtimeAnimations.length; index++) {
  54214. runtimeAnimations[index].animation.enableBlending = true;
  54215. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  54216. }
  54217. };
  54218. /**
  54219. * Disable animation blending
  54220. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54221. */
  54222. Animatable.prototype.disableBlending = function () {
  54223. var runtimeAnimations = this._runtimeAnimations;
  54224. for (var index = 0; index < runtimeAnimations.length; index++) {
  54225. runtimeAnimations[index].animation.enableBlending = false;
  54226. }
  54227. };
  54228. /**
  54229. * Jump directly to a given frame
  54230. * @param frame defines the frame to jump to
  54231. */
  54232. Animatable.prototype.goToFrame = function (frame) {
  54233. var runtimeAnimations = this._runtimeAnimations;
  54234. if (runtimeAnimations[0]) {
  54235. var fps = runtimeAnimations[0].animation.framePerSecond;
  54236. var currentFrame = runtimeAnimations[0].currentFrame;
  54237. var adjustTime = frame - currentFrame;
  54238. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  54239. if (this._localDelayOffset === null) {
  54240. this._localDelayOffset = 0;
  54241. }
  54242. this._localDelayOffset -= delay;
  54243. }
  54244. for (var index = 0; index < runtimeAnimations.length; index++) {
  54245. runtimeAnimations[index].goToFrame(frame);
  54246. }
  54247. };
  54248. /**
  54249. * Pause the animation
  54250. */
  54251. Animatable.prototype.pause = function () {
  54252. if (this._paused) {
  54253. return;
  54254. }
  54255. this._paused = true;
  54256. };
  54257. /**
  54258. * Restart the animation
  54259. */
  54260. Animatable.prototype.restart = function () {
  54261. this._paused = false;
  54262. };
  54263. Animatable.prototype._raiseOnAnimationEnd = function () {
  54264. if (this.onAnimationEnd) {
  54265. this.onAnimationEnd();
  54266. }
  54267. this.onAnimationEndObservable.notifyObservers(this);
  54268. };
  54269. /**
  54270. * Stop and delete the current animation
  54271. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  54272. * @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)
  54273. */
  54274. Animatable.prototype.stop = function (animationName, targetMask) {
  54275. if (animationName || targetMask) {
  54276. var idx = this._scene._activeAnimatables.indexOf(this);
  54277. if (idx > -1) {
  54278. var runtimeAnimations = this._runtimeAnimations;
  54279. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  54280. var runtimeAnimation = runtimeAnimations[index];
  54281. if (animationName && runtimeAnimation.animation.name != animationName) {
  54282. continue;
  54283. }
  54284. if (targetMask && !targetMask(runtimeAnimation.target)) {
  54285. continue;
  54286. }
  54287. runtimeAnimation.dispose();
  54288. runtimeAnimations.splice(index, 1);
  54289. }
  54290. if (runtimeAnimations.length == 0) {
  54291. this._scene._activeAnimatables.splice(idx, 1);
  54292. this._raiseOnAnimationEnd();
  54293. }
  54294. }
  54295. }
  54296. else {
  54297. var index = this._scene._activeAnimatables.indexOf(this);
  54298. if (index > -1) {
  54299. this._scene._activeAnimatables.splice(index, 1);
  54300. var runtimeAnimations = this._runtimeAnimations;
  54301. for (var index = 0; index < runtimeAnimations.length; index++) {
  54302. runtimeAnimations[index].dispose();
  54303. }
  54304. this._raiseOnAnimationEnd();
  54305. }
  54306. }
  54307. };
  54308. /**
  54309. * Wait asynchronously for the animation to end
  54310. * @returns a promise which will be fullfilled when the animation ends
  54311. */
  54312. Animatable.prototype.waitAsync = function () {
  54313. var _this = this;
  54314. return new Promise(function (resolve, reject) {
  54315. _this.onAnimationEndObservable.add(function () {
  54316. resolve(_this);
  54317. }, undefined, undefined, _this, true);
  54318. });
  54319. };
  54320. /** @hidden */
  54321. Animatable.prototype._animate = function (delay) {
  54322. if (this._paused) {
  54323. this.animationStarted = false;
  54324. if (this._pausedDelay === null) {
  54325. this._pausedDelay = delay;
  54326. }
  54327. return true;
  54328. }
  54329. if (this._localDelayOffset === null) {
  54330. this._localDelayOffset = delay;
  54331. this._pausedDelay = null;
  54332. }
  54333. else if (this._pausedDelay !== null) {
  54334. this._localDelayOffset += delay - this._pausedDelay;
  54335. this._pausedDelay = null;
  54336. }
  54337. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  54338. return true;
  54339. }
  54340. // Animating
  54341. var running = false;
  54342. var runtimeAnimations = this._runtimeAnimations;
  54343. var index;
  54344. for (index = 0; index < runtimeAnimations.length; index++) {
  54345. var animation = runtimeAnimations[index];
  54346. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  54347. running = running || isRunning;
  54348. }
  54349. this.animationStarted = running;
  54350. if (!running) {
  54351. if (this.disposeOnEnd) {
  54352. // Remove from active animatables
  54353. index = this._scene._activeAnimatables.indexOf(this);
  54354. this._scene._activeAnimatables.splice(index, 1);
  54355. // Dispose all runtime animations
  54356. for (index = 0; index < runtimeAnimations.length; index++) {
  54357. runtimeAnimations[index].dispose();
  54358. }
  54359. }
  54360. this._raiseOnAnimationEnd();
  54361. if (this.disposeOnEnd) {
  54362. this.onAnimationEnd = null;
  54363. this.onAnimationEndObservable.clear();
  54364. }
  54365. }
  54366. return running;
  54367. };
  54368. return Animatable;
  54369. }());
  54370. BABYLON.Animatable = Animatable;
  54371. })(BABYLON || (BABYLON = {}));
  54372. //# sourceMappingURL=babylon.animatable.js.map
  54373. var BABYLON;
  54374. (function (BABYLON) {
  54375. /**
  54376. * Base class used for every default easing function.
  54377. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54378. */
  54379. var EasingFunction = /** @class */ (function () {
  54380. function EasingFunction() {
  54381. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  54382. }
  54383. /**
  54384. * Sets the easing mode of the current function.
  54385. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  54386. */
  54387. EasingFunction.prototype.setEasingMode = function (easingMode) {
  54388. var n = Math.min(Math.max(easingMode, 0), 2);
  54389. this._easingMode = n;
  54390. };
  54391. /**
  54392. * Gets the current easing mode.
  54393. * @returns the easing mode
  54394. */
  54395. EasingFunction.prototype.getEasingMode = function () {
  54396. return this._easingMode;
  54397. };
  54398. /**
  54399. * @hidden
  54400. */
  54401. EasingFunction.prototype.easeInCore = function (gradient) {
  54402. throw new Error('You must implement this method');
  54403. };
  54404. /**
  54405. * Given an input gradient between 0 and 1, this returns the corrseponding value
  54406. * of the easing function.
  54407. * @param gradient Defines the value between 0 and 1 we want the easing value for
  54408. * @returns the corresponding value on the curve defined by the easing function
  54409. */
  54410. EasingFunction.prototype.ease = function (gradient) {
  54411. switch (this._easingMode) {
  54412. case EasingFunction.EASINGMODE_EASEIN:
  54413. return this.easeInCore(gradient);
  54414. case EasingFunction.EASINGMODE_EASEOUT:
  54415. return (1 - this.easeInCore(1 - gradient));
  54416. }
  54417. if (gradient >= 0.5) {
  54418. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  54419. }
  54420. return (this.easeInCore(gradient * 2) * 0.5);
  54421. };
  54422. /**
  54423. * Interpolation follows the mathematical formula associated with the easing function.
  54424. */
  54425. EasingFunction.EASINGMODE_EASEIN = 0;
  54426. /**
  54427. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  54428. */
  54429. EasingFunction.EASINGMODE_EASEOUT = 1;
  54430. /**
  54431. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  54432. */
  54433. EasingFunction.EASINGMODE_EASEINOUT = 2;
  54434. return EasingFunction;
  54435. }());
  54436. BABYLON.EasingFunction = EasingFunction;
  54437. /**
  54438. * Easing function with a circle shape (see link below).
  54439. * @see https://easings.net/#easeInCirc
  54440. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54441. */
  54442. var CircleEase = /** @class */ (function (_super) {
  54443. __extends(CircleEase, _super);
  54444. function CircleEase() {
  54445. return _super !== null && _super.apply(this, arguments) || this;
  54446. }
  54447. /** @hidden */
  54448. CircleEase.prototype.easeInCore = function (gradient) {
  54449. gradient = Math.max(0, Math.min(1, gradient));
  54450. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  54451. };
  54452. return CircleEase;
  54453. }(EasingFunction));
  54454. BABYLON.CircleEase = CircleEase;
  54455. /**
  54456. * Easing function with a ease back shape (see link below).
  54457. * @see https://easings.net/#easeInBack
  54458. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54459. */
  54460. var BackEase = /** @class */ (function (_super) {
  54461. __extends(BackEase, _super);
  54462. /**
  54463. * Instantiates a back ease easing
  54464. * @see https://easings.net/#easeInBack
  54465. * @param amplitude Defines the amplitude of the function
  54466. */
  54467. function BackEase(
  54468. /** Defines the amplitude of the function */
  54469. amplitude) {
  54470. if (amplitude === void 0) { amplitude = 1; }
  54471. var _this = _super.call(this) || this;
  54472. _this.amplitude = amplitude;
  54473. return _this;
  54474. }
  54475. /** @hidden */
  54476. BackEase.prototype.easeInCore = function (gradient) {
  54477. var num = Math.max(0, this.amplitude);
  54478. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  54479. };
  54480. return BackEase;
  54481. }(EasingFunction));
  54482. BABYLON.BackEase = BackEase;
  54483. /**
  54484. * Easing function with a bouncing shape (see link below).
  54485. * @see https://easings.net/#easeInBounce
  54486. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54487. */
  54488. var BounceEase = /** @class */ (function (_super) {
  54489. __extends(BounceEase, _super);
  54490. /**
  54491. * Instantiates a bounce easing
  54492. * @see https://easings.net/#easeInBounce
  54493. * @param bounces Defines the number of bounces
  54494. * @param bounciness Defines the amplitude of the bounce
  54495. */
  54496. function BounceEase(
  54497. /** Defines the number of bounces */
  54498. bounces,
  54499. /** Defines the amplitude of the bounce */
  54500. bounciness) {
  54501. if (bounces === void 0) { bounces = 3; }
  54502. if (bounciness === void 0) { bounciness = 2; }
  54503. var _this = _super.call(this) || this;
  54504. _this.bounces = bounces;
  54505. _this.bounciness = bounciness;
  54506. return _this;
  54507. }
  54508. /** @hidden */
  54509. BounceEase.prototype.easeInCore = function (gradient) {
  54510. var y = Math.max(0.0, this.bounces);
  54511. var bounciness = this.bounciness;
  54512. if (bounciness <= 1.0) {
  54513. bounciness = 1.001;
  54514. }
  54515. var num9 = Math.pow(bounciness, y);
  54516. var num5 = 1.0 - bounciness;
  54517. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  54518. var num15 = gradient * num4;
  54519. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  54520. var num3 = Math.floor(num65);
  54521. var num13 = num3 + 1.0;
  54522. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  54523. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  54524. var num7 = (num8 + num12) * 0.5;
  54525. var num6 = gradient - num7;
  54526. var num2 = num7 - num8;
  54527. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  54528. };
  54529. return BounceEase;
  54530. }(EasingFunction));
  54531. BABYLON.BounceEase = BounceEase;
  54532. /**
  54533. * Easing function with a power of 3 shape (see link below).
  54534. * @see https://easings.net/#easeInCubic
  54535. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54536. */
  54537. var CubicEase = /** @class */ (function (_super) {
  54538. __extends(CubicEase, _super);
  54539. function CubicEase() {
  54540. return _super !== null && _super.apply(this, arguments) || this;
  54541. }
  54542. /** @hidden */
  54543. CubicEase.prototype.easeInCore = function (gradient) {
  54544. return (gradient * gradient * gradient);
  54545. };
  54546. return CubicEase;
  54547. }(EasingFunction));
  54548. BABYLON.CubicEase = CubicEase;
  54549. /**
  54550. * Easing function with an elastic shape (see link below).
  54551. * @see https://easings.net/#easeInElastic
  54552. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54553. */
  54554. var ElasticEase = /** @class */ (function (_super) {
  54555. __extends(ElasticEase, _super);
  54556. /**
  54557. * Instantiates an elastic easing function
  54558. * @see https://easings.net/#easeInElastic
  54559. * @param oscillations Defines the number of oscillations
  54560. * @param springiness Defines the amplitude of the oscillations
  54561. */
  54562. function ElasticEase(
  54563. /** Defines the number of oscillations*/
  54564. oscillations,
  54565. /** Defines the amplitude of the oscillations*/
  54566. springiness) {
  54567. if (oscillations === void 0) { oscillations = 3; }
  54568. if (springiness === void 0) { springiness = 3; }
  54569. var _this = _super.call(this) || this;
  54570. _this.oscillations = oscillations;
  54571. _this.springiness = springiness;
  54572. return _this;
  54573. }
  54574. /** @hidden */
  54575. ElasticEase.prototype.easeInCore = function (gradient) {
  54576. var num2;
  54577. var num3 = Math.max(0.0, this.oscillations);
  54578. var num = Math.max(0.0, this.springiness);
  54579. if (num == 0) {
  54580. num2 = gradient;
  54581. }
  54582. else {
  54583. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  54584. }
  54585. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  54586. };
  54587. return ElasticEase;
  54588. }(EasingFunction));
  54589. BABYLON.ElasticEase = ElasticEase;
  54590. /**
  54591. * Easing function with an exponential shape (see link below).
  54592. * @see https://easings.net/#easeInExpo
  54593. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54594. */
  54595. var ExponentialEase = /** @class */ (function (_super) {
  54596. __extends(ExponentialEase, _super);
  54597. /**
  54598. * Instantiates an exponential easing function
  54599. * @see https://easings.net/#easeInExpo
  54600. * @param exponent Defines the exponent of the function
  54601. */
  54602. function ExponentialEase(
  54603. /** Defines the exponent of the function */
  54604. exponent) {
  54605. if (exponent === void 0) { exponent = 2; }
  54606. var _this = _super.call(this) || this;
  54607. _this.exponent = exponent;
  54608. return _this;
  54609. }
  54610. /** @hidden */
  54611. ExponentialEase.prototype.easeInCore = function (gradient) {
  54612. if (this.exponent <= 0) {
  54613. return gradient;
  54614. }
  54615. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  54616. };
  54617. return ExponentialEase;
  54618. }(EasingFunction));
  54619. BABYLON.ExponentialEase = ExponentialEase;
  54620. /**
  54621. * Easing function with a power shape (see link below).
  54622. * @see https://easings.net/#easeInQuad
  54623. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54624. */
  54625. var PowerEase = /** @class */ (function (_super) {
  54626. __extends(PowerEase, _super);
  54627. /**
  54628. * Instantiates an power base easing function
  54629. * @see https://easings.net/#easeInQuad
  54630. * @param power Defines the power of the function
  54631. */
  54632. function PowerEase(
  54633. /** Defines the power of the function */
  54634. power) {
  54635. if (power === void 0) { power = 2; }
  54636. var _this = _super.call(this) || this;
  54637. _this.power = power;
  54638. return _this;
  54639. }
  54640. /** @hidden */
  54641. PowerEase.prototype.easeInCore = function (gradient) {
  54642. var y = Math.max(0.0, this.power);
  54643. return Math.pow(gradient, y);
  54644. };
  54645. return PowerEase;
  54646. }(EasingFunction));
  54647. BABYLON.PowerEase = PowerEase;
  54648. /**
  54649. * Easing function with a power of 2 shape (see link below).
  54650. * @see https://easings.net/#easeInQuad
  54651. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54652. */
  54653. var QuadraticEase = /** @class */ (function (_super) {
  54654. __extends(QuadraticEase, _super);
  54655. function QuadraticEase() {
  54656. return _super !== null && _super.apply(this, arguments) || this;
  54657. }
  54658. /** @hidden */
  54659. QuadraticEase.prototype.easeInCore = function (gradient) {
  54660. return (gradient * gradient);
  54661. };
  54662. return QuadraticEase;
  54663. }(EasingFunction));
  54664. BABYLON.QuadraticEase = QuadraticEase;
  54665. /**
  54666. * Easing function with a power of 4 shape (see link below).
  54667. * @see https://easings.net/#easeInQuart
  54668. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54669. */
  54670. var QuarticEase = /** @class */ (function (_super) {
  54671. __extends(QuarticEase, _super);
  54672. function QuarticEase() {
  54673. return _super !== null && _super.apply(this, arguments) || this;
  54674. }
  54675. /** @hidden */
  54676. QuarticEase.prototype.easeInCore = function (gradient) {
  54677. return (gradient * gradient * gradient * gradient);
  54678. };
  54679. return QuarticEase;
  54680. }(EasingFunction));
  54681. BABYLON.QuarticEase = QuarticEase;
  54682. /**
  54683. * Easing function with a power of 5 shape (see link below).
  54684. * @see https://easings.net/#easeInQuint
  54685. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54686. */
  54687. var QuinticEase = /** @class */ (function (_super) {
  54688. __extends(QuinticEase, _super);
  54689. function QuinticEase() {
  54690. return _super !== null && _super.apply(this, arguments) || this;
  54691. }
  54692. /** @hidden */
  54693. QuinticEase.prototype.easeInCore = function (gradient) {
  54694. return (gradient * gradient * gradient * gradient * gradient);
  54695. };
  54696. return QuinticEase;
  54697. }(EasingFunction));
  54698. BABYLON.QuinticEase = QuinticEase;
  54699. /**
  54700. * Easing function with a sin shape (see link below).
  54701. * @see https://easings.net/#easeInSine
  54702. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54703. */
  54704. var SineEase = /** @class */ (function (_super) {
  54705. __extends(SineEase, _super);
  54706. function SineEase() {
  54707. return _super !== null && _super.apply(this, arguments) || this;
  54708. }
  54709. /** @hidden */
  54710. SineEase.prototype.easeInCore = function (gradient) {
  54711. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54712. };
  54713. return SineEase;
  54714. }(EasingFunction));
  54715. BABYLON.SineEase = SineEase;
  54716. /**
  54717. * Easing function with a bezier shape (see link below).
  54718. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54719. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54720. */
  54721. var BezierCurveEase = /** @class */ (function (_super) {
  54722. __extends(BezierCurveEase, _super);
  54723. /**
  54724. * Instantiates a bezier function
  54725. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54726. * @param x1 Defines the x component of the start tangent in the bezier curve
  54727. * @param y1 Defines the y component of the start tangent in the bezier curve
  54728. * @param x2 Defines the x component of the end tangent in the bezier curve
  54729. * @param y2 Defines the y component of the end tangent in the bezier curve
  54730. */
  54731. function BezierCurveEase(
  54732. /** Defines the x component of the start tangent in the bezier curve */
  54733. x1,
  54734. /** Defines the y component of the start tangent in the bezier curve */
  54735. y1,
  54736. /** Defines the x component of the end tangent in the bezier curve */
  54737. x2,
  54738. /** Defines the y component of the end tangent in the bezier curve */
  54739. y2) {
  54740. if (x1 === void 0) { x1 = 0; }
  54741. if (y1 === void 0) { y1 = 0; }
  54742. if (x2 === void 0) { x2 = 1; }
  54743. if (y2 === void 0) { y2 = 1; }
  54744. var _this = _super.call(this) || this;
  54745. _this.x1 = x1;
  54746. _this.y1 = y1;
  54747. _this.x2 = x2;
  54748. _this.y2 = y2;
  54749. return _this;
  54750. }
  54751. /** @hidden */
  54752. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54753. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54754. };
  54755. return BezierCurveEase;
  54756. }(EasingFunction));
  54757. BABYLON.BezierCurveEase = BezierCurveEase;
  54758. })(BABYLON || (BABYLON = {}));
  54759. //# sourceMappingURL=babylon.easing.js.map
  54760. var BABYLON;
  54761. (function (BABYLON) {
  54762. /**
  54763. * A Condition applied to an Action
  54764. */
  54765. var Condition = /** @class */ (function () {
  54766. /**
  54767. * Creates a new Condition
  54768. * @param actionManager the manager of the action the condition is applied to
  54769. */
  54770. function Condition(actionManager) {
  54771. this._actionManager = actionManager;
  54772. }
  54773. /**
  54774. * Check if the current condition is valid
  54775. * @returns a boolean
  54776. */
  54777. Condition.prototype.isValid = function () {
  54778. return true;
  54779. };
  54780. /**
  54781. * Internal only
  54782. * @hidden
  54783. */
  54784. Condition.prototype._getProperty = function (propertyPath) {
  54785. return this._actionManager._getProperty(propertyPath);
  54786. };
  54787. /**
  54788. * Internal only
  54789. * @hidden
  54790. */
  54791. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54792. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54793. };
  54794. /**
  54795. * Serialize placeholder for child classes
  54796. * @returns the serialized object
  54797. */
  54798. Condition.prototype.serialize = function () {
  54799. };
  54800. /**
  54801. * Internal only
  54802. * @hidden
  54803. */
  54804. Condition.prototype._serialize = function (serializedCondition) {
  54805. return {
  54806. type: 2,
  54807. children: [],
  54808. name: serializedCondition.name,
  54809. properties: serializedCondition.properties
  54810. };
  54811. };
  54812. return Condition;
  54813. }());
  54814. BABYLON.Condition = Condition;
  54815. /**
  54816. * Defines specific conditional operators as extensions of Condition
  54817. */
  54818. var ValueCondition = /** @class */ (function (_super) {
  54819. __extends(ValueCondition, _super);
  54820. /**
  54821. * Creates a new ValueCondition
  54822. * @param actionManager manager for the action the condition applies to
  54823. * @param target for the action
  54824. * @param propertyPath path to specify the property of the target the conditional operator uses
  54825. * @param value the value compared by the conditional operator against the current value of the property
  54826. * @param operator the conditional operator, default ValueCondition.IsEqual
  54827. */
  54828. function ValueCondition(actionManager, target,
  54829. /** path to specify the property of the target the conditional operator uses */
  54830. propertyPath,
  54831. /** the value compared by the conditional operator against the current value of the property */
  54832. value,
  54833. /** the conditional operator, default ValueCondition.IsEqual */
  54834. operator) {
  54835. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54836. var _this = _super.call(this, actionManager) || this;
  54837. _this.propertyPath = propertyPath;
  54838. _this.value = value;
  54839. _this.operator = operator;
  54840. _this._target = target;
  54841. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54842. _this._property = _this._getProperty(_this.propertyPath);
  54843. return _this;
  54844. }
  54845. Object.defineProperty(ValueCondition, "IsEqual", {
  54846. /**
  54847. * returns the number for IsEqual
  54848. */
  54849. get: function () {
  54850. return ValueCondition._IsEqual;
  54851. },
  54852. enumerable: true,
  54853. configurable: true
  54854. });
  54855. Object.defineProperty(ValueCondition, "IsDifferent", {
  54856. /**
  54857. * Returns the number for IsDifferent
  54858. */
  54859. get: function () {
  54860. return ValueCondition._IsDifferent;
  54861. },
  54862. enumerable: true,
  54863. configurable: true
  54864. });
  54865. Object.defineProperty(ValueCondition, "IsGreater", {
  54866. /**
  54867. * Returns the number for IsGreater
  54868. */
  54869. get: function () {
  54870. return ValueCondition._IsGreater;
  54871. },
  54872. enumerable: true,
  54873. configurable: true
  54874. });
  54875. Object.defineProperty(ValueCondition, "IsLesser", {
  54876. /**
  54877. * Returns the number for IsLesser
  54878. */
  54879. get: function () {
  54880. return ValueCondition._IsLesser;
  54881. },
  54882. enumerable: true,
  54883. configurable: true
  54884. });
  54885. /**
  54886. * Compares the given value with the property value for the specified conditional operator
  54887. * @returns the result of the comparison
  54888. */
  54889. ValueCondition.prototype.isValid = function () {
  54890. switch (this.operator) {
  54891. case ValueCondition.IsGreater:
  54892. return this._effectiveTarget[this._property] > this.value;
  54893. case ValueCondition.IsLesser:
  54894. return this._effectiveTarget[this._property] < this.value;
  54895. case ValueCondition.IsEqual:
  54896. case ValueCondition.IsDifferent:
  54897. var check;
  54898. if (this.value.equals) {
  54899. check = this.value.equals(this._effectiveTarget[this._property]);
  54900. }
  54901. else {
  54902. check = this.value === this._effectiveTarget[this._property];
  54903. }
  54904. return this.operator === ValueCondition.IsEqual ? check : !check;
  54905. }
  54906. return false;
  54907. };
  54908. /**
  54909. * Serialize the ValueCondition into a JSON compatible object
  54910. * @returns serialization object
  54911. */
  54912. ValueCondition.prototype.serialize = function () {
  54913. return this._serialize({
  54914. name: "ValueCondition",
  54915. properties: [
  54916. BABYLON.Action._GetTargetProperty(this._target),
  54917. { name: "propertyPath", value: this.propertyPath },
  54918. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54919. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54920. ]
  54921. });
  54922. };
  54923. /**
  54924. * Gets the name of the conditional operator for the ValueCondition
  54925. * @param operator the conditional operator
  54926. * @returns the name
  54927. */
  54928. ValueCondition.GetOperatorName = function (operator) {
  54929. switch (operator) {
  54930. case ValueCondition._IsEqual: return "IsEqual";
  54931. case ValueCondition._IsDifferent: return "IsDifferent";
  54932. case ValueCondition._IsGreater: return "IsGreater";
  54933. case ValueCondition._IsLesser: return "IsLesser";
  54934. default: return "";
  54935. }
  54936. };
  54937. /**
  54938. * Internal only
  54939. * @hidden
  54940. */
  54941. ValueCondition._IsEqual = 0;
  54942. /**
  54943. * Internal only
  54944. * @hidden
  54945. */
  54946. ValueCondition._IsDifferent = 1;
  54947. /**
  54948. * Internal only
  54949. * @hidden
  54950. */
  54951. ValueCondition._IsGreater = 2;
  54952. /**
  54953. * Internal only
  54954. * @hidden
  54955. */
  54956. ValueCondition._IsLesser = 3;
  54957. return ValueCondition;
  54958. }(Condition));
  54959. BABYLON.ValueCondition = ValueCondition;
  54960. /**
  54961. * Defines a predicate condition as an extension of Condition
  54962. */
  54963. var PredicateCondition = /** @class */ (function (_super) {
  54964. __extends(PredicateCondition, _super);
  54965. /**
  54966. * Creates a new PredicateCondition
  54967. * @param actionManager manager for the action the condition applies to
  54968. * @param predicate defines the predicate function used to validate the condition
  54969. */
  54970. function PredicateCondition(actionManager,
  54971. /** defines the predicate function used to validate the condition */
  54972. predicate) {
  54973. var _this = _super.call(this, actionManager) || this;
  54974. _this.predicate = predicate;
  54975. return _this;
  54976. }
  54977. /**
  54978. * @returns the validity of the predicate condition
  54979. */
  54980. PredicateCondition.prototype.isValid = function () {
  54981. return this.predicate();
  54982. };
  54983. return PredicateCondition;
  54984. }(Condition));
  54985. BABYLON.PredicateCondition = PredicateCondition;
  54986. /**
  54987. * Defines a state condition as an extension of Condition
  54988. */
  54989. var StateCondition = /** @class */ (function (_super) {
  54990. __extends(StateCondition, _super);
  54991. /**
  54992. * Creates a new StateCondition
  54993. * @param actionManager manager for the action the condition applies to
  54994. * @param target of the condition
  54995. * @param value to compare with target state
  54996. */
  54997. function StateCondition(actionManager, target,
  54998. /** Value to compare with target state */
  54999. value) {
  55000. var _this = _super.call(this, actionManager) || this;
  55001. _this.value = value;
  55002. _this._target = target;
  55003. return _this;
  55004. }
  55005. /**
  55006. * Gets a boolean indicating if the current condition is met
  55007. * @returns the validity of the state
  55008. */
  55009. StateCondition.prototype.isValid = function () {
  55010. return this._target.state === this.value;
  55011. };
  55012. /**
  55013. * Serialize the StateCondition into a JSON compatible object
  55014. * @returns serialization object
  55015. */
  55016. StateCondition.prototype.serialize = function () {
  55017. return this._serialize({
  55018. name: "StateCondition",
  55019. properties: [
  55020. BABYLON.Action._GetTargetProperty(this._target),
  55021. { name: "value", value: this.value }
  55022. ]
  55023. });
  55024. };
  55025. return StateCondition;
  55026. }(Condition));
  55027. BABYLON.StateCondition = StateCondition;
  55028. })(BABYLON || (BABYLON = {}));
  55029. //# sourceMappingURL=babylon.condition.js.map
  55030. var BABYLON;
  55031. (function (BABYLON) {
  55032. /**
  55033. * The action to be carried out following a trigger
  55034. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  55035. */
  55036. var Action = /** @class */ (function () {
  55037. /**
  55038. * Creates a new Action
  55039. * @param triggerOptions the trigger, with or without parameters, for the action
  55040. * @param condition an optional determinant of action
  55041. */
  55042. function Action(
  55043. /** the trigger, with or without parameters, for the action */
  55044. triggerOptions, condition) {
  55045. this.triggerOptions = triggerOptions;
  55046. /**
  55047. * An event triggered prior to action being executed.
  55048. */
  55049. this.onBeforeExecuteObservable = new BABYLON.Observable();
  55050. if (triggerOptions.parameter) {
  55051. this.trigger = triggerOptions.trigger;
  55052. this._triggerParameter = triggerOptions.parameter;
  55053. }
  55054. else if (triggerOptions.trigger) {
  55055. this.trigger = triggerOptions.trigger;
  55056. }
  55057. else {
  55058. this.trigger = triggerOptions;
  55059. }
  55060. this._nextActiveAction = this;
  55061. this._condition = condition;
  55062. }
  55063. /**
  55064. * Internal only
  55065. * @hidden
  55066. */
  55067. Action.prototype._prepare = function () {
  55068. };
  55069. /**
  55070. * Gets the trigger parameters
  55071. * @returns the trigger parameters
  55072. */
  55073. Action.prototype.getTriggerParameter = function () {
  55074. return this._triggerParameter;
  55075. };
  55076. /**
  55077. * Internal only - executes current action event
  55078. * @hidden
  55079. */
  55080. Action.prototype._executeCurrent = function (evt) {
  55081. if (this._nextActiveAction._condition) {
  55082. var condition = this._nextActiveAction._condition;
  55083. var currentRenderId = this._actionManager.getScene().getRenderId();
  55084. // We cache the current evaluation for the current frame
  55085. if (condition._evaluationId === currentRenderId) {
  55086. if (!condition._currentResult) {
  55087. return;
  55088. }
  55089. }
  55090. else {
  55091. condition._evaluationId = currentRenderId;
  55092. if (!condition.isValid()) {
  55093. condition._currentResult = false;
  55094. return;
  55095. }
  55096. condition._currentResult = true;
  55097. }
  55098. }
  55099. this.onBeforeExecuteObservable.notifyObservers(this);
  55100. this._nextActiveAction.execute(evt);
  55101. this.skipToNextActiveAction();
  55102. };
  55103. /**
  55104. * Execute placeholder for child classes
  55105. * @param evt optional action event
  55106. */
  55107. Action.prototype.execute = function (evt) {
  55108. };
  55109. /**
  55110. * Skips to next active action
  55111. */
  55112. Action.prototype.skipToNextActiveAction = function () {
  55113. if (this._nextActiveAction._child) {
  55114. if (!this._nextActiveAction._child._actionManager) {
  55115. this._nextActiveAction._child._actionManager = this._actionManager;
  55116. }
  55117. this._nextActiveAction = this._nextActiveAction._child;
  55118. }
  55119. else {
  55120. this._nextActiveAction = this;
  55121. }
  55122. };
  55123. /**
  55124. * Adds action to chain of actions, may be a DoNothingAction
  55125. * @param action defines the next action to execute
  55126. * @returns The action passed in
  55127. * @see https://www.babylonjs-playground.com/#1T30HR#0
  55128. */
  55129. Action.prototype.then = function (action) {
  55130. this._child = action;
  55131. action._actionManager = this._actionManager;
  55132. action._prepare();
  55133. return action;
  55134. };
  55135. /**
  55136. * Internal only
  55137. * @hidden
  55138. */
  55139. Action.prototype._getProperty = function (propertyPath) {
  55140. return this._actionManager._getProperty(propertyPath);
  55141. };
  55142. /**
  55143. * Internal only
  55144. * @hidden
  55145. */
  55146. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  55147. return this._actionManager._getEffectiveTarget(target, propertyPath);
  55148. };
  55149. /**
  55150. * Serialize placeholder for child classes
  55151. * @param parent of child
  55152. * @returns the serialized object
  55153. */
  55154. Action.prototype.serialize = function (parent) {
  55155. };
  55156. /**
  55157. * Internal only called by serialize
  55158. * @hidden
  55159. */
  55160. Action.prototype._serialize = function (serializedAction, parent) {
  55161. var serializationObject = {
  55162. type: 1,
  55163. children: [],
  55164. name: serializedAction.name,
  55165. properties: serializedAction.properties || []
  55166. };
  55167. // Serialize child
  55168. if (this._child) {
  55169. this._child.serialize(serializationObject);
  55170. }
  55171. // Check if "this" has a condition
  55172. if (this._condition) {
  55173. var serializedCondition = this._condition.serialize();
  55174. serializedCondition.children.push(serializationObject);
  55175. if (parent) {
  55176. parent.children.push(serializedCondition);
  55177. }
  55178. return serializedCondition;
  55179. }
  55180. if (parent) {
  55181. parent.children.push(serializationObject);
  55182. }
  55183. return serializationObject;
  55184. };
  55185. /**
  55186. * Internal only
  55187. * @hidden
  55188. */
  55189. Action._SerializeValueAsString = function (value) {
  55190. if (typeof value === "number") {
  55191. return value.toString();
  55192. }
  55193. if (typeof value === "boolean") {
  55194. return value ? "true" : "false";
  55195. }
  55196. if (value instanceof BABYLON.Vector2) {
  55197. return value.x + ", " + value.y;
  55198. }
  55199. if (value instanceof BABYLON.Vector3) {
  55200. return value.x + ", " + value.y + ", " + value.z;
  55201. }
  55202. if (value instanceof BABYLON.Color3) {
  55203. return value.r + ", " + value.g + ", " + value.b;
  55204. }
  55205. if (value instanceof BABYLON.Color4) {
  55206. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  55207. }
  55208. return value; // string
  55209. };
  55210. /**
  55211. * Internal only
  55212. * @hidden
  55213. */
  55214. Action._GetTargetProperty = function (target) {
  55215. return {
  55216. name: "target",
  55217. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  55218. : target instanceof BABYLON.Light ? "LightProperties"
  55219. : target instanceof BABYLON.Camera ? "CameraProperties"
  55220. : "SceneProperties",
  55221. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  55222. };
  55223. };
  55224. return Action;
  55225. }());
  55226. BABYLON.Action = Action;
  55227. })(BABYLON || (BABYLON = {}));
  55228. //# sourceMappingURL=babylon.action.js.map
  55229. var BABYLON;
  55230. (function (BABYLON) {
  55231. /**
  55232. * ActionEvent is the event being sent when an action is triggered.
  55233. */
  55234. var ActionEvent = /** @class */ (function () {
  55235. /**
  55236. * Creates a new ActionEvent
  55237. * @param source The mesh or sprite that triggered the action
  55238. * @param pointerX The X mouse cursor position at the time of the event
  55239. * @param pointerY The Y mouse cursor position at the time of the event
  55240. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  55241. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  55242. * @param additionalData additional data for the event
  55243. */
  55244. function ActionEvent(
  55245. /** The mesh or sprite that triggered the action */
  55246. source,
  55247. /** The X mouse cursor position at the time of the event */
  55248. pointerX,
  55249. /** The Y mouse cursor position at the time of the event */
  55250. pointerY,
  55251. /** The mesh that is currently pointed at (can be null) */
  55252. meshUnderPointer,
  55253. /** the original (browser) event that triggered the ActionEvent */
  55254. sourceEvent,
  55255. /** additional data for the event */
  55256. additionalData) {
  55257. this.source = source;
  55258. this.pointerX = pointerX;
  55259. this.pointerY = pointerY;
  55260. this.meshUnderPointer = meshUnderPointer;
  55261. this.sourceEvent = sourceEvent;
  55262. this.additionalData = additionalData;
  55263. }
  55264. /**
  55265. * Helper function to auto-create an ActionEvent from a source mesh.
  55266. * @param source The source mesh that triggered the event
  55267. * @param evt The original (browser) event
  55268. * @param additionalData additional data for the event
  55269. * @returns the new ActionEvent
  55270. */
  55271. ActionEvent.CreateNew = function (source, evt, additionalData) {
  55272. var scene = source.getScene();
  55273. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55274. };
  55275. /**
  55276. * Helper function to auto-create an ActionEvent from a source sprite
  55277. * @param source The source sprite that triggered the event
  55278. * @param scene Scene associated with the sprite
  55279. * @param evt The original (browser) event
  55280. * @param additionalData additional data for the event
  55281. * @returns the new ActionEvent
  55282. */
  55283. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  55284. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55285. };
  55286. /**
  55287. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  55288. * @param scene the scene where the event occurred
  55289. * @param evt The original (browser) event
  55290. * @returns the new ActionEvent
  55291. */
  55292. ActionEvent.CreateNewFromScene = function (scene, evt) {
  55293. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  55294. };
  55295. /**
  55296. * Helper function to auto-create an ActionEvent from a primitive
  55297. * @param prim defines the target primitive
  55298. * @param pointerPos defines the pointer position
  55299. * @param evt The original (browser) event
  55300. * @param additionalData additional data for the event
  55301. * @returns the new ActionEvent
  55302. */
  55303. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  55304. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  55305. };
  55306. return ActionEvent;
  55307. }());
  55308. BABYLON.ActionEvent = ActionEvent;
  55309. /**
  55310. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  55311. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  55312. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55313. */
  55314. var ActionManager = /** @class */ (function () {
  55315. /**
  55316. * Creates a new action manager
  55317. * @param scene defines the hosting scene
  55318. */
  55319. function ActionManager(scene) {
  55320. // Members
  55321. /** Gets the list of actions */
  55322. this.actions = new Array();
  55323. /** Gets the cursor to use when hovering items */
  55324. this.hoverCursor = '';
  55325. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55326. scene.actionManagers.push(this);
  55327. }
  55328. // Methods
  55329. /**
  55330. * Releases all associated resources
  55331. */
  55332. ActionManager.prototype.dispose = function () {
  55333. var index = this._scene.actionManagers.indexOf(this);
  55334. for (var i = 0; i < this.actions.length; i++) {
  55335. var action = this.actions[i];
  55336. ActionManager.Triggers[action.trigger]--;
  55337. if (ActionManager.Triggers[action.trigger] === 0) {
  55338. delete ActionManager.Triggers[action.trigger];
  55339. }
  55340. }
  55341. if (index > -1) {
  55342. this._scene.actionManagers.splice(index, 1);
  55343. }
  55344. };
  55345. /**
  55346. * Gets hosting scene
  55347. * @returns the hosting scene
  55348. */
  55349. ActionManager.prototype.getScene = function () {
  55350. return this._scene;
  55351. };
  55352. /**
  55353. * Does this action manager handles actions of any of the given triggers
  55354. * @param triggers defines the triggers to be tested
  55355. * @return a boolean indicating whether one (or more) of the triggers is handled
  55356. */
  55357. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  55358. for (var index = 0; index < this.actions.length; index++) {
  55359. var action = this.actions[index];
  55360. if (triggers.indexOf(action.trigger) > -1) {
  55361. return true;
  55362. }
  55363. }
  55364. return false;
  55365. };
  55366. /**
  55367. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  55368. * speed.
  55369. * @param triggerA defines the trigger to be tested
  55370. * @param triggerB defines the trigger to be tested
  55371. * @return a boolean indicating whether one (or more) of the triggers is handled
  55372. */
  55373. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  55374. for (var index = 0; index < this.actions.length; index++) {
  55375. var action = this.actions[index];
  55376. if (triggerA == action.trigger || triggerB == action.trigger) {
  55377. return true;
  55378. }
  55379. }
  55380. return false;
  55381. };
  55382. /**
  55383. * Does this action manager handles actions of a given trigger
  55384. * @param trigger defines the trigger to be tested
  55385. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  55386. * @return whether the trigger is handled
  55387. */
  55388. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  55389. for (var index = 0; index < this.actions.length; index++) {
  55390. var action = this.actions[index];
  55391. if (action.trigger === trigger) {
  55392. if (parameterPredicate) {
  55393. if (parameterPredicate(action.getTriggerParameter())) {
  55394. return true;
  55395. }
  55396. }
  55397. else {
  55398. return true;
  55399. }
  55400. }
  55401. }
  55402. return false;
  55403. };
  55404. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  55405. /**
  55406. * Does this action manager has pointer triggers
  55407. */
  55408. get: function () {
  55409. for (var index = 0; index < this.actions.length; index++) {
  55410. var action = this.actions[index];
  55411. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  55412. return true;
  55413. }
  55414. }
  55415. return false;
  55416. },
  55417. enumerable: true,
  55418. configurable: true
  55419. });
  55420. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  55421. /**
  55422. * Does this action manager has pick triggers
  55423. */
  55424. get: function () {
  55425. for (var index = 0; index < this.actions.length; index++) {
  55426. var action = this.actions[index];
  55427. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  55428. return true;
  55429. }
  55430. }
  55431. return false;
  55432. },
  55433. enumerable: true,
  55434. configurable: true
  55435. });
  55436. Object.defineProperty(ActionManager, "HasTriggers", {
  55437. /**
  55438. * Does exist one action manager with at least one trigger
  55439. **/
  55440. get: function () {
  55441. for (var t in ActionManager.Triggers) {
  55442. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55443. return true;
  55444. }
  55445. }
  55446. return false;
  55447. },
  55448. enumerable: true,
  55449. configurable: true
  55450. });
  55451. Object.defineProperty(ActionManager, "HasPickTriggers", {
  55452. /**
  55453. * Does exist one action manager with at least one pick trigger
  55454. **/
  55455. get: function () {
  55456. for (var t in ActionManager.Triggers) {
  55457. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55458. var t_int = parseInt(t);
  55459. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  55460. return true;
  55461. }
  55462. }
  55463. }
  55464. return false;
  55465. },
  55466. enumerable: true,
  55467. configurable: true
  55468. });
  55469. /**
  55470. * Does exist one action manager that handles actions of a given trigger
  55471. * @param trigger defines the trigger to be tested
  55472. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  55473. **/
  55474. ActionManager.HasSpecificTrigger = function (trigger) {
  55475. for (var t in ActionManager.Triggers) {
  55476. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55477. var t_int = parseInt(t);
  55478. if (t_int === trigger) {
  55479. return true;
  55480. }
  55481. }
  55482. }
  55483. return false;
  55484. };
  55485. /**
  55486. * Registers an action to this action manager
  55487. * @param action defines the action to be registered
  55488. * @return the action amended (prepared) after registration
  55489. */
  55490. ActionManager.prototype.registerAction = function (action) {
  55491. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  55492. if (this.getScene().actionManager !== this) {
  55493. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  55494. return null;
  55495. }
  55496. }
  55497. this.actions.push(action);
  55498. if (ActionManager.Triggers[action.trigger]) {
  55499. ActionManager.Triggers[action.trigger]++;
  55500. }
  55501. else {
  55502. ActionManager.Triggers[action.trigger] = 1;
  55503. }
  55504. action._actionManager = this;
  55505. action._prepare();
  55506. return action;
  55507. };
  55508. /**
  55509. * Unregisters an action to this action manager
  55510. * @param action defines the action to be unregistered
  55511. * @return a boolean indicating whether the action has been unregistered
  55512. */
  55513. ActionManager.prototype.unregisterAction = function (action) {
  55514. var index = this.actions.indexOf(action);
  55515. if (index !== -1) {
  55516. this.actions.splice(index, 1);
  55517. ActionManager.Triggers[action.trigger] -= 1;
  55518. if (ActionManager.Triggers[action.trigger] === 0) {
  55519. delete ActionManager.Triggers[action.trigger];
  55520. }
  55521. delete action._actionManager;
  55522. return true;
  55523. }
  55524. return false;
  55525. };
  55526. /**
  55527. * Process a specific trigger
  55528. * @param trigger defines the trigger to process
  55529. * @param evt defines the event details to be processed
  55530. */
  55531. ActionManager.prototype.processTrigger = function (trigger, evt) {
  55532. for (var index = 0; index < this.actions.length; index++) {
  55533. var action = this.actions[index];
  55534. if (action.trigger === trigger) {
  55535. if (evt) {
  55536. if (trigger === ActionManager.OnKeyUpTrigger
  55537. || trigger === ActionManager.OnKeyDownTrigger) {
  55538. var parameter = action.getTriggerParameter();
  55539. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  55540. if (!parameter.toLowerCase) {
  55541. continue;
  55542. }
  55543. var lowerCase = parameter.toLowerCase();
  55544. if (lowerCase !== evt.sourceEvent.key) {
  55545. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  55546. var actualkey = String.fromCharCode(unicode).toLowerCase();
  55547. if (actualkey !== lowerCase) {
  55548. continue;
  55549. }
  55550. }
  55551. }
  55552. }
  55553. }
  55554. action._executeCurrent(evt);
  55555. }
  55556. }
  55557. };
  55558. /** @hidden */
  55559. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  55560. var properties = propertyPath.split(".");
  55561. for (var index = 0; index < properties.length - 1; index++) {
  55562. target = target[properties[index]];
  55563. }
  55564. return target;
  55565. };
  55566. /** @hidden */
  55567. ActionManager.prototype._getProperty = function (propertyPath) {
  55568. var properties = propertyPath.split(".");
  55569. return properties[properties.length - 1];
  55570. };
  55571. /**
  55572. * Serialize this manager to a JSON object
  55573. * @param name defines the property name to store this manager
  55574. * @returns a JSON representation of this manager
  55575. */
  55576. ActionManager.prototype.serialize = function (name) {
  55577. var root = {
  55578. children: new Array(),
  55579. name: name,
  55580. type: 3,
  55581. properties: new Array() // Empty for root but required
  55582. };
  55583. for (var i = 0; i < this.actions.length; i++) {
  55584. var triggerObject = {
  55585. type: 0,
  55586. children: new Array(),
  55587. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  55588. properties: new Array()
  55589. };
  55590. var triggerOptions = this.actions[i].triggerOptions;
  55591. if (triggerOptions && typeof triggerOptions !== "number") {
  55592. if (triggerOptions.parameter instanceof BABYLON.Node) {
  55593. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  55594. }
  55595. else {
  55596. var parameter = {};
  55597. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  55598. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  55599. parameter._meshId = triggerOptions.parameter.mesh.id;
  55600. }
  55601. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  55602. }
  55603. }
  55604. // Serialize child action, recursively
  55605. this.actions[i].serialize(triggerObject);
  55606. // Add serialized trigger
  55607. root.children.push(triggerObject);
  55608. }
  55609. return root;
  55610. };
  55611. /**
  55612. * Creates a new ActionManager from a JSON data
  55613. * @param parsedActions defines the JSON data to read from
  55614. * @param object defines the hosting mesh
  55615. * @param scene defines the hosting scene
  55616. */
  55617. ActionManager.Parse = function (parsedActions, object, scene) {
  55618. var actionManager = new ActionManager(scene);
  55619. if (object === null) {
  55620. scene.actionManager = actionManager;
  55621. }
  55622. else {
  55623. object.actionManager = actionManager;
  55624. }
  55625. // instanciate a new object
  55626. var instanciate = function (name, params) {
  55627. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  55628. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  55629. newInstance.constructor.apply(newInstance, params);
  55630. return newInstance;
  55631. };
  55632. var parseParameter = function (name, value, target, propertyPath) {
  55633. if (propertyPath === null) {
  55634. // String, boolean or float
  55635. var floatValue = parseFloat(value);
  55636. if (value === "true" || value === "false") {
  55637. return value === "true";
  55638. }
  55639. else {
  55640. return isNaN(floatValue) ? value : floatValue;
  55641. }
  55642. }
  55643. var effectiveTarget = propertyPath.split(".");
  55644. var values = value.split(",");
  55645. // Get effective Target
  55646. for (var i = 0; i < effectiveTarget.length; i++) {
  55647. target = target[effectiveTarget[i]];
  55648. }
  55649. // Return appropriate value with its type
  55650. if (typeof (target) === "boolean") {
  55651. return values[0] === "true";
  55652. }
  55653. if (typeof (target) === "string") {
  55654. return values[0];
  55655. }
  55656. // Parameters with multiple values such as Vector3 etc.
  55657. var split = new Array();
  55658. for (var i = 0; i < values.length; i++) {
  55659. split.push(parseFloat(values[i]));
  55660. }
  55661. if (target instanceof BABYLON.Vector3) {
  55662. return BABYLON.Vector3.FromArray(split);
  55663. }
  55664. if (target instanceof BABYLON.Vector4) {
  55665. return BABYLON.Vector4.FromArray(split);
  55666. }
  55667. if (target instanceof BABYLON.Color3) {
  55668. return BABYLON.Color3.FromArray(split);
  55669. }
  55670. if (target instanceof BABYLON.Color4) {
  55671. return BABYLON.Color4.FromArray(split);
  55672. }
  55673. return parseFloat(values[0]);
  55674. };
  55675. // traverse graph per trigger
  55676. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55677. if (combineArray === void 0) { combineArray = null; }
  55678. if (parsedAction.detached) {
  55679. return;
  55680. }
  55681. var parameters = new Array();
  55682. var target = null;
  55683. var propertyPath = null;
  55684. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55685. // Parameters
  55686. if (parsedAction.type === 2) {
  55687. parameters.push(actionManager);
  55688. }
  55689. else {
  55690. parameters.push(trigger);
  55691. }
  55692. if (combine) {
  55693. var actions = new Array();
  55694. for (var j = 0; j < parsedAction.combine.length; j++) {
  55695. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55696. }
  55697. parameters.push(actions);
  55698. }
  55699. else {
  55700. for (var i = 0; i < parsedAction.properties.length; i++) {
  55701. var value = parsedAction.properties[i].value;
  55702. var name = parsedAction.properties[i].name;
  55703. var targetType = parsedAction.properties[i].targetType;
  55704. if (name === "target") {
  55705. if (targetType !== null && targetType === "SceneProperties") {
  55706. value = target = scene;
  55707. }
  55708. else {
  55709. value = target = scene.getNodeByName(value);
  55710. }
  55711. }
  55712. else if (name === "parent") {
  55713. value = scene.getNodeByName(value);
  55714. }
  55715. else if (name === "sound") {
  55716. // Can not externalize to component, so only checks for the presence off the API.
  55717. if (scene.getSoundByName) {
  55718. value = scene.getSoundByName(value);
  55719. }
  55720. }
  55721. else if (name !== "propertyPath") {
  55722. if (parsedAction.type === 2 && name === "operator") {
  55723. value = BABYLON.ValueCondition[value];
  55724. }
  55725. else {
  55726. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55727. }
  55728. }
  55729. else {
  55730. propertyPath = value;
  55731. }
  55732. parameters.push(value);
  55733. }
  55734. }
  55735. if (combineArray === null) {
  55736. parameters.push(condition);
  55737. }
  55738. else {
  55739. parameters.push(null);
  55740. }
  55741. // If interpolate value action
  55742. if (parsedAction.name === "InterpolateValueAction") {
  55743. var param = parameters[parameters.length - 2];
  55744. parameters[parameters.length - 1] = param;
  55745. parameters[parameters.length - 2] = condition;
  55746. }
  55747. // Action or condition(s) and not CombineAction
  55748. var newAction = instanciate(parsedAction.name, parameters);
  55749. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55750. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55751. if (action) {
  55752. action.then(nothing);
  55753. }
  55754. else {
  55755. actionManager.registerAction(nothing);
  55756. }
  55757. action = nothing;
  55758. }
  55759. if (combineArray === null) {
  55760. if (newAction instanceof BABYLON.Condition) {
  55761. condition = newAction;
  55762. newAction = action;
  55763. }
  55764. else {
  55765. condition = null;
  55766. if (action) {
  55767. action.then(newAction);
  55768. }
  55769. else {
  55770. actionManager.registerAction(newAction);
  55771. }
  55772. }
  55773. }
  55774. else {
  55775. combineArray.push(newAction);
  55776. }
  55777. for (var i = 0; i < parsedAction.children.length; i++) {
  55778. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55779. }
  55780. };
  55781. // triggers
  55782. for (var i = 0; i < parsedActions.children.length; i++) {
  55783. var triggerParams;
  55784. var trigger = parsedActions.children[i];
  55785. if (trigger.properties.length > 0) {
  55786. var param = trigger.properties[0].value;
  55787. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55788. if (value._meshId) {
  55789. value.mesh = scene.getMeshByID(value._meshId);
  55790. }
  55791. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55792. }
  55793. else {
  55794. triggerParams = ActionManager[trigger.name];
  55795. }
  55796. for (var j = 0; j < trigger.children.length; j++) {
  55797. if (!trigger.detached) {
  55798. traverse(trigger.children[j], triggerParams, null, null);
  55799. }
  55800. }
  55801. }
  55802. };
  55803. /**
  55804. * Get a trigger name by index
  55805. * @param trigger defines the trigger index
  55806. * @returns a trigger name
  55807. */
  55808. ActionManager.GetTriggerName = function (trigger) {
  55809. switch (trigger) {
  55810. case 0: return "NothingTrigger";
  55811. case 1: return "OnPickTrigger";
  55812. case 2: return "OnLeftPickTrigger";
  55813. case 3: return "OnRightPickTrigger";
  55814. case 4: return "OnCenterPickTrigger";
  55815. case 5: return "OnPickDownTrigger";
  55816. case 6: return "OnPickUpTrigger";
  55817. case 7: return "OnLongPressTrigger";
  55818. case 8: return "OnPointerOverTrigger";
  55819. case 9: return "OnPointerOutTrigger";
  55820. case 10: return "OnEveryFrameTrigger";
  55821. case 11: return "OnIntersectionEnterTrigger";
  55822. case 12: return "OnIntersectionExitTrigger";
  55823. case 13: return "OnKeyDownTrigger";
  55824. case 14: return "OnKeyUpTrigger";
  55825. case 15: return "OnPickOutTrigger";
  55826. default: return "";
  55827. }
  55828. };
  55829. /**
  55830. * Nothing
  55831. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55832. */
  55833. ActionManager.NothingTrigger = 0;
  55834. /**
  55835. * On pick
  55836. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55837. */
  55838. ActionManager.OnPickTrigger = 1;
  55839. /**
  55840. * On left pick
  55841. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55842. */
  55843. ActionManager.OnLeftPickTrigger = 2;
  55844. /**
  55845. * On right pick
  55846. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55847. */
  55848. ActionManager.OnRightPickTrigger = 3;
  55849. /**
  55850. * On center pick
  55851. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55852. */
  55853. ActionManager.OnCenterPickTrigger = 4;
  55854. /**
  55855. * On pick down
  55856. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55857. */
  55858. ActionManager.OnPickDownTrigger = 5;
  55859. /**
  55860. * On double pick
  55861. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55862. */
  55863. ActionManager.OnDoublePickTrigger = 6;
  55864. /**
  55865. * On pick up
  55866. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55867. */
  55868. ActionManager.OnPickUpTrigger = 7;
  55869. /**
  55870. * On pick out.
  55871. * This trigger will only be raised if you also declared a OnPickDown
  55872. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55873. */
  55874. ActionManager.OnPickOutTrigger = 16;
  55875. /**
  55876. * On long press
  55877. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55878. */
  55879. ActionManager.OnLongPressTrigger = 8;
  55880. /**
  55881. * On pointer over
  55882. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55883. */
  55884. ActionManager.OnPointerOverTrigger = 9;
  55885. /**
  55886. * On pointer out
  55887. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55888. */
  55889. ActionManager.OnPointerOutTrigger = 10;
  55890. /**
  55891. * On every frame
  55892. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55893. */
  55894. ActionManager.OnEveryFrameTrigger = 11;
  55895. /**
  55896. * On intersection enter
  55897. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55898. */
  55899. ActionManager.OnIntersectionEnterTrigger = 12;
  55900. /**
  55901. * On intersection exit
  55902. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55903. */
  55904. ActionManager.OnIntersectionExitTrigger = 13;
  55905. /**
  55906. * On key down
  55907. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55908. */
  55909. ActionManager.OnKeyDownTrigger = 14;
  55910. /**
  55911. * On key up
  55912. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55913. */
  55914. ActionManager.OnKeyUpTrigger = 15;
  55915. /** Gets the list of active triggers */
  55916. ActionManager.Triggers = {};
  55917. return ActionManager;
  55918. }());
  55919. BABYLON.ActionManager = ActionManager;
  55920. })(BABYLON || (BABYLON = {}));
  55921. //# sourceMappingURL=babylon.actionManager.js.map
  55922. var BABYLON;
  55923. (function (BABYLON) {
  55924. /**
  55925. * This defines an action responsible to change the value of a property
  55926. * by interpolating between its current value and the newly set one once triggered.
  55927. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55928. */
  55929. var InterpolateValueAction = /** @class */ (function (_super) {
  55930. __extends(InterpolateValueAction, _super);
  55931. /**
  55932. * Instantiate the action
  55933. * @param triggerOptions defines the trigger options
  55934. * @param target defines the object containing the value to interpolate
  55935. * @param propertyPath defines the path to the property in the target object
  55936. * @param value defines the target value at the end of the interpolation
  55937. * @param duration deines the time it will take for the property to interpolate to the value.
  55938. * @param condition defines the trigger related conditions
  55939. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55940. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55941. */
  55942. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55943. if (duration === void 0) { duration = 1000; }
  55944. var _this = _super.call(this, triggerOptions, condition) || this;
  55945. /**
  55946. * Defines the time it will take for the property to interpolate to the value.
  55947. */
  55948. _this.duration = 1000;
  55949. /**
  55950. * Observable triggered once the interpolation animation has been done.
  55951. */
  55952. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55953. _this.propertyPath = propertyPath;
  55954. _this.value = value;
  55955. _this.duration = duration;
  55956. _this.stopOtherAnimations = stopOtherAnimations;
  55957. _this.onInterpolationDone = onInterpolationDone;
  55958. _this._target = _this._effectiveTarget = target;
  55959. return _this;
  55960. }
  55961. /** @hidden */
  55962. InterpolateValueAction.prototype._prepare = function () {
  55963. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55964. this._property = this._getProperty(this.propertyPath);
  55965. };
  55966. /**
  55967. * Execute the action starts the value interpolation.
  55968. */
  55969. InterpolateValueAction.prototype.execute = function () {
  55970. var _this = this;
  55971. var scene = this._actionManager.getScene();
  55972. var keys = [
  55973. {
  55974. frame: 0,
  55975. value: this._effectiveTarget[this._property]
  55976. }, {
  55977. frame: 100,
  55978. value: this.value
  55979. }
  55980. ];
  55981. var dataType;
  55982. if (typeof this.value === "number") {
  55983. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55984. }
  55985. else if (this.value instanceof BABYLON.Color3) {
  55986. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55987. }
  55988. else if (this.value instanceof BABYLON.Vector3) {
  55989. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55990. }
  55991. else if (this.value instanceof BABYLON.Matrix) {
  55992. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55993. }
  55994. else if (this.value instanceof BABYLON.Quaternion) {
  55995. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55996. }
  55997. else {
  55998. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  55999. return;
  56000. }
  56001. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  56002. animation.setKeys(keys);
  56003. if (this.stopOtherAnimations) {
  56004. scene.stopAnimation(this._effectiveTarget);
  56005. }
  56006. var wrapper = function () {
  56007. _this.onInterpolationDoneObservable.notifyObservers(_this);
  56008. if (_this.onInterpolationDone) {
  56009. _this.onInterpolationDone();
  56010. }
  56011. };
  56012. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  56013. };
  56014. /**
  56015. * Serializes the actions and its related information.
  56016. * @param parent defines the object to serialize in
  56017. * @returns the serialized object
  56018. */
  56019. InterpolateValueAction.prototype.serialize = function (parent) {
  56020. return _super.prototype._serialize.call(this, {
  56021. name: "InterpolateValueAction",
  56022. properties: [
  56023. BABYLON.Action._GetTargetProperty(this._target),
  56024. { name: "propertyPath", value: this.propertyPath },
  56025. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56026. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  56027. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  56028. ]
  56029. }, parent);
  56030. };
  56031. return InterpolateValueAction;
  56032. }(BABYLON.Action));
  56033. BABYLON.InterpolateValueAction = InterpolateValueAction;
  56034. })(BABYLON || (BABYLON = {}));
  56035. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  56036. var BABYLON;
  56037. (function (BABYLON) {
  56038. /**
  56039. * This defines an action responsible to toggle a boolean once triggered.
  56040. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56041. */
  56042. var SwitchBooleanAction = /** @class */ (function (_super) {
  56043. __extends(SwitchBooleanAction, _super);
  56044. /**
  56045. * Instantiate the action
  56046. * @param triggerOptions defines the trigger options
  56047. * @param target defines the object containing the boolean
  56048. * @param propertyPath defines the path to the boolean property in the target object
  56049. * @param condition defines the trigger related conditions
  56050. */
  56051. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  56052. var _this = _super.call(this, triggerOptions, condition) || this;
  56053. _this.propertyPath = propertyPath;
  56054. _this._target = _this._effectiveTarget = target;
  56055. return _this;
  56056. }
  56057. /** @hidden */
  56058. SwitchBooleanAction.prototype._prepare = function () {
  56059. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56060. this._property = this._getProperty(this.propertyPath);
  56061. };
  56062. /**
  56063. * Execute the action toggle the boolean value.
  56064. */
  56065. SwitchBooleanAction.prototype.execute = function () {
  56066. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  56067. };
  56068. /**
  56069. * Serializes the actions and its related information.
  56070. * @param parent defines the object to serialize in
  56071. * @returns the serialized object
  56072. */
  56073. SwitchBooleanAction.prototype.serialize = function (parent) {
  56074. return _super.prototype._serialize.call(this, {
  56075. name: "SwitchBooleanAction",
  56076. properties: [
  56077. BABYLON.Action._GetTargetProperty(this._target),
  56078. { name: "propertyPath", value: this.propertyPath }
  56079. ]
  56080. }, parent);
  56081. };
  56082. return SwitchBooleanAction;
  56083. }(BABYLON.Action));
  56084. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  56085. /**
  56086. * This defines an action responsible to set a the state field of the target
  56087. * to a desired value once triggered.
  56088. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56089. */
  56090. var SetStateAction = /** @class */ (function (_super) {
  56091. __extends(SetStateAction, _super);
  56092. /**
  56093. * Instantiate the action
  56094. * @param triggerOptions defines the trigger options
  56095. * @param target defines the object containing the state property
  56096. * @param value defines the value to store in the state field
  56097. * @param condition defines the trigger related conditions
  56098. */
  56099. function SetStateAction(triggerOptions, target, value, condition) {
  56100. var _this = _super.call(this, triggerOptions, condition) || this;
  56101. _this.value = value;
  56102. _this._target = target;
  56103. return _this;
  56104. }
  56105. /**
  56106. * Execute the action and store the value on the target state property.
  56107. */
  56108. SetStateAction.prototype.execute = function () {
  56109. this._target.state = this.value;
  56110. };
  56111. /**
  56112. * Serializes the actions and its related information.
  56113. * @param parent defines the object to serialize in
  56114. * @returns the serialized object
  56115. */
  56116. SetStateAction.prototype.serialize = function (parent) {
  56117. return _super.prototype._serialize.call(this, {
  56118. name: "SetStateAction",
  56119. properties: [
  56120. BABYLON.Action._GetTargetProperty(this._target),
  56121. { name: "value", value: this.value }
  56122. ]
  56123. }, parent);
  56124. };
  56125. return SetStateAction;
  56126. }(BABYLON.Action));
  56127. BABYLON.SetStateAction = SetStateAction;
  56128. /**
  56129. * This defines an action responsible to set a property of the target
  56130. * to a desired value once triggered.
  56131. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56132. */
  56133. var SetValueAction = /** @class */ (function (_super) {
  56134. __extends(SetValueAction, _super);
  56135. /**
  56136. * Instantiate the action
  56137. * @param triggerOptions defines the trigger options
  56138. * @param target defines the object containing the property
  56139. * @param propertyPath defines the path of the property to set in the target
  56140. * @param value defines the value to set in the property
  56141. * @param condition defines the trigger related conditions
  56142. */
  56143. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  56144. var _this = _super.call(this, triggerOptions, condition) || this;
  56145. _this.propertyPath = propertyPath;
  56146. _this.value = value;
  56147. _this._target = _this._effectiveTarget = target;
  56148. return _this;
  56149. }
  56150. /** @hidden */
  56151. SetValueAction.prototype._prepare = function () {
  56152. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56153. this._property = this._getProperty(this.propertyPath);
  56154. };
  56155. /**
  56156. * Execute the action and set the targetted property to the desired value.
  56157. */
  56158. SetValueAction.prototype.execute = function () {
  56159. this._effectiveTarget[this._property] = this.value;
  56160. if (this._target.markAsDirty) {
  56161. this._target.markAsDirty(this._property);
  56162. }
  56163. };
  56164. /**
  56165. * Serializes the actions and its related information.
  56166. * @param parent defines the object to serialize in
  56167. * @returns the serialized object
  56168. */
  56169. SetValueAction.prototype.serialize = function (parent) {
  56170. return _super.prototype._serialize.call(this, {
  56171. name: "SetValueAction",
  56172. properties: [
  56173. BABYLON.Action._GetTargetProperty(this._target),
  56174. { name: "propertyPath", value: this.propertyPath },
  56175. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  56176. ]
  56177. }, parent);
  56178. };
  56179. return SetValueAction;
  56180. }(BABYLON.Action));
  56181. BABYLON.SetValueAction = SetValueAction;
  56182. /**
  56183. * This defines an action responsible to increment the target value
  56184. * to a desired value once triggered.
  56185. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56186. */
  56187. var IncrementValueAction = /** @class */ (function (_super) {
  56188. __extends(IncrementValueAction, _super);
  56189. /**
  56190. * Instantiate the action
  56191. * @param triggerOptions defines the trigger options
  56192. * @param target defines the object containing the property
  56193. * @param propertyPath defines the path of the property to increment in the target
  56194. * @param value defines the value value we should increment the property by
  56195. * @param condition defines the trigger related conditions
  56196. */
  56197. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  56198. var _this = _super.call(this, triggerOptions, condition) || this;
  56199. _this.propertyPath = propertyPath;
  56200. _this.value = value;
  56201. _this._target = _this._effectiveTarget = target;
  56202. return _this;
  56203. }
  56204. /** @hidden */
  56205. IncrementValueAction.prototype._prepare = function () {
  56206. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56207. this._property = this._getProperty(this.propertyPath);
  56208. if (typeof this._effectiveTarget[this._property] !== "number") {
  56209. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  56210. }
  56211. };
  56212. /**
  56213. * Execute the action and increment the target of the value amount.
  56214. */
  56215. IncrementValueAction.prototype.execute = function () {
  56216. this._effectiveTarget[this._property] += this.value;
  56217. if (this._target.markAsDirty) {
  56218. this._target.markAsDirty(this._property);
  56219. }
  56220. };
  56221. /**
  56222. * Serializes the actions and its related information.
  56223. * @param parent defines the object to serialize in
  56224. * @returns the serialized object
  56225. */
  56226. IncrementValueAction.prototype.serialize = function (parent) {
  56227. return _super.prototype._serialize.call(this, {
  56228. name: "IncrementValueAction",
  56229. properties: [
  56230. BABYLON.Action._GetTargetProperty(this._target),
  56231. { name: "propertyPath", value: this.propertyPath },
  56232. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  56233. ]
  56234. }, parent);
  56235. };
  56236. return IncrementValueAction;
  56237. }(BABYLON.Action));
  56238. BABYLON.IncrementValueAction = IncrementValueAction;
  56239. /**
  56240. * This defines an action responsible to start an animation once triggered.
  56241. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56242. */
  56243. var PlayAnimationAction = /** @class */ (function (_super) {
  56244. __extends(PlayAnimationAction, _super);
  56245. /**
  56246. * Instantiate the action
  56247. * @param triggerOptions defines the trigger options
  56248. * @param target defines the target animation or animation name
  56249. * @param from defines from where the animation should start (animation frame)
  56250. * @param end defines where the animation should stop (animation frame)
  56251. * @param loop defines if the animation should loop or stop after the first play
  56252. * @param condition defines the trigger related conditions
  56253. */
  56254. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  56255. var _this = _super.call(this, triggerOptions, condition) || this;
  56256. _this.from = from;
  56257. _this.to = to;
  56258. _this.loop = loop;
  56259. _this._target = target;
  56260. return _this;
  56261. }
  56262. /** @hidden */
  56263. PlayAnimationAction.prototype._prepare = function () {
  56264. };
  56265. /**
  56266. * Execute the action and play the animation.
  56267. */
  56268. PlayAnimationAction.prototype.execute = function () {
  56269. var scene = this._actionManager.getScene();
  56270. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  56271. };
  56272. /**
  56273. * Serializes the actions and its related information.
  56274. * @param parent defines the object to serialize in
  56275. * @returns the serialized object
  56276. */
  56277. PlayAnimationAction.prototype.serialize = function (parent) {
  56278. return _super.prototype._serialize.call(this, {
  56279. name: "PlayAnimationAction",
  56280. properties: [
  56281. BABYLON.Action._GetTargetProperty(this._target),
  56282. { name: "from", value: String(this.from) },
  56283. { name: "to", value: String(this.to) },
  56284. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  56285. ]
  56286. }, parent);
  56287. };
  56288. return PlayAnimationAction;
  56289. }(BABYLON.Action));
  56290. BABYLON.PlayAnimationAction = PlayAnimationAction;
  56291. /**
  56292. * This defines an action responsible to stop an animation once triggered.
  56293. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56294. */
  56295. var StopAnimationAction = /** @class */ (function (_super) {
  56296. __extends(StopAnimationAction, _super);
  56297. /**
  56298. * Instantiate the action
  56299. * @param triggerOptions defines the trigger options
  56300. * @param target defines the target animation or animation name
  56301. * @param condition defines the trigger related conditions
  56302. */
  56303. function StopAnimationAction(triggerOptions, target, condition) {
  56304. var _this = _super.call(this, triggerOptions, condition) || this;
  56305. _this._target = target;
  56306. return _this;
  56307. }
  56308. /** @hidden */
  56309. StopAnimationAction.prototype._prepare = function () {
  56310. };
  56311. /**
  56312. * Execute the action and stop the animation.
  56313. */
  56314. StopAnimationAction.prototype.execute = function () {
  56315. var scene = this._actionManager.getScene();
  56316. scene.stopAnimation(this._target);
  56317. };
  56318. /**
  56319. * Serializes the actions and its related information.
  56320. * @param parent defines the object to serialize in
  56321. * @returns the serialized object
  56322. */
  56323. StopAnimationAction.prototype.serialize = function (parent) {
  56324. return _super.prototype._serialize.call(this, {
  56325. name: "StopAnimationAction",
  56326. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  56327. }, parent);
  56328. };
  56329. return StopAnimationAction;
  56330. }(BABYLON.Action));
  56331. BABYLON.StopAnimationAction = StopAnimationAction;
  56332. /**
  56333. * This defines an action responsible that does nothing once triggered.
  56334. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56335. */
  56336. var DoNothingAction = /** @class */ (function (_super) {
  56337. __extends(DoNothingAction, _super);
  56338. /**
  56339. * Instantiate the action
  56340. * @param triggerOptions defines the trigger options
  56341. * @param condition defines the trigger related conditions
  56342. */
  56343. function DoNothingAction(triggerOptions, condition) {
  56344. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  56345. return _super.call(this, triggerOptions, condition) || this;
  56346. }
  56347. /**
  56348. * Execute the action and do nothing.
  56349. */
  56350. DoNothingAction.prototype.execute = function () {
  56351. };
  56352. /**
  56353. * Serializes the actions and its related information.
  56354. * @param parent defines the object to serialize in
  56355. * @returns the serialized object
  56356. */
  56357. DoNothingAction.prototype.serialize = function (parent) {
  56358. return _super.prototype._serialize.call(this, {
  56359. name: "DoNothingAction",
  56360. properties: []
  56361. }, parent);
  56362. };
  56363. return DoNothingAction;
  56364. }(BABYLON.Action));
  56365. BABYLON.DoNothingAction = DoNothingAction;
  56366. /**
  56367. * This defines an action responsible to trigger several actions once triggered.
  56368. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56369. */
  56370. var CombineAction = /** @class */ (function (_super) {
  56371. __extends(CombineAction, _super);
  56372. /**
  56373. * Instantiate the action
  56374. * @param triggerOptions defines the trigger options
  56375. * @param children defines the list of aggregated animations to run
  56376. * @param condition defines the trigger related conditions
  56377. */
  56378. function CombineAction(triggerOptions, children, condition) {
  56379. var _this = _super.call(this, triggerOptions, condition) || this;
  56380. _this.children = children;
  56381. return _this;
  56382. }
  56383. /** @hidden */
  56384. CombineAction.prototype._prepare = function () {
  56385. for (var index = 0; index < this.children.length; index++) {
  56386. this.children[index]._actionManager = this._actionManager;
  56387. this.children[index]._prepare();
  56388. }
  56389. };
  56390. /**
  56391. * Execute the action and executes all the aggregated actions.
  56392. */
  56393. CombineAction.prototype.execute = function (evt) {
  56394. for (var index = 0; index < this.children.length; index++) {
  56395. this.children[index].execute(evt);
  56396. }
  56397. };
  56398. /**
  56399. * Serializes the actions and its related information.
  56400. * @param parent defines the object to serialize in
  56401. * @returns the serialized object
  56402. */
  56403. CombineAction.prototype.serialize = function (parent) {
  56404. var serializationObject = _super.prototype._serialize.call(this, {
  56405. name: "CombineAction",
  56406. properties: [],
  56407. combine: []
  56408. }, parent);
  56409. for (var i = 0; i < this.children.length; i++) {
  56410. serializationObject.combine.push(this.children[i].serialize(null));
  56411. }
  56412. return serializationObject;
  56413. };
  56414. return CombineAction;
  56415. }(BABYLON.Action));
  56416. BABYLON.CombineAction = CombineAction;
  56417. /**
  56418. * This defines an action responsible to run code (external event) once triggered.
  56419. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56420. */
  56421. var ExecuteCodeAction = /** @class */ (function (_super) {
  56422. __extends(ExecuteCodeAction, _super);
  56423. /**
  56424. * Instantiate the action
  56425. * @param triggerOptions defines the trigger options
  56426. * @param func defines the callback function to run
  56427. * @param condition defines the trigger related conditions
  56428. */
  56429. function ExecuteCodeAction(triggerOptions, func, condition) {
  56430. var _this = _super.call(this, triggerOptions, condition) || this;
  56431. _this.func = func;
  56432. return _this;
  56433. }
  56434. /**
  56435. * Execute the action and run the attached code.
  56436. */
  56437. ExecuteCodeAction.prototype.execute = function (evt) {
  56438. this.func(evt);
  56439. };
  56440. return ExecuteCodeAction;
  56441. }(BABYLON.Action));
  56442. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  56443. /**
  56444. * This defines an action responsible to set the parent property of the target once triggered.
  56445. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56446. */
  56447. var SetParentAction = /** @class */ (function (_super) {
  56448. __extends(SetParentAction, _super);
  56449. /**
  56450. * Instantiate the action
  56451. * @param triggerOptions defines the trigger options
  56452. * @param target defines the target containing the parent property
  56453. * @param parent defines from where the animation should start (animation frame)
  56454. * @param condition defines the trigger related conditions
  56455. */
  56456. function SetParentAction(triggerOptions, target, parent, condition) {
  56457. var _this = _super.call(this, triggerOptions, condition) || this;
  56458. _this._target = target;
  56459. _this._parent = parent;
  56460. return _this;
  56461. }
  56462. /** @hidden */
  56463. SetParentAction.prototype._prepare = function () {
  56464. };
  56465. /**
  56466. * Execute the action and set the parent property.
  56467. */
  56468. SetParentAction.prototype.execute = function () {
  56469. if (this._target.parent === this._parent) {
  56470. return;
  56471. }
  56472. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  56473. invertParentWorldMatrix.invert();
  56474. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  56475. this._target.parent = this._parent;
  56476. };
  56477. /**
  56478. * Serializes the actions and its related information.
  56479. * @param parent defines the object to serialize in
  56480. * @returns the serialized object
  56481. */
  56482. SetParentAction.prototype.serialize = function (parent) {
  56483. return _super.prototype._serialize.call(this, {
  56484. name: "SetParentAction",
  56485. properties: [
  56486. BABYLON.Action._GetTargetProperty(this._target),
  56487. BABYLON.Action._GetTargetProperty(this._parent),
  56488. ]
  56489. }, parent);
  56490. };
  56491. return SetParentAction;
  56492. }(BABYLON.Action));
  56493. BABYLON.SetParentAction = SetParentAction;
  56494. })(BABYLON || (BABYLON = {}));
  56495. //# sourceMappingURL=babylon.directActions.js.map
  56496. var BABYLON;
  56497. (function (BABYLON) {
  56498. /**
  56499. * Class used to manage multiple sprites on the same spritesheet
  56500. * @see http://doc.babylonjs.com/babylon101/sprites
  56501. */
  56502. var SpriteManager = /** @class */ (function () {
  56503. /**
  56504. * Creates a new sprite manager
  56505. * @param name defines the manager's name
  56506. * @param imgUrl defines the sprite sheet url
  56507. * @param capacity defines the maximum allowed number of sprites
  56508. * @param cellSize defines the size of a sprite cell
  56509. * @param scene defines the hosting scene
  56510. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  56511. * @param samplingMode defines the smapling mode to use with spritesheet
  56512. */
  56513. function SpriteManager(
  56514. /** defines the manager's name */
  56515. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  56516. if (epsilon === void 0) { epsilon = 0.01; }
  56517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56518. this.name = name;
  56519. /** Gets the list of sprites */
  56520. this.sprites = new Array();
  56521. /** Gets or sets the rendering group id (0 by default) */
  56522. this.renderingGroupId = 0;
  56523. /** Gets or sets camera layer mask */
  56524. this.layerMask = 0x0FFFFFFF;
  56525. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  56526. this.fogEnabled = true;
  56527. /** Gets or sets a boolean indicating if the sprites are pickable */
  56528. this.isPickable = false;
  56529. /**
  56530. * An event triggered when the manager is disposed.
  56531. */
  56532. this.onDisposeObservable = new BABYLON.Observable();
  56533. this._vertexBuffers = {};
  56534. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  56535. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  56536. }
  56537. this._capacity = capacity;
  56538. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  56539. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56540. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56541. if (cellSize.width && cellSize.height) {
  56542. this.cellWidth = cellSize.width;
  56543. this.cellHeight = cellSize.height;
  56544. }
  56545. else if (cellSize !== undefined) {
  56546. this.cellWidth = cellSize;
  56547. this.cellHeight = cellSize;
  56548. }
  56549. else {
  56550. return;
  56551. }
  56552. this._epsilon = epsilon;
  56553. this._scene = scene;
  56554. this._scene.spriteManagers.push(this);
  56555. var indices = [];
  56556. var index = 0;
  56557. for (var count = 0; count < capacity; count++) {
  56558. indices.push(index);
  56559. indices.push(index + 1);
  56560. indices.push(index + 2);
  56561. indices.push(index);
  56562. indices.push(index + 2);
  56563. indices.push(index + 3);
  56564. index += 4;
  56565. }
  56566. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  56567. // VBO
  56568. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  56569. this._vertexData = new Float32Array(capacity * 16 * 4);
  56570. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  56571. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  56572. var options = this._buffer.createVertexBuffer("options", 4, 4);
  56573. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  56574. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  56575. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56576. this._vertexBuffers["options"] = options;
  56577. this._vertexBuffers["cellInfo"] = cellInfo;
  56578. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56579. // Effects
  56580. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  56581. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  56582. }
  56583. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  56584. /**
  56585. * Callback called when the manager is disposed
  56586. */
  56587. set: function (callback) {
  56588. if (this._onDisposeObserver) {
  56589. this.onDisposeObservable.remove(this._onDisposeObserver);
  56590. }
  56591. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56592. },
  56593. enumerable: true,
  56594. configurable: true
  56595. });
  56596. Object.defineProperty(SpriteManager.prototype, "texture", {
  56597. /**
  56598. * Gets or sets the spritesheet texture
  56599. */
  56600. get: function () {
  56601. return this._spriteTexture;
  56602. },
  56603. set: function (value) {
  56604. this._spriteTexture = value;
  56605. },
  56606. enumerable: true,
  56607. configurable: true
  56608. });
  56609. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  56610. var arrayOffset = index * 16;
  56611. if (offsetX === 0) {
  56612. offsetX = this._epsilon;
  56613. }
  56614. else if (offsetX === 1) {
  56615. offsetX = 1 - this._epsilon;
  56616. }
  56617. if (offsetY === 0) {
  56618. offsetY = this._epsilon;
  56619. }
  56620. else if (offsetY === 1) {
  56621. offsetY = 1 - this._epsilon;
  56622. }
  56623. this._vertexData[arrayOffset] = sprite.position.x;
  56624. this._vertexData[arrayOffset + 1] = sprite.position.y;
  56625. this._vertexData[arrayOffset + 2] = sprite.position.z;
  56626. this._vertexData[arrayOffset + 3] = sprite.angle;
  56627. this._vertexData[arrayOffset + 4] = sprite.width;
  56628. this._vertexData[arrayOffset + 5] = sprite.height;
  56629. this._vertexData[arrayOffset + 6] = offsetX;
  56630. this._vertexData[arrayOffset + 7] = offsetY;
  56631. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  56632. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  56633. var offset = (sprite.cellIndex / rowSize) >> 0;
  56634. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  56635. this._vertexData[arrayOffset + 11] = offset;
  56636. // Color
  56637. this._vertexData[arrayOffset + 12] = sprite.color.r;
  56638. this._vertexData[arrayOffset + 13] = sprite.color.g;
  56639. this._vertexData[arrayOffset + 14] = sprite.color.b;
  56640. this._vertexData[arrayOffset + 15] = sprite.color.a;
  56641. };
  56642. /**
  56643. * Intersects the sprites with a ray
  56644. * @param ray defines the ray to intersect with
  56645. * @param camera defines the current active camera
  56646. * @param predicate defines a predicate used to select candidate sprites
  56647. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  56648. * @returns null if no hit or a PickingInfo
  56649. */
  56650. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  56651. var count = Math.min(this._capacity, this.sprites.length);
  56652. var min = BABYLON.Vector3.Zero();
  56653. var max = BABYLON.Vector3.Zero();
  56654. var distance = Number.MAX_VALUE;
  56655. var currentSprite = null;
  56656. var cameraSpacePosition = BABYLON.Vector3.Zero();
  56657. var cameraView = camera.getViewMatrix();
  56658. for (var index = 0; index < count; index++) {
  56659. var sprite = this.sprites[index];
  56660. if (!sprite) {
  56661. continue;
  56662. }
  56663. if (predicate) {
  56664. if (!predicate(sprite)) {
  56665. continue;
  56666. }
  56667. }
  56668. else if (!sprite.isPickable) {
  56669. continue;
  56670. }
  56671. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  56672. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  56673. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  56674. if (ray.intersectsBoxMinMax(min, max)) {
  56675. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  56676. if (distance > currentDistance) {
  56677. distance = currentDistance;
  56678. currentSprite = sprite;
  56679. if (fastCheck) {
  56680. break;
  56681. }
  56682. }
  56683. }
  56684. }
  56685. if (currentSprite) {
  56686. var result = new BABYLON.PickingInfo();
  56687. result.hit = true;
  56688. result.pickedSprite = currentSprite;
  56689. result.distance = distance;
  56690. return result;
  56691. }
  56692. return null;
  56693. };
  56694. /**
  56695. * Render all child sprites
  56696. */
  56697. SpriteManager.prototype.render = function () {
  56698. // Check
  56699. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  56700. return;
  56701. }
  56702. var engine = this._scene.getEngine();
  56703. var baseSize = this._spriteTexture.getBaseSize();
  56704. // Sprites
  56705. var deltaTime = engine.getDeltaTime();
  56706. var max = Math.min(this._capacity, this.sprites.length);
  56707. var rowSize = baseSize.width / this.cellWidth;
  56708. var offset = 0;
  56709. for (var index = 0; index < max; index++) {
  56710. var sprite = this.sprites[index];
  56711. if (!sprite || !sprite.isVisible) {
  56712. continue;
  56713. }
  56714. sprite._animate(deltaTime);
  56715. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  56716. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  56717. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  56718. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  56719. }
  56720. this._buffer.update(this._vertexData);
  56721. // Render
  56722. var effect = this._effectBase;
  56723. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56724. effect = this._effectFog;
  56725. }
  56726. engine.enableEffect(effect);
  56727. var viewMatrix = this._scene.getViewMatrix();
  56728. effect.setTexture("diffuseSampler", this._spriteTexture);
  56729. effect.setMatrix("view", viewMatrix);
  56730. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56731. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  56732. // Fog
  56733. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56734. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56735. effect.setColor3("vFogColor", this._scene.fogColor);
  56736. }
  56737. // VBOs
  56738. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56739. // Draw order
  56740. engine.setDepthFunctionToLessOrEqual();
  56741. effect.setBool("alphaTest", true);
  56742. engine.setColorWrite(false);
  56743. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56744. engine.setColorWrite(true);
  56745. effect.setBool("alphaTest", false);
  56746. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56747. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56748. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56749. };
  56750. /**
  56751. * Release associated resources
  56752. */
  56753. SpriteManager.prototype.dispose = function () {
  56754. if (this._buffer) {
  56755. this._buffer.dispose();
  56756. this._buffer = null;
  56757. }
  56758. if (this._indexBuffer) {
  56759. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56760. this._indexBuffer = null;
  56761. }
  56762. if (this._spriteTexture) {
  56763. this._spriteTexture.dispose();
  56764. this._spriteTexture = null;
  56765. }
  56766. // Remove from scene
  56767. var index = this._scene.spriteManagers.indexOf(this);
  56768. this._scene.spriteManagers.splice(index, 1);
  56769. // Callback
  56770. this.onDisposeObservable.notifyObservers(this);
  56771. this.onDisposeObservable.clear();
  56772. };
  56773. return SpriteManager;
  56774. }());
  56775. BABYLON.SpriteManager = SpriteManager;
  56776. })(BABYLON || (BABYLON = {}));
  56777. //# sourceMappingURL=babylon.spriteManager.js.map
  56778. var BABYLON;
  56779. (function (BABYLON) {
  56780. /**
  56781. * Class used to represent a sprite
  56782. * @see http://doc.babylonjs.com/babylon101/sprites
  56783. */
  56784. var Sprite = /** @class */ (function () {
  56785. /**
  56786. * Creates a new Sprite
  56787. * @param name defines the name
  56788. * @param manager defines the manager
  56789. */
  56790. function Sprite(
  56791. /** defines the name */
  56792. name, manager) {
  56793. this.name = name;
  56794. /** Gets or sets the main color */
  56795. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56796. /** Gets or sets the width */
  56797. this.width = 1.0;
  56798. /** Gets or sets the height */
  56799. this.height = 1.0;
  56800. /** Gets or sets rotation angle */
  56801. this.angle = 0;
  56802. /** Gets or sets the cell index in the sprite sheet */
  56803. this.cellIndex = 0;
  56804. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  56805. this.invertU = 0;
  56806. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  56807. this.invertV = 0;
  56808. /** Gets the list of attached animations */
  56809. this.animations = new Array();
  56810. /** Gets or sets a boolean indicating if the sprite can be picked */
  56811. this.isPickable = false;
  56812. this._animationStarted = false;
  56813. this._loopAnimation = false;
  56814. this._fromIndex = 0;
  56815. this._toIndex = 0;
  56816. this._delay = 0;
  56817. this._direction = 1;
  56818. this._time = 0;
  56819. /**
  56820. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56821. */
  56822. this.isVisible = true;
  56823. this._manager = manager;
  56824. this._manager.sprites.push(this);
  56825. this.position = BABYLON.Vector3.Zero();
  56826. }
  56827. Object.defineProperty(Sprite.prototype, "size", {
  56828. /**
  56829. * Gets or sets the sprite size
  56830. */
  56831. get: function () {
  56832. return this.width;
  56833. },
  56834. set: function (value) {
  56835. this.width = value;
  56836. this.height = value;
  56837. },
  56838. enumerable: true,
  56839. configurable: true
  56840. });
  56841. /**
  56842. * Starts an animation
  56843. * @param from defines the initial key
  56844. * @param to defines the end key
  56845. * @param loop defines if the animation must loop
  56846. * @param delay defines the start delay (in ms)
  56847. * @param onAnimationEnd defines a callback to call when animation ends
  56848. */
  56849. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56850. this._fromIndex = from;
  56851. this._toIndex = to;
  56852. this._loopAnimation = loop;
  56853. this._delay = delay;
  56854. this._animationStarted = true;
  56855. this._direction = from < to ? 1 : -1;
  56856. this.cellIndex = from;
  56857. this._time = 0;
  56858. this._onAnimationEnd = onAnimationEnd;
  56859. };
  56860. /** Stops current animation (if any) */
  56861. Sprite.prototype.stopAnimation = function () {
  56862. this._animationStarted = false;
  56863. };
  56864. /** @hidden */
  56865. Sprite.prototype._animate = function (deltaTime) {
  56866. if (!this._animationStarted) {
  56867. return;
  56868. }
  56869. this._time += deltaTime;
  56870. if (this._time > this._delay) {
  56871. this._time = this._time % this._delay;
  56872. this.cellIndex += this._direction;
  56873. if (this.cellIndex > this._toIndex) {
  56874. if (this._loopAnimation) {
  56875. this.cellIndex = this._fromIndex;
  56876. }
  56877. else {
  56878. this.cellIndex = this._toIndex;
  56879. this._animationStarted = false;
  56880. if (this._onAnimationEnd) {
  56881. this._onAnimationEnd();
  56882. }
  56883. if (this.disposeWhenFinishedAnimating) {
  56884. this.dispose();
  56885. }
  56886. }
  56887. }
  56888. }
  56889. };
  56890. /** Release associated resources */
  56891. Sprite.prototype.dispose = function () {
  56892. for (var i = 0; i < this._manager.sprites.length; i++) {
  56893. if (this._manager.sprites[i] == this) {
  56894. this._manager.sprites.splice(i, 1);
  56895. }
  56896. }
  56897. };
  56898. return Sprite;
  56899. }());
  56900. BABYLON.Sprite = Sprite;
  56901. })(BABYLON || (BABYLON = {}));
  56902. //# sourceMappingURL=babylon.sprite.js.map
  56903. var BABYLON;
  56904. (function (BABYLON) {
  56905. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56906. if (!BABYLON.PickingInfo) {
  56907. return null;
  56908. }
  56909. var pickingInfo = null;
  56910. if (!camera) {
  56911. if (!this.activeCamera) {
  56912. return null;
  56913. }
  56914. camera = this.activeCamera;
  56915. }
  56916. if (this.spriteManagers.length > 0) {
  56917. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56918. var spriteManager = this.spriteManagers[spriteIndex];
  56919. if (!spriteManager.isPickable) {
  56920. continue;
  56921. }
  56922. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56923. if (!result || !result.hit) {
  56924. continue;
  56925. }
  56926. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  56927. continue;
  56928. }
  56929. pickingInfo = result;
  56930. if (fastCheck) {
  56931. break;
  56932. }
  56933. }
  56934. }
  56935. return pickingInfo || new BABYLON.PickingInfo();
  56936. };
  56937. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56938. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56939. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56940. };
  56941. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56942. if (!this._tempSpritePickingRay) {
  56943. return null;
  56944. }
  56945. if (!camera) {
  56946. if (!this.activeCamera) {
  56947. return null;
  56948. }
  56949. camera = this.activeCamera;
  56950. }
  56951. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56952. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56953. };
  56954. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56955. if (this._pointerOverSprite === sprite) {
  56956. return;
  56957. }
  56958. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56959. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56960. }
  56961. this._pointerOverSprite = sprite;
  56962. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56963. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56964. }
  56965. };
  56966. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56967. return this._pointerOverSprite;
  56968. };
  56969. /**
  56970. * Defines the sprite scene component responsible to manage sprites
  56971. * in a given scene.
  56972. */
  56973. var SpriteSceneComponent = /** @class */ (function () {
  56974. /**
  56975. * Creates a new instance of the component for the given scene
  56976. * @param scene Defines the scene to register the component in
  56977. */
  56978. function SpriteSceneComponent(scene) {
  56979. /**
  56980. * The component name helpfull to identify the component in the list of scene components.
  56981. */
  56982. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56983. this.scene = scene;
  56984. this.scene.spriteManagers = new Array();
  56985. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56986. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56987. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56988. this._spritePredicate = function (sprite) {
  56989. if (!sprite.actionManager) {
  56990. return false;
  56991. }
  56992. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  56993. };
  56994. }
  56995. /**
  56996. * Registers the component in a given scene
  56997. */
  56998. SpriteSceneComponent.prototype.register = function () {
  56999. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  57000. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  57001. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  57002. };
  57003. /**
  57004. * Rebuilds the elements related to this component in case of
  57005. * context lost for instance.
  57006. */
  57007. SpriteSceneComponent.prototype.rebuild = function () {
  57008. /** Nothing to do for sprites */
  57009. };
  57010. /**
  57011. * Disposes the component and the associated ressources.
  57012. */
  57013. SpriteSceneComponent.prototype.dispose = function () {
  57014. this.scene.onBeforeSpritesRenderingObservable.clear();
  57015. this.scene.onAfterSpritesRenderingObservable.clear();
  57016. var spriteManagers = this.scene.spriteManagers;
  57017. while (spriteManagers.length) {
  57018. spriteManagers[0].dispose();
  57019. }
  57020. };
  57021. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  57022. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  57023. if (result) {
  57024. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  57025. }
  57026. return result;
  57027. };
  57028. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  57029. var scene = this.scene;
  57030. if (isMeshPicked) {
  57031. scene.setPointerOverSprite(null);
  57032. }
  57033. else {
  57034. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  57035. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  57036. scene.setPointerOverSprite(pickResult.pickedSprite);
  57037. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  57038. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  57039. }
  57040. else {
  57041. canvas.style.cursor = scene.hoverCursor;
  57042. }
  57043. }
  57044. else {
  57045. scene.setPointerOverSprite(null);
  57046. }
  57047. }
  57048. return pickResult;
  57049. };
  57050. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  57051. var scene = this.scene;
  57052. scene._pickedDownSprite = null;
  57053. if (scene.spriteManagers.length > 0) {
  57054. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  57055. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  57056. if (pickResult.pickedSprite.actionManager) {
  57057. scene._pickedDownSprite = pickResult.pickedSprite;
  57058. switch (evt.button) {
  57059. case 0:
  57060. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57061. break;
  57062. case 1:
  57063. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57064. break;
  57065. case 2:
  57066. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57067. break;
  57068. }
  57069. if (pickResult.pickedSprite.actionManager) {
  57070. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57071. }
  57072. }
  57073. }
  57074. }
  57075. return pickResult;
  57076. };
  57077. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  57078. var scene = this.scene;
  57079. if (scene.spriteManagers.length > 0) {
  57080. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  57081. if (spritePickResult) {
  57082. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  57083. if (spritePickResult.pickedSprite.actionManager) {
  57084. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  57085. if (spritePickResult.pickedSprite.actionManager) {
  57086. if (!this.scene._isPointerSwiping()) {
  57087. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  57088. }
  57089. }
  57090. }
  57091. }
  57092. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  57093. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  57094. }
  57095. }
  57096. }
  57097. return pickResult;
  57098. };
  57099. return SpriteSceneComponent;
  57100. }());
  57101. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  57102. })(BABYLON || (BABYLON = {}));
  57103. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  57104. var BABYLON;
  57105. (function (BABYLON) {
  57106. /**
  57107. * @hidden
  57108. */
  57109. var IntersectionInfo = /** @class */ (function () {
  57110. function IntersectionInfo(bu, bv, distance) {
  57111. this.bu = bu;
  57112. this.bv = bv;
  57113. this.distance = distance;
  57114. this.faceId = 0;
  57115. this.subMeshId = 0;
  57116. }
  57117. return IntersectionInfo;
  57118. }());
  57119. BABYLON.IntersectionInfo = IntersectionInfo;
  57120. /**
  57121. * Information about the result of picking within a scene
  57122. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  57123. */
  57124. var PickingInfo = /** @class */ (function () {
  57125. function PickingInfo() {
  57126. /**
  57127. * If the pick collided with an object
  57128. */
  57129. this.hit = false;
  57130. /**
  57131. * Distance away where the pick collided
  57132. */
  57133. this.distance = 0;
  57134. /**
  57135. * The location of pick collision
  57136. */
  57137. this.pickedPoint = null;
  57138. /**
  57139. * The mesh corresponding the the pick collision
  57140. */
  57141. this.pickedMesh = null;
  57142. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  57143. this.bu = 0;
  57144. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  57145. this.bv = 0;
  57146. /** The id of the face on the mesh that was picked */
  57147. this.faceId = -1;
  57148. /** Id of the the submesh that was picked */
  57149. this.subMeshId = 0;
  57150. /** If a sprite was picked, this will be the sprite the pick collided with */
  57151. this.pickedSprite = null;
  57152. /**
  57153. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  57154. */
  57155. this.originMesh = null;
  57156. /**
  57157. * The ray that was used to perform the picking.
  57158. */
  57159. this.ray = null;
  57160. }
  57161. /**
  57162. * Gets the normal correspodning to the face the pick collided with
  57163. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  57164. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  57165. * @returns The normal correspodning to the face the pick collided with
  57166. */
  57167. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  57168. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  57169. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  57170. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  57171. return null;
  57172. }
  57173. var indices = this.pickedMesh.getIndices();
  57174. if (!indices) {
  57175. return null;
  57176. }
  57177. var result;
  57178. if (useVerticesNormals) {
  57179. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57180. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  57181. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  57182. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  57183. normal0 = normal0.scale(this.bu);
  57184. normal1 = normal1.scale(this.bv);
  57185. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  57186. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  57187. }
  57188. else {
  57189. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57190. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  57191. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  57192. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  57193. var p1p2 = vertex1.subtract(vertex2);
  57194. var p3p2 = vertex3.subtract(vertex2);
  57195. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  57196. }
  57197. if (useWorldCoordinates) {
  57198. var wm = this.pickedMesh.getWorldMatrix();
  57199. if (this.pickedMesh.nonUniformScaling) {
  57200. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  57201. wm = BABYLON.Tmp.Matrix[0];
  57202. wm.setTranslationFromFloats(0, 0, 0);
  57203. wm.invert();
  57204. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  57205. wm = BABYLON.Tmp.Matrix[1];
  57206. }
  57207. result = BABYLON.Vector3.TransformNormal(result, wm);
  57208. }
  57209. result.normalize();
  57210. return result;
  57211. };
  57212. /**
  57213. * Gets the texture coordinates of where the pick occured
  57214. * @returns the vector containing the coordnates of the texture
  57215. */
  57216. PickingInfo.prototype.getTextureCoordinates = function () {
  57217. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57218. return null;
  57219. }
  57220. var indices = this.pickedMesh.getIndices();
  57221. if (!indices) {
  57222. return null;
  57223. }
  57224. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57225. if (!uvs) {
  57226. return null;
  57227. }
  57228. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  57229. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  57230. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  57231. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  57232. uv1 = uv1.scale(this.bu);
  57233. uv2 = uv2.scale(this.bv);
  57234. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  57235. };
  57236. return PickingInfo;
  57237. }());
  57238. BABYLON.PickingInfo = PickingInfo;
  57239. })(BABYLON || (BABYLON = {}));
  57240. //# sourceMappingURL=babylon.pickingInfo.js.map
  57241. var BABYLON;
  57242. (function (BABYLON) {
  57243. /**
  57244. * Class representing a ray with position and direction
  57245. */
  57246. var Ray = /** @class */ (function () {
  57247. /**
  57248. * Creates a new ray
  57249. * @param origin origin point
  57250. * @param direction direction
  57251. * @param length length of the ray
  57252. */
  57253. function Ray(
  57254. /** origin point */
  57255. origin,
  57256. /** direction */
  57257. direction,
  57258. /** length of the ray */
  57259. length) {
  57260. if (length === void 0) { length = Number.MAX_VALUE; }
  57261. this.origin = origin;
  57262. this.direction = direction;
  57263. this.length = length;
  57264. }
  57265. // Methods
  57266. /**
  57267. * Checks if the ray intersects a box
  57268. * @param minimum bound of the box
  57269. * @param maximum bound of the box
  57270. * @returns if the box was hit
  57271. */
  57272. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  57273. var d = 0.0;
  57274. var maxValue = Number.MAX_VALUE;
  57275. var inv;
  57276. var min;
  57277. var max;
  57278. var temp;
  57279. if (Math.abs(this.direction.x) < 0.0000001) {
  57280. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  57281. return false;
  57282. }
  57283. }
  57284. else {
  57285. inv = 1.0 / this.direction.x;
  57286. min = (minimum.x - this.origin.x) * inv;
  57287. max = (maximum.x - this.origin.x) * inv;
  57288. if (max === -Infinity) {
  57289. max = Infinity;
  57290. }
  57291. if (min > max) {
  57292. temp = min;
  57293. min = max;
  57294. max = temp;
  57295. }
  57296. d = Math.max(min, d);
  57297. maxValue = Math.min(max, maxValue);
  57298. if (d > maxValue) {
  57299. return false;
  57300. }
  57301. }
  57302. if (Math.abs(this.direction.y) < 0.0000001) {
  57303. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  57304. return false;
  57305. }
  57306. }
  57307. else {
  57308. inv = 1.0 / this.direction.y;
  57309. min = (minimum.y - this.origin.y) * inv;
  57310. max = (maximum.y - this.origin.y) * inv;
  57311. if (max === -Infinity) {
  57312. max = Infinity;
  57313. }
  57314. if (min > max) {
  57315. temp = min;
  57316. min = max;
  57317. max = temp;
  57318. }
  57319. d = Math.max(min, d);
  57320. maxValue = Math.min(max, maxValue);
  57321. if (d > maxValue) {
  57322. return false;
  57323. }
  57324. }
  57325. if (Math.abs(this.direction.z) < 0.0000001) {
  57326. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  57327. return false;
  57328. }
  57329. }
  57330. else {
  57331. inv = 1.0 / this.direction.z;
  57332. min = (minimum.z - this.origin.z) * inv;
  57333. max = (maximum.z - this.origin.z) * inv;
  57334. if (max === -Infinity) {
  57335. max = Infinity;
  57336. }
  57337. if (min > max) {
  57338. temp = min;
  57339. min = max;
  57340. max = temp;
  57341. }
  57342. d = Math.max(min, d);
  57343. maxValue = Math.min(max, maxValue);
  57344. if (d > maxValue) {
  57345. return false;
  57346. }
  57347. }
  57348. return true;
  57349. };
  57350. /**
  57351. * Checks if the ray intersects a box
  57352. * @param box the bounding box to check
  57353. * @returns if the box was hit
  57354. */
  57355. Ray.prototype.intersectsBox = function (box) {
  57356. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  57357. };
  57358. /**
  57359. * If the ray hits a sphere
  57360. * @param sphere the bounding sphere to check
  57361. * @returns true if it hits the sphere
  57362. */
  57363. Ray.prototype.intersectsSphere = function (sphere) {
  57364. var x = sphere.center.x - this.origin.x;
  57365. var y = sphere.center.y - this.origin.y;
  57366. var z = sphere.center.z - this.origin.z;
  57367. var pyth = (x * x) + (y * y) + (z * z);
  57368. var rr = sphere.radius * sphere.radius;
  57369. if (pyth <= rr) {
  57370. return true;
  57371. }
  57372. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  57373. if (dot < 0.0) {
  57374. return false;
  57375. }
  57376. var temp = pyth - (dot * dot);
  57377. return temp <= rr;
  57378. };
  57379. /**
  57380. * If the ray hits a triange
  57381. * @param vertex0 triangle vertex
  57382. * @param vertex1 triangle vertex
  57383. * @param vertex2 triangle vertex
  57384. * @returns intersection information if hit
  57385. */
  57386. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  57387. if (!this._edge1) {
  57388. this._edge1 = BABYLON.Vector3.Zero();
  57389. this._edge2 = BABYLON.Vector3.Zero();
  57390. this._pvec = BABYLON.Vector3.Zero();
  57391. this._tvec = BABYLON.Vector3.Zero();
  57392. this._qvec = BABYLON.Vector3.Zero();
  57393. }
  57394. vertex1.subtractToRef(vertex0, this._edge1);
  57395. vertex2.subtractToRef(vertex0, this._edge2);
  57396. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  57397. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  57398. if (det === 0) {
  57399. return null;
  57400. }
  57401. var invdet = 1 / det;
  57402. this.origin.subtractToRef(vertex0, this._tvec);
  57403. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  57404. if (bu < 0 || bu > 1.0) {
  57405. return null;
  57406. }
  57407. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  57408. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  57409. if (bv < 0 || bu + bv > 1.0) {
  57410. return null;
  57411. }
  57412. //check if the distance is longer than the predefined length.
  57413. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  57414. if (distance > this.length) {
  57415. return null;
  57416. }
  57417. return new BABYLON.IntersectionInfo(bu, bv, distance);
  57418. };
  57419. /**
  57420. * Checks if ray intersects a plane
  57421. * @param plane the plane to check
  57422. * @returns the distance away it was hit
  57423. */
  57424. Ray.prototype.intersectsPlane = function (plane) {
  57425. var distance;
  57426. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  57427. if (Math.abs(result1) < 9.99999997475243E-07) {
  57428. return null;
  57429. }
  57430. else {
  57431. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  57432. distance = (-plane.d - result2) / result1;
  57433. if (distance < 0.0) {
  57434. if (distance < -9.99999997475243E-07) {
  57435. return null;
  57436. }
  57437. else {
  57438. return 0;
  57439. }
  57440. }
  57441. return distance;
  57442. }
  57443. };
  57444. /**
  57445. * Checks if ray intersects a mesh
  57446. * @param mesh the mesh to check
  57447. * @param fastCheck if only the bounding box should checked
  57448. * @returns picking info of the intersecton
  57449. */
  57450. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  57451. var tm = BABYLON.Tmp.Matrix[0];
  57452. mesh.getWorldMatrix().invertToRef(tm);
  57453. if (this._tmpRay) {
  57454. Ray.TransformToRef(this, tm, this._tmpRay);
  57455. }
  57456. else {
  57457. this._tmpRay = Ray.Transform(this, tm);
  57458. }
  57459. return mesh.intersects(this._tmpRay, fastCheck);
  57460. };
  57461. /**
  57462. * Checks if ray intersects a mesh
  57463. * @param meshes the meshes to check
  57464. * @param fastCheck if only the bounding box should checked
  57465. * @param results array to store result in
  57466. * @returns Array of picking infos
  57467. */
  57468. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  57469. if (results) {
  57470. results.length = 0;
  57471. }
  57472. else {
  57473. results = [];
  57474. }
  57475. for (var i = 0; i < meshes.length; i++) {
  57476. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  57477. if (pickInfo.hit) {
  57478. results.push(pickInfo);
  57479. }
  57480. }
  57481. results.sort(this._comparePickingInfo);
  57482. return results;
  57483. };
  57484. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  57485. if (pickingInfoA.distance < pickingInfoB.distance) {
  57486. return -1;
  57487. }
  57488. else if (pickingInfoA.distance > pickingInfoB.distance) {
  57489. return 1;
  57490. }
  57491. else {
  57492. return 0;
  57493. }
  57494. };
  57495. /**
  57496. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  57497. * @param sega the first point of the segment to test the intersection against
  57498. * @param segb the second point of the segment to test the intersection against
  57499. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  57500. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  57501. */
  57502. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  57503. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  57504. var u = segb.subtract(sega);
  57505. var v = rsegb.subtract(this.origin);
  57506. var w = sega.subtract(this.origin);
  57507. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  57508. var b = BABYLON.Vector3.Dot(u, v);
  57509. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  57510. var d = BABYLON.Vector3.Dot(u, w);
  57511. var e = BABYLON.Vector3.Dot(v, w);
  57512. var D = a * c - b * b; // always >= 0
  57513. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  57514. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  57515. // compute the line parameters of the two closest points
  57516. if (D < Ray.smallnum) { // the lines are almost parallel
  57517. sN = 0.0; // force using point P0 on segment S1
  57518. sD = 1.0; // to prevent possible division by 0.0 later
  57519. tN = e;
  57520. tD = c;
  57521. }
  57522. else { // get the closest points on the infinite lines
  57523. sN = (b * e - c * d);
  57524. tN = (a * e - b * d);
  57525. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  57526. sN = 0.0;
  57527. tN = e;
  57528. tD = c;
  57529. }
  57530. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  57531. sN = sD;
  57532. tN = e + b;
  57533. tD = c;
  57534. }
  57535. }
  57536. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  57537. tN = 0.0;
  57538. // recompute sc for this edge
  57539. if (-d < 0.0) {
  57540. sN = 0.0;
  57541. }
  57542. else if (-d > a) {
  57543. sN = sD;
  57544. }
  57545. else {
  57546. sN = -d;
  57547. sD = a;
  57548. }
  57549. }
  57550. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  57551. tN = tD;
  57552. // recompute sc for this edge
  57553. if ((-d + b) < 0.0) {
  57554. sN = 0;
  57555. }
  57556. else if ((-d + b) > a) {
  57557. sN = sD;
  57558. }
  57559. else {
  57560. sN = (-d + b);
  57561. sD = a;
  57562. }
  57563. }
  57564. // finally do the division to get sc and tc
  57565. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  57566. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  57567. // get the difference of the two closest points
  57568. var qtc = v.multiplyByFloats(tc, tc, tc);
  57569. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  57570. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  57571. if (isIntersected) {
  57572. return qtc.length();
  57573. }
  57574. return -1;
  57575. };
  57576. /**
  57577. * Update the ray from viewport position
  57578. * @param x position
  57579. * @param y y position
  57580. * @param viewportWidth viewport width
  57581. * @param viewportHeight viewport height
  57582. * @param world world matrix
  57583. * @param view view matrix
  57584. * @param projection projection matrix
  57585. * @returns this ray updated
  57586. */
  57587. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57588. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  57589. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  57590. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  57591. this.direction.normalize();
  57592. return this;
  57593. };
  57594. // Statics
  57595. /**
  57596. * Creates a ray with origin and direction of 0,0,0
  57597. * @returns the new ray
  57598. */
  57599. Ray.Zero = function () {
  57600. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  57601. };
  57602. /**
  57603. * Creates a new ray from screen space and viewport
  57604. * @param x position
  57605. * @param y y position
  57606. * @param viewportWidth viewport width
  57607. * @param viewportHeight viewport height
  57608. * @param world world matrix
  57609. * @param view view matrix
  57610. * @param projection projection matrix
  57611. * @returns new ray
  57612. */
  57613. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57614. var result = Ray.Zero();
  57615. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  57616. };
  57617. /**
  57618. * 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
  57619. * transformed to the given world matrix.
  57620. * @param origin The origin point
  57621. * @param end The end point
  57622. * @param world a matrix to transform the ray to. Default is the identity matrix.
  57623. * @returns the new ray
  57624. */
  57625. Ray.CreateNewFromTo = function (origin, end, world) {
  57626. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  57627. var direction = end.subtract(origin);
  57628. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  57629. direction.normalize();
  57630. return Ray.Transform(new Ray(origin, direction, length), world);
  57631. };
  57632. /**
  57633. * Transforms a ray by a matrix
  57634. * @param ray ray to transform
  57635. * @param matrix matrix to apply
  57636. * @returns the resulting new ray
  57637. */
  57638. Ray.Transform = function (ray, matrix) {
  57639. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  57640. Ray.TransformToRef(ray, matrix, result);
  57641. return result;
  57642. };
  57643. /**
  57644. * Transforms a ray by a matrix
  57645. * @param ray ray to transform
  57646. * @param matrix matrix to apply
  57647. * @param result ray to store result in
  57648. */
  57649. Ray.TransformToRef = function (ray, matrix, result) {
  57650. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  57651. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  57652. result.length = ray.length;
  57653. var dir = result.direction;
  57654. var len = dir.length();
  57655. if (!(len === 0 || len === 1)) {
  57656. var num = 1.0 / len;
  57657. dir.x *= num;
  57658. dir.y *= num;
  57659. dir.z *= num;
  57660. result.length *= len;
  57661. }
  57662. };
  57663. Ray.smallnum = 0.00000001;
  57664. Ray.rayl = 10e8;
  57665. return Ray;
  57666. }());
  57667. BABYLON.Ray = Ray;
  57668. })(BABYLON || (BABYLON = {}));
  57669. //# sourceMappingURL=babylon.ray.js.map
  57670. var BABYLON;
  57671. (function (BABYLON) {
  57672. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  57673. if (boxMin.x > sphereCenter.x + sphereRadius) {
  57674. return false;
  57675. }
  57676. if (sphereCenter.x - sphereRadius > boxMax.x) {
  57677. return false;
  57678. }
  57679. if (boxMin.y > sphereCenter.y + sphereRadius) {
  57680. return false;
  57681. }
  57682. if (sphereCenter.y - sphereRadius > boxMax.y) {
  57683. return false;
  57684. }
  57685. if (boxMin.z > sphereCenter.z + sphereRadius) {
  57686. return false;
  57687. }
  57688. if (sphereCenter.z - sphereRadius > boxMax.z) {
  57689. return false;
  57690. }
  57691. return true;
  57692. };
  57693. var getLowestRoot = (function () {
  57694. var result = { root: 0, found: false };
  57695. return function (a, b, c, maxR) {
  57696. result.root = 0;
  57697. result.found = false;
  57698. var determinant = b * b - 4.0 * a * c;
  57699. if (determinant < 0) {
  57700. return result;
  57701. }
  57702. var sqrtD = Math.sqrt(determinant);
  57703. var r1 = (-b - sqrtD) / (2.0 * a);
  57704. var r2 = (-b + sqrtD) / (2.0 * a);
  57705. if (r1 > r2) {
  57706. var temp = r2;
  57707. r2 = r1;
  57708. r1 = temp;
  57709. }
  57710. if (r1 > 0 && r1 < maxR) {
  57711. result.root = r1;
  57712. result.found = true;
  57713. return result;
  57714. }
  57715. if (r2 > 0 && r2 < maxR) {
  57716. result.root = r2;
  57717. result.found = true;
  57718. return result;
  57719. }
  57720. return result;
  57721. };
  57722. })();
  57723. /** @hidden */
  57724. var Collider = /** @class */ (function () {
  57725. function Collider() {
  57726. this._collisionPoint = BABYLON.Vector3.Zero();
  57727. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  57728. this._tempVector = BABYLON.Vector3.Zero();
  57729. this._tempVector2 = BABYLON.Vector3.Zero();
  57730. this._tempVector3 = BABYLON.Vector3.Zero();
  57731. this._tempVector4 = BABYLON.Vector3.Zero();
  57732. this._edge = BABYLON.Vector3.Zero();
  57733. this._baseToVertex = BABYLON.Vector3.Zero();
  57734. this._destinationPoint = BABYLON.Vector3.Zero();
  57735. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  57736. this._displacementVector = BABYLON.Vector3.Zero();
  57737. /** @hidden */
  57738. this._radius = BABYLON.Vector3.One();
  57739. /** @hidden */
  57740. this._retry = 0;
  57741. /** @hidden */
  57742. this._basePointWorld = BABYLON.Vector3.Zero();
  57743. this._velocityWorld = BABYLON.Vector3.Zero();
  57744. this._normalizedVelocity = BABYLON.Vector3.Zero();
  57745. this._collisionMask = -1;
  57746. }
  57747. Object.defineProperty(Collider.prototype, "collisionMask", {
  57748. get: function () {
  57749. return this._collisionMask;
  57750. },
  57751. set: function (mask) {
  57752. this._collisionMask = !isNaN(mask) ? mask : -1;
  57753. },
  57754. enumerable: true,
  57755. configurable: true
  57756. });
  57757. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  57758. /**
  57759. * Gets the plane normal used to compute the sliding response (in local space)
  57760. */
  57761. get: function () {
  57762. return this._slidePlaneNormal;
  57763. },
  57764. enumerable: true,
  57765. configurable: true
  57766. });
  57767. // Methods
  57768. /** @hidden */
  57769. Collider.prototype._initialize = function (source, dir, e) {
  57770. this._velocity = dir;
  57771. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  57772. this._basePoint = source;
  57773. source.multiplyToRef(this._radius, this._basePointWorld);
  57774. dir.multiplyToRef(this._radius, this._velocityWorld);
  57775. this._velocityWorldLength = this._velocityWorld.length();
  57776. this._epsilon = e;
  57777. this.collisionFound = false;
  57778. };
  57779. /** @hidden */
  57780. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  57781. pa.subtractToRef(point, this._tempVector);
  57782. pb.subtractToRef(point, this._tempVector2);
  57783. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  57784. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57785. if (d < 0) {
  57786. return false;
  57787. }
  57788. pc.subtractToRef(point, this._tempVector3);
  57789. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  57790. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57791. if (d < 0) {
  57792. return false;
  57793. }
  57794. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  57795. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57796. return d >= 0;
  57797. };
  57798. /** @hidden */
  57799. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  57800. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  57801. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  57802. if (distance > this._velocityWorldLength + max + sphereRadius) {
  57803. return false;
  57804. }
  57805. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  57806. return false;
  57807. }
  57808. return true;
  57809. };
  57810. /** @hidden */
  57811. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  57812. var t0;
  57813. var embeddedInPlane = false;
  57814. //defensive programming, actually not needed.
  57815. if (!trianglePlaneArray) {
  57816. trianglePlaneArray = [];
  57817. }
  57818. if (!trianglePlaneArray[faceIndex]) {
  57819. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  57820. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  57821. }
  57822. var trianglePlane = trianglePlaneArray[faceIndex];
  57823. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  57824. return;
  57825. }
  57826. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  57827. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  57828. if (normalDotVelocity == 0) {
  57829. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  57830. return;
  57831. }
  57832. embeddedInPlane = true;
  57833. t0 = 0;
  57834. }
  57835. else {
  57836. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57837. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57838. if (t0 > t1) {
  57839. var temp = t1;
  57840. t1 = t0;
  57841. t0 = temp;
  57842. }
  57843. if (t0 > 1.0 || t1 < 0.0) {
  57844. return;
  57845. }
  57846. if (t0 < 0) {
  57847. t0 = 0;
  57848. }
  57849. if (t0 > 1.0) {
  57850. t0 = 1.0;
  57851. }
  57852. }
  57853. this._collisionPoint.copyFromFloats(0, 0, 0);
  57854. var found = false;
  57855. var t = 1.0;
  57856. if (!embeddedInPlane) {
  57857. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  57858. this._velocity.scaleToRef(t0, this._tempVector);
  57859. this._planeIntersectionPoint.addInPlace(this._tempVector);
  57860. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  57861. found = true;
  57862. t = t0;
  57863. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  57864. }
  57865. }
  57866. if (!found) {
  57867. var velocitySquaredLength = this._velocity.lengthSquared();
  57868. var a = velocitySquaredLength;
  57869. this._basePoint.subtractToRef(p1, this._tempVector);
  57870. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57871. var c = this._tempVector.lengthSquared() - 1.0;
  57872. var lowestRoot = getLowestRoot(a, b, c, t);
  57873. if (lowestRoot.found) {
  57874. t = lowestRoot.root;
  57875. found = true;
  57876. this._collisionPoint.copyFrom(p1);
  57877. }
  57878. this._basePoint.subtractToRef(p2, this._tempVector);
  57879. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57880. c = this._tempVector.lengthSquared() - 1.0;
  57881. lowestRoot = getLowestRoot(a, b, c, t);
  57882. if (lowestRoot.found) {
  57883. t = lowestRoot.root;
  57884. found = true;
  57885. this._collisionPoint.copyFrom(p2);
  57886. }
  57887. this._basePoint.subtractToRef(p3, this._tempVector);
  57888. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57889. c = this._tempVector.lengthSquared() - 1.0;
  57890. lowestRoot = getLowestRoot(a, b, c, t);
  57891. if (lowestRoot.found) {
  57892. t = lowestRoot.root;
  57893. found = true;
  57894. this._collisionPoint.copyFrom(p3);
  57895. }
  57896. p2.subtractToRef(p1, this._edge);
  57897. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57898. var edgeSquaredLength = this._edge.lengthSquared();
  57899. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57900. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57901. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57902. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57903. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57904. lowestRoot = getLowestRoot(a, b, c, t);
  57905. if (lowestRoot.found) {
  57906. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57907. if (f >= 0.0 && f <= 1.0) {
  57908. t = lowestRoot.root;
  57909. found = true;
  57910. this._edge.scaleInPlace(f);
  57911. p1.addToRef(this._edge, this._collisionPoint);
  57912. }
  57913. }
  57914. p3.subtractToRef(p2, this._edge);
  57915. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57916. edgeSquaredLength = this._edge.lengthSquared();
  57917. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57918. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57919. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57920. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57921. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57922. lowestRoot = getLowestRoot(a, b, c, t);
  57923. if (lowestRoot.found) {
  57924. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57925. if (f >= 0.0 && f <= 1.0) {
  57926. t = lowestRoot.root;
  57927. found = true;
  57928. this._edge.scaleInPlace(f);
  57929. p2.addToRef(this._edge, this._collisionPoint);
  57930. }
  57931. }
  57932. p1.subtractToRef(p3, this._edge);
  57933. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57934. edgeSquaredLength = this._edge.lengthSquared();
  57935. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57936. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57937. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57938. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57939. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57940. lowestRoot = getLowestRoot(a, b, c, t);
  57941. if (lowestRoot.found) {
  57942. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57943. if (f >= 0.0 && f <= 1.0) {
  57944. t = lowestRoot.root;
  57945. found = true;
  57946. this._edge.scaleInPlace(f);
  57947. p3.addToRef(this._edge, this._collisionPoint);
  57948. }
  57949. }
  57950. }
  57951. if (found) {
  57952. var distToCollision = t * this._velocity.length();
  57953. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57954. if (!this.intersectionPoint) {
  57955. this.intersectionPoint = this._collisionPoint.clone();
  57956. }
  57957. else {
  57958. this.intersectionPoint.copyFrom(this._collisionPoint);
  57959. }
  57960. this._nearestDistance = distToCollision;
  57961. this.collisionFound = true;
  57962. }
  57963. }
  57964. };
  57965. /** @hidden */
  57966. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57967. for (var i = indexStart; i < indexEnd; i += 3) {
  57968. var p1 = pts[indices[i] - decal];
  57969. var p2 = pts[indices[i + 1] - decal];
  57970. var p3 = pts[indices[i + 2] - decal];
  57971. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  57972. }
  57973. };
  57974. /** @hidden */
  57975. Collider.prototype._getResponse = function (pos, vel) {
  57976. pos.addToRef(vel, this._destinationPoint);
  57977. vel.scaleInPlace((this._nearestDistance / vel.length()));
  57978. this._basePoint.addToRef(vel, pos);
  57979. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  57980. this._slidePlaneNormal.normalize();
  57981. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  57982. pos.addInPlace(this._displacementVector);
  57983. this.intersectionPoint.addInPlace(this._displacementVector);
  57984. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  57985. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  57986. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  57987. };
  57988. return Collider;
  57989. }());
  57990. BABYLON.Collider = Collider;
  57991. })(BABYLON || (BABYLON = {}));
  57992. //# sourceMappingURL=babylon.collider.js.map
  57993. var BABYLON;
  57994. (function (BABYLON) {
  57995. //WebWorker code will be inserted to this variable.
  57996. /** @hidden */
  57997. BABYLON.CollisionWorker = "";
  57998. /** Defines supported task for worker process */
  57999. var WorkerTaskType;
  58000. (function (WorkerTaskType) {
  58001. /** Initialization */
  58002. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  58003. /** Update of geometry */
  58004. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  58005. /** Evaluate collision */
  58006. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  58007. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  58008. /** Defines kind of replies returned by worker */
  58009. var WorkerReplyType;
  58010. (function (WorkerReplyType) {
  58011. /** Success */
  58012. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  58013. /** Unkown error */
  58014. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  58015. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  58016. /** @hidden */
  58017. var CollisionCoordinatorWorker = /** @class */ (function () {
  58018. function CollisionCoordinatorWorker() {
  58019. var _this = this;
  58020. this._scaledPosition = BABYLON.Vector3.Zero();
  58021. this._scaledVelocity = BABYLON.Vector3.Zero();
  58022. this.onMeshUpdated = function (transformNode) {
  58023. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  58024. };
  58025. this.onGeometryUpdated = function (geometry) {
  58026. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  58027. };
  58028. this._afterRender = function () {
  58029. if (!_this._init) {
  58030. return;
  58031. }
  58032. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  58033. return;
  58034. }
  58035. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  58036. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  58037. if (_this._runningUpdated > 4) {
  58038. return;
  58039. }
  58040. ++_this._runningUpdated;
  58041. var payload = {
  58042. updatedMeshes: _this._addUpdateMeshesList,
  58043. updatedGeometries: _this._addUpdateGeometriesList,
  58044. removedGeometries: _this._toRemoveGeometryArray,
  58045. removedMeshes: _this._toRemoveMeshesArray
  58046. };
  58047. var message = {
  58048. payload: payload,
  58049. taskType: WorkerTaskType.UPDATE
  58050. };
  58051. var serializable = [];
  58052. for (var id in payload.updatedGeometries) {
  58053. if (payload.updatedGeometries.hasOwnProperty(id)) {
  58054. //prepare transferables
  58055. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  58056. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  58057. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  58058. }
  58059. }
  58060. _this._worker.postMessage(message, serializable);
  58061. _this._addUpdateMeshesList = {};
  58062. _this._addUpdateGeometriesList = {};
  58063. _this._toRemoveGeometryArray = [];
  58064. _this._toRemoveMeshesArray = [];
  58065. };
  58066. this._onMessageFromWorker = function (e) {
  58067. var returnData = e.data;
  58068. if (returnData.error != WorkerReplyType.SUCCESS) {
  58069. //TODO what errors can be returned from the worker?
  58070. BABYLON.Tools.Warn("error returned from worker!");
  58071. return;
  58072. }
  58073. switch (returnData.taskType) {
  58074. case WorkerTaskType.INIT:
  58075. _this._init = true;
  58076. //Update the worked with ALL of the scene's current state
  58077. _this._scene.meshes.forEach(function (mesh) {
  58078. _this.onMeshAdded(mesh);
  58079. });
  58080. _this._scene.getGeometries().forEach(function (geometry) {
  58081. _this.onGeometryAdded(geometry);
  58082. });
  58083. break;
  58084. case WorkerTaskType.UPDATE:
  58085. _this._runningUpdated--;
  58086. break;
  58087. case WorkerTaskType.COLLIDE:
  58088. var returnPayload = returnData.payload;
  58089. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  58090. return;
  58091. }
  58092. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  58093. if (callback) {
  58094. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  58095. if (mesh) {
  58096. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  58097. }
  58098. }
  58099. //cleanup
  58100. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  58101. break;
  58102. }
  58103. };
  58104. this._collisionsCallbackArray = [];
  58105. this._init = false;
  58106. this._runningUpdated = 0;
  58107. this._addUpdateMeshesList = {};
  58108. this._addUpdateGeometriesList = {};
  58109. this._toRemoveGeometryArray = [];
  58110. this._toRemoveMeshesArray = [];
  58111. }
  58112. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  58113. if (!this._init) {
  58114. return;
  58115. }
  58116. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  58117. return;
  58118. }
  58119. position.divideToRef(collider._radius, this._scaledPosition);
  58120. displacement.divideToRef(collider._radius, this._scaledVelocity);
  58121. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  58122. var payload = {
  58123. collider: {
  58124. position: this._scaledPosition.asArray(),
  58125. velocity: this._scaledVelocity.asArray(),
  58126. radius: collider._radius.asArray()
  58127. },
  58128. collisionId: collisionIndex,
  58129. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  58130. maximumRetry: maximumRetry
  58131. };
  58132. var message = {
  58133. payload: payload,
  58134. taskType: WorkerTaskType.COLLIDE
  58135. };
  58136. this._worker.postMessage(message);
  58137. };
  58138. CollisionCoordinatorWorker.prototype.init = function (scene) {
  58139. this._scene = scene;
  58140. this._scene.registerAfterRender(this._afterRender);
  58141. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  58142. this._worker = new Worker(workerUrl);
  58143. this._worker.onmessage = this._onMessageFromWorker;
  58144. var message = {
  58145. payload: {},
  58146. taskType: WorkerTaskType.INIT
  58147. };
  58148. this._worker.postMessage(message);
  58149. };
  58150. CollisionCoordinatorWorker.prototype.destroy = function () {
  58151. this._scene.unregisterAfterRender(this._afterRender);
  58152. this._worker.terminate();
  58153. };
  58154. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  58155. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  58156. this.onMeshUpdated(mesh);
  58157. };
  58158. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  58159. this._toRemoveMeshesArray.push(mesh.uniqueId);
  58160. };
  58161. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  58162. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  58163. geometry.onGeometryUpdated = this.onGeometryUpdated;
  58164. this.onGeometryUpdated(geometry);
  58165. };
  58166. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  58167. this._toRemoveGeometryArray.push(geometry.id);
  58168. };
  58169. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  58170. var submeshes = [];
  58171. if (mesh.subMeshes) {
  58172. submeshes = mesh.subMeshes.map(function (sm, idx) {
  58173. var boundingInfo = sm.getBoundingInfo();
  58174. return {
  58175. position: idx,
  58176. verticesStart: sm.verticesStart,
  58177. verticesCount: sm.verticesCount,
  58178. indexStart: sm.indexStart,
  58179. indexCount: sm.indexCount,
  58180. hasMaterial: !!sm.getMaterial(),
  58181. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  58182. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  58183. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  58184. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  58185. };
  58186. });
  58187. }
  58188. var geometryId = null;
  58189. if (mesh instanceof BABYLON.Mesh) {
  58190. var geometry = mesh.geometry;
  58191. geometryId = geometry ? geometry.id : null;
  58192. }
  58193. else if (mesh instanceof BABYLON.InstancedMesh) {
  58194. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  58195. geometryId = geometry ? geometry.id : null;
  58196. }
  58197. var boundingInfo = mesh.getBoundingInfo();
  58198. return {
  58199. uniqueId: mesh.uniqueId,
  58200. id: mesh.id,
  58201. name: mesh.name,
  58202. geometryId: geometryId,
  58203. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  58204. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  58205. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  58206. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  58207. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  58208. subMeshes: submeshes,
  58209. checkCollisions: mesh.checkCollisions
  58210. };
  58211. };
  58212. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  58213. return {
  58214. id: geometry.id,
  58215. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  58216. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  58217. indices: new Uint32Array(geometry.getIndices() || []),
  58218. };
  58219. };
  58220. return CollisionCoordinatorWorker;
  58221. }());
  58222. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  58223. /** @hidden */
  58224. var CollisionCoordinatorLegacy = /** @class */ (function () {
  58225. function CollisionCoordinatorLegacy() {
  58226. this._scaledPosition = BABYLON.Vector3.Zero();
  58227. this._scaledVelocity = BABYLON.Vector3.Zero();
  58228. this._finalPosition = BABYLON.Vector3.Zero();
  58229. }
  58230. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  58231. position.divideToRef(collider._radius, this._scaledPosition);
  58232. displacement.divideToRef(collider._radius, this._scaledVelocity);
  58233. collider.collidedMesh = null;
  58234. collider._retry = 0;
  58235. collider._initialVelocity = this._scaledVelocity;
  58236. collider._initialPosition = this._scaledPosition;
  58237. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  58238. this._finalPosition.multiplyInPlace(collider._radius);
  58239. //run the callback
  58240. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  58241. };
  58242. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  58243. this._scene = scene;
  58244. };
  58245. CollisionCoordinatorLegacy.prototype.destroy = function () {
  58246. //Legacy need no destruction method.
  58247. };
  58248. //No update in legacy mode
  58249. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  58250. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  58251. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  58252. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  58253. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  58254. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  58255. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  58256. if (excludedMesh === void 0) { excludedMesh = null; }
  58257. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  58258. if (collider._retry >= maximumRetry) {
  58259. finalPosition.copyFrom(position);
  58260. return;
  58261. }
  58262. // Check if this is a mesh else camera or -1
  58263. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  58264. collider._initialize(position, velocity, closeDistance);
  58265. // Check all meshes
  58266. for (var index = 0; index < this._scene.meshes.length; index++) {
  58267. var mesh = this._scene.meshes[index];
  58268. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  58269. mesh._checkCollision(collider);
  58270. }
  58271. }
  58272. if (!collider.collisionFound) {
  58273. position.addToRef(velocity, finalPosition);
  58274. return;
  58275. }
  58276. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  58277. collider._getResponse(position, velocity);
  58278. }
  58279. if (velocity.length() <= closeDistance) {
  58280. finalPosition.copyFrom(position);
  58281. return;
  58282. }
  58283. collider._retry++;
  58284. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  58285. };
  58286. return CollisionCoordinatorLegacy;
  58287. }());
  58288. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  58289. })(BABYLON || (BABYLON = {}));
  58290. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  58291. var BABYLON;
  58292. (function (BABYLON) {
  58293. /**
  58294. * A particle represents one of the element emitted by a particle system.
  58295. * This is mainly define by its coordinates, direction, velocity and age.
  58296. */
  58297. var Particle = /** @class */ (function () {
  58298. /**
  58299. * Creates a new instance Particle
  58300. * @param particleSystem the particle system the particle belongs to
  58301. */
  58302. function Particle(
  58303. /**
  58304. * The particle system the particle belongs to.
  58305. */
  58306. particleSystem) {
  58307. this.particleSystem = particleSystem;
  58308. /**
  58309. * The world position of the particle in the scene.
  58310. */
  58311. this.position = BABYLON.Vector3.Zero();
  58312. /**
  58313. * The world direction of the particle in the scene.
  58314. */
  58315. this.direction = BABYLON.Vector3.Zero();
  58316. /**
  58317. * The color of the particle.
  58318. */
  58319. this.color = new BABYLON.Color4(0, 0, 0, 0);
  58320. /**
  58321. * The color change of the particle per step.
  58322. */
  58323. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  58324. /**
  58325. * Defines how long will the life of the particle be.
  58326. */
  58327. this.lifeTime = 1.0;
  58328. /**
  58329. * The current age of the particle.
  58330. */
  58331. this.age = 0;
  58332. /**
  58333. * The current size of the particle.
  58334. */
  58335. this.size = 0;
  58336. /**
  58337. * The current scale of the particle.
  58338. */
  58339. this.scale = new BABYLON.Vector2(1, 1);
  58340. /**
  58341. * The current angle of the particle.
  58342. */
  58343. this.angle = 0;
  58344. /**
  58345. * Defines how fast is the angle changing.
  58346. */
  58347. this.angularSpeed = 0;
  58348. /**
  58349. * Defines the cell index used by the particle to be rendered from a sprite.
  58350. */
  58351. this.cellIndex = 0;
  58352. /** @hidden */
  58353. this._attachedSubEmitters = null;
  58354. /** @hidden */
  58355. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  58356. /** @hidden */
  58357. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  58358. /** @hidden */
  58359. this._currentSize1 = 0;
  58360. /** @hidden */
  58361. this._currentSize2 = 0;
  58362. /** @hidden */
  58363. this._currentAngularSpeed1 = 0;
  58364. /** @hidden */
  58365. this._currentAngularSpeed2 = 0;
  58366. /** @hidden */
  58367. this._currentVelocity1 = 0;
  58368. /** @hidden */
  58369. this._currentVelocity2 = 0;
  58370. /** @hidden */
  58371. this._currentLimitVelocity1 = 0;
  58372. /** @hidden */
  58373. this._currentLimitVelocity2 = 0;
  58374. /** @hidden */
  58375. this._currentDrag1 = 0;
  58376. /** @hidden */
  58377. this._currentDrag2 = 0;
  58378. this.id = Particle._Count++;
  58379. if (!this.particleSystem.isAnimationSheetEnabled) {
  58380. return;
  58381. }
  58382. this.updateCellInfoFromSystem();
  58383. }
  58384. Particle.prototype.updateCellInfoFromSystem = function () {
  58385. this.cellIndex = this.particleSystem.startSpriteCellID;
  58386. };
  58387. /**
  58388. * Defines how the sprite cell index is updated for the particle
  58389. */
  58390. Particle.prototype.updateCellIndex = function () {
  58391. var offsetAge = this.age;
  58392. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  58393. if (this.particleSystem.spriteRandomStartCell) {
  58394. if (this._randomCellOffset === undefined) {
  58395. this._randomCellOffset = Math.random() * this.lifeTime;
  58396. }
  58397. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  58398. changeSpeed = 1;
  58399. offsetAge = this._randomCellOffset;
  58400. }
  58401. else {
  58402. offsetAge += this._randomCellOffset;
  58403. }
  58404. }
  58405. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  58406. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  58407. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  58408. };
  58409. /** @hidden */
  58410. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  58411. if (subEmitter.particleSystem.emitter.position) {
  58412. var emitterMesh = subEmitter.particleSystem.emitter;
  58413. emitterMesh.position.copyFrom(this.position);
  58414. if (subEmitter.inheritDirection) {
  58415. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  58416. // Look at using Y as forward
  58417. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  58418. }
  58419. }
  58420. else {
  58421. var emitterPosition = subEmitter.particleSystem.emitter;
  58422. emitterPosition.copyFrom(this.position);
  58423. }
  58424. // Set inheritedVelocityOffset to be used when new particles are created
  58425. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  58426. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  58427. };
  58428. /** @hidden */
  58429. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  58430. var _this = this;
  58431. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  58432. this._attachedSubEmitters.forEach(function (subEmitter) {
  58433. _this._inheritParticleInfoToSubEmitter(subEmitter);
  58434. });
  58435. }
  58436. };
  58437. /** @hidden */
  58438. Particle.prototype._reset = function () {
  58439. this.age = 0;
  58440. this._currentColorGradient = null;
  58441. this._currentSizeGradient = null;
  58442. this._currentAngularSpeedGradient = null;
  58443. this._currentVelocityGradient = null;
  58444. this._currentLimitVelocityGradient = null;
  58445. this._currentDragGradient = null;
  58446. this.cellIndex = this.particleSystem.startSpriteCellID;
  58447. this._randomCellOffset = undefined;
  58448. };
  58449. /**
  58450. * Copy the properties of particle to another one.
  58451. * @param other the particle to copy the information to.
  58452. */
  58453. Particle.prototype.copyTo = function (other) {
  58454. other.position.copyFrom(this.position);
  58455. if (this._initialDirection) {
  58456. if (other._initialDirection) {
  58457. other._initialDirection.copyFrom(this._initialDirection);
  58458. }
  58459. else {
  58460. other._initialDirection = this._initialDirection.clone();
  58461. }
  58462. }
  58463. else {
  58464. other._initialDirection = null;
  58465. }
  58466. other.direction.copyFrom(this.direction);
  58467. other.color.copyFrom(this.color);
  58468. other.colorStep.copyFrom(this.colorStep);
  58469. other.lifeTime = this.lifeTime;
  58470. other.age = this.age;
  58471. other._randomCellOffset = this._randomCellOffset;
  58472. other.size = this.size;
  58473. other.scale.copyFrom(this.scale);
  58474. other.angle = this.angle;
  58475. other.angularSpeed = this.angularSpeed;
  58476. other.particleSystem = this.particleSystem;
  58477. other.cellIndex = this.cellIndex;
  58478. other.id = this.id;
  58479. other._attachedSubEmitters = this._attachedSubEmitters;
  58480. if (this._currentColorGradient) {
  58481. other._currentColorGradient = this._currentColorGradient;
  58482. other._currentColor1.copyFrom(this._currentColor1);
  58483. other._currentColor2.copyFrom(this._currentColor2);
  58484. }
  58485. if (this._currentSizeGradient) {
  58486. other._currentSizeGradient = this._currentSizeGradient;
  58487. other._currentSize1 = this._currentSize1;
  58488. other._currentSize2 = this._currentSize2;
  58489. }
  58490. if (this._currentAngularSpeedGradient) {
  58491. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  58492. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  58493. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  58494. }
  58495. if (this._currentVelocityGradient) {
  58496. other._currentVelocityGradient = this._currentVelocityGradient;
  58497. other._currentVelocity1 = this._currentVelocity1;
  58498. other._currentVelocity2 = this._currentVelocity2;
  58499. }
  58500. if (this._currentLimitVelocityGradient) {
  58501. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  58502. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  58503. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  58504. }
  58505. if (this._currentDragGradient) {
  58506. other._currentDragGradient = this._currentDragGradient;
  58507. other._currentDrag1 = this._currentDrag1;
  58508. other._currentDrag2 = this._currentDrag2;
  58509. }
  58510. if (this.particleSystem.isAnimationSheetEnabled) {
  58511. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  58512. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  58513. }
  58514. if (this.particleSystem.useRampGradients) {
  58515. other.remapData.copyFrom(this.remapData);
  58516. }
  58517. if (this._randomNoiseCoordinates1) {
  58518. if (other._randomNoiseCoordinates1) {
  58519. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  58520. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  58521. }
  58522. else {
  58523. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  58524. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  58525. }
  58526. }
  58527. };
  58528. Particle._Count = 0;
  58529. return Particle;
  58530. }());
  58531. BABYLON.Particle = Particle;
  58532. })(BABYLON || (BABYLON = {}));
  58533. //# sourceMappingURL=babylon.particle.js.map
  58534. var BABYLON;
  58535. (function (BABYLON) {
  58536. /**
  58537. * This represents the base class for particle system in Babylon.
  58538. * 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.
  58539. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58540. * @example https://doc.babylonjs.com/babylon101/particles
  58541. */
  58542. var BaseParticleSystem = /** @class */ (function () {
  58543. /**
  58544. * Instantiates a particle system.
  58545. * 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.
  58546. * @param name The name of the particle system
  58547. */
  58548. function BaseParticleSystem(name) {
  58549. /**
  58550. * List of animations used by the particle system.
  58551. */
  58552. this.animations = [];
  58553. /**
  58554. * The rendering group used by the Particle system to chose when to render.
  58555. */
  58556. this.renderingGroupId = 0;
  58557. /**
  58558. * The emitter represents the Mesh or position we are attaching the particle system to.
  58559. */
  58560. this.emitter = null;
  58561. /**
  58562. * The maximum number of particles to emit per frame
  58563. */
  58564. this.emitRate = 10;
  58565. /**
  58566. * If you want to launch only a few particles at once, that can be done, as well.
  58567. */
  58568. this.manualEmitCount = -1;
  58569. /**
  58570. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  58571. */
  58572. this.updateSpeed = 0.01;
  58573. /**
  58574. * The amount of time the particle system is running (depends of the overall update speed).
  58575. */
  58576. this.targetStopDuration = 0;
  58577. /**
  58578. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  58579. */
  58580. this.disposeOnStop = false;
  58581. /**
  58582. * Minimum power of emitting particles.
  58583. */
  58584. this.minEmitPower = 1;
  58585. /**
  58586. * Maximum power of emitting particles.
  58587. */
  58588. this.maxEmitPower = 1;
  58589. /**
  58590. * Minimum life time of emitting particles.
  58591. */
  58592. this.minLifeTime = 1;
  58593. /**
  58594. * Maximum life time of emitting particles.
  58595. */
  58596. this.maxLifeTime = 1;
  58597. /**
  58598. * Minimum Size of emitting particles.
  58599. */
  58600. this.minSize = 1;
  58601. /**
  58602. * Maximum Size of emitting particles.
  58603. */
  58604. this.maxSize = 1;
  58605. /**
  58606. * Minimum scale of emitting particles on X axis.
  58607. */
  58608. this.minScaleX = 1;
  58609. /**
  58610. * Maximum scale of emitting particles on X axis.
  58611. */
  58612. this.maxScaleX = 1;
  58613. /**
  58614. * Minimum scale of emitting particles on Y axis.
  58615. */
  58616. this.minScaleY = 1;
  58617. /**
  58618. * Maximum scale of emitting particles on Y axis.
  58619. */
  58620. this.maxScaleY = 1;
  58621. /**
  58622. * Gets or sets the minimal initial rotation in radians.
  58623. */
  58624. this.minInitialRotation = 0;
  58625. /**
  58626. * Gets or sets the maximal initial rotation in radians.
  58627. */
  58628. this.maxInitialRotation = 0;
  58629. /**
  58630. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  58631. */
  58632. this.minAngularSpeed = 0;
  58633. /**
  58634. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  58635. */
  58636. this.maxAngularSpeed = 0;
  58637. /**
  58638. * The layer mask we are rendering the particles through.
  58639. */
  58640. this.layerMask = 0x0FFFFFFF;
  58641. /**
  58642. * This can help using your own shader to render the particle system.
  58643. * The according effect will be created
  58644. */
  58645. this.customShader = null;
  58646. /**
  58647. * By default particle system starts as soon as they are created. This prevents the
  58648. * automatic start to happen and let you decide when to start emitting particles.
  58649. */
  58650. this.preventAutoStart = false;
  58651. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  58652. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  58653. /**
  58654. * Callback triggered when the particle animation is ending.
  58655. */
  58656. this.onAnimationEnd = null;
  58657. /**
  58658. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  58659. */
  58660. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  58661. /**
  58662. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  58663. * to override the particles.
  58664. */
  58665. this.forceDepthWrite = false;
  58666. /** 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 */
  58667. this.preWarmCycles = 0;
  58668. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  58669. this.preWarmStepOffset = 1;
  58670. /**
  58671. * 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)
  58672. */
  58673. this.spriteCellChangeSpeed = 1;
  58674. /**
  58675. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  58676. */
  58677. this.startSpriteCellID = 0;
  58678. /**
  58679. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  58680. */
  58681. this.endSpriteCellID = 0;
  58682. /**
  58683. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  58684. */
  58685. this.spriteCellWidth = 0;
  58686. /**
  58687. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  58688. */
  58689. this.spriteCellHeight = 0;
  58690. /**
  58691. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  58692. */
  58693. this.spriteRandomStartCell = false;
  58694. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  58695. this.translationPivot = new BABYLON.Vector2(0, 0);
  58696. /**
  58697. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  58698. */
  58699. this.beginAnimationOnStart = false;
  58700. /**
  58701. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  58702. */
  58703. this.beginAnimationFrom = 0;
  58704. /**
  58705. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  58706. */
  58707. this.beginAnimationTo = 60;
  58708. /**
  58709. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  58710. */
  58711. this.beginAnimationLoop = false;
  58712. /**
  58713. * You can use gravity if you want to give an orientation to your particles.
  58714. */
  58715. this.gravity = BABYLON.Vector3.Zero();
  58716. this._colorGradients = null;
  58717. this._sizeGradients = null;
  58718. this._lifeTimeGradients = null;
  58719. this._angularSpeedGradients = null;
  58720. this._velocityGradients = null;
  58721. this._limitVelocityGradients = null;
  58722. this._dragGradients = null;
  58723. this._emitRateGradients = null;
  58724. this._startSizeGradients = null;
  58725. this._rampGradients = null;
  58726. this._colorRemapGradients = null;
  58727. this._alphaRemapGradients = null;
  58728. /**
  58729. * Defines the delay in milliseconds before starting the system (0 by default)
  58730. */
  58731. this.startDelay = 0;
  58732. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  58733. this.limitVelocityDamping = 0.4;
  58734. /**
  58735. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58736. */
  58737. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58738. /**
  58739. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58740. */
  58741. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58742. /**
  58743. * Color the particle will have at the end of its lifetime
  58744. */
  58745. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  58746. /**
  58747. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  58748. */
  58749. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58750. /** @hidden */
  58751. this._isSubEmitter = false;
  58752. /**
  58753. * Gets or sets the billboard mode to use when isBillboardBased = true.
  58754. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  58755. */
  58756. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  58757. this._isBillboardBased = true;
  58758. /**
  58759. * Local cache of defines for image processing.
  58760. */
  58761. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  58762. this.id = name;
  58763. this.name = name;
  58764. }
  58765. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  58766. /**
  58767. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  58768. */
  58769. get: function () {
  58770. return this._isAnimationSheetEnabled;
  58771. },
  58772. set: function (value) {
  58773. if (this._isAnimationSheetEnabled == value) {
  58774. return;
  58775. }
  58776. this._isAnimationSheetEnabled = value;
  58777. this._reset();
  58778. },
  58779. enumerable: true,
  58780. configurable: true
  58781. });
  58782. /**
  58783. * Get hosting scene
  58784. * @returns the scene
  58785. */
  58786. BaseParticleSystem.prototype.getScene = function () {
  58787. return this._scene;
  58788. };
  58789. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  58790. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  58791. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  58792. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  58793. };
  58794. /**
  58795. * Gets the current list of drag gradients.
  58796. * You must use addDragGradient and removeDragGradient to udpate this list
  58797. * @returns the list of drag gradients
  58798. */
  58799. BaseParticleSystem.prototype.getDragGradients = function () {
  58800. return this._dragGradients;
  58801. };
  58802. /**
  58803. * Gets the current list of limit velocity gradients.
  58804. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  58805. * @returns the list of limit velocity gradients
  58806. */
  58807. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  58808. return this._limitVelocityGradients;
  58809. };
  58810. /**
  58811. * Gets the current list of color gradients.
  58812. * You must use addColorGradient and removeColorGradient to udpate this list
  58813. * @returns the list of color gradients
  58814. */
  58815. BaseParticleSystem.prototype.getColorGradients = function () {
  58816. return this._colorGradients;
  58817. };
  58818. /**
  58819. * Gets the current list of size gradients.
  58820. * You must use addSizeGradient and removeSizeGradient to udpate this list
  58821. * @returns the list of size gradients
  58822. */
  58823. BaseParticleSystem.prototype.getSizeGradients = function () {
  58824. return this._sizeGradients;
  58825. };
  58826. /**
  58827. * Gets the current list of color remap gradients.
  58828. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  58829. * @returns the list of color remap gradients
  58830. */
  58831. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  58832. return this._colorRemapGradients;
  58833. };
  58834. /**
  58835. * Gets the current list of alpha remap gradients.
  58836. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  58837. * @returns the list of alpha remap gradients
  58838. */
  58839. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  58840. return this._alphaRemapGradients;
  58841. };
  58842. /**
  58843. * Gets the current list of life time gradients.
  58844. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  58845. * @returns the list of life time gradients
  58846. */
  58847. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  58848. return this._lifeTimeGradients;
  58849. };
  58850. /**
  58851. * Gets the current list of angular speed gradients.
  58852. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  58853. * @returns the list of angular speed gradients
  58854. */
  58855. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  58856. return this._angularSpeedGradients;
  58857. };
  58858. /**
  58859. * Gets the current list of velocity gradients.
  58860. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  58861. * @returns the list of velocity gradients
  58862. */
  58863. BaseParticleSystem.prototype.getVelocityGradients = function () {
  58864. return this._velocityGradients;
  58865. };
  58866. /**
  58867. * Gets the current list of start size gradients.
  58868. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  58869. * @returns the list of start size gradients
  58870. */
  58871. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  58872. return this._startSizeGradients;
  58873. };
  58874. /**
  58875. * Gets the current list of emit rate gradients.
  58876. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  58877. * @returns the list of emit rate gradients
  58878. */
  58879. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  58880. return this._emitRateGradients;
  58881. };
  58882. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  58883. /**
  58884. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58885. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58886. */
  58887. get: function () {
  58888. if (this.particleEmitterType.direction1) {
  58889. return this.particleEmitterType.direction1;
  58890. }
  58891. return BABYLON.Vector3.Zero();
  58892. },
  58893. set: function (value) {
  58894. if (this.particleEmitterType.direction1) {
  58895. this.particleEmitterType.direction1 = value;
  58896. }
  58897. },
  58898. enumerable: true,
  58899. configurable: true
  58900. });
  58901. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58902. /**
  58903. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58904. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58905. */
  58906. get: function () {
  58907. if (this.particleEmitterType.direction2) {
  58908. return this.particleEmitterType.direction2;
  58909. }
  58910. return BABYLON.Vector3.Zero();
  58911. },
  58912. set: function (value) {
  58913. if (this.particleEmitterType.direction2) {
  58914. this.particleEmitterType.direction2 = value;
  58915. }
  58916. },
  58917. enumerable: true,
  58918. configurable: true
  58919. });
  58920. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58921. /**
  58922. * 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.
  58923. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58924. */
  58925. get: function () {
  58926. if (this.particleEmitterType.minEmitBox) {
  58927. return this.particleEmitterType.minEmitBox;
  58928. }
  58929. return BABYLON.Vector3.Zero();
  58930. },
  58931. set: function (value) {
  58932. if (this.particleEmitterType.minEmitBox) {
  58933. this.particleEmitterType.minEmitBox = value;
  58934. }
  58935. },
  58936. enumerable: true,
  58937. configurable: true
  58938. });
  58939. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58940. /**
  58941. * 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.
  58942. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58943. */
  58944. get: function () {
  58945. if (this.particleEmitterType.maxEmitBox) {
  58946. return this.particleEmitterType.maxEmitBox;
  58947. }
  58948. return BABYLON.Vector3.Zero();
  58949. },
  58950. set: function (value) {
  58951. if (this.particleEmitterType.maxEmitBox) {
  58952. this.particleEmitterType.maxEmitBox = value;
  58953. }
  58954. },
  58955. enumerable: true,
  58956. configurable: true
  58957. });
  58958. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58959. /**
  58960. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58961. */
  58962. get: function () {
  58963. return this._isBillboardBased;
  58964. },
  58965. set: function (value) {
  58966. if (this._isBillboardBased === value) {
  58967. return;
  58968. }
  58969. this._isBillboardBased = value;
  58970. this._reset();
  58971. },
  58972. enumerable: true,
  58973. configurable: true
  58974. });
  58975. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  58976. /**
  58977. * Gets the image processing configuration used either in this material.
  58978. */
  58979. get: function () {
  58980. return this._imageProcessingConfiguration;
  58981. },
  58982. /**
  58983. * Sets the Default image processing configuration used either in the this material.
  58984. *
  58985. * If sets to null, the scene one is in use.
  58986. */
  58987. set: function (value) {
  58988. this._attachImageProcessingConfiguration(value);
  58989. },
  58990. enumerable: true,
  58991. configurable: true
  58992. });
  58993. /**
  58994. * Attaches a new image processing configuration to the Standard Material.
  58995. * @param configuration
  58996. */
  58997. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  58998. if (configuration === this._imageProcessingConfiguration) {
  58999. return;
  59000. }
  59001. // Pick the scene configuration if needed.
  59002. if (!configuration) {
  59003. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  59004. }
  59005. else {
  59006. this._imageProcessingConfiguration = configuration;
  59007. }
  59008. };
  59009. /** @hidden */
  59010. BaseParticleSystem.prototype._reset = function () {
  59011. };
  59012. /** @hidden */
  59013. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  59014. if (!gradients) {
  59015. return this;
  59016. }
  59017. var index = 0;
  59018. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59019. var valueGradient = gradients_1[_i];
  59020. if (valueGradient.gradient === gradient) {
  59021. gradients.splice(index, 1);
  59022. break;
  59023. }
  59024. index++;
  59025. }
  59026. if (texture) {
  59027. texture.dispose();
  59028. }
  59029. return this;
  59030. };
  59031. /**
  59032. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  59033. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  59034. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  59035. * @returns the emitter
  59036. */
  59037. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  59038. var particleEmitter = new BABYLON.PointParticleEmitter();
  59039. particleEmitter.direction1 = direction1;
  59040. particleEmitter.direction2 = direction2;
  59041. this.particleEmitterType = particleEmitter;
  59042. return particleEmitter;
  59043. };
  59044. /**
  59045. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  59046. * @param radius The radius of the hemisphere to emit from
  59047. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  59048. * @returns the emitter
  59049. */
  59050. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  59051. if (radius === void 0) { radius = 1; }
  59052. if (radiusRange === void 0) { radiusRange = 1; }
  59053. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  59054. this.particleEmitterType = particleEmitter;
  59055. return particleEmitter;
  59056. };
  59057. /**
  59058. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  59059. * @param radius The radius of the sphere to emit from
  59060. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  59061. * @returns the emitter
  59062. */
  59063. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  59064. if (radius === void 0) { radius = 1; }
  59065. if (radiusRange === void 0) { radiusRange = 1; }
  59066. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  59067. this.particleEmitterType = particleEmitter;
  59068. return particleEmitter;
  59069. };
  59070. /**
  59071. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  59072. * @param radius The radius of the sphere to emit from
  59073. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  59074. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  59075. * @returns the emitter
  59076. */
  59077. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  59078. if (radius === void 0) { radius = 1; }
  59079. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  59080. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  59081. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  59082. this.particleEmitterType = particleEmitter;
  59083. return particleEmitter;
  59084. };
  59085. /**
  59086. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  59087. * @param radius The radius of the emission cylinder
  59088. * @param height The height of the emission cylinder
  59089. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  59090. * @param directionRandomizer How much to randomize the particle direction [0-1]
  59091. * @returns the emitter
  59092. */
  59093. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  59094. if (radius === void 0) { radius = 1; }
  59095. if (height === void 0) { height = 1; }
  59096. if (radiusRange === void 0) { radiusRange = 1; }
  59097. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59098. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  59099. this.particleEmitterType = particleEmitter;
  59100. return particleEmitter;
  59101. };
  59102. /**
  59103. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  59104. * @param radius The radius of the cylinder to emit from
  59105. * @param height The height of the emission cylinder
  59106. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59107. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  59108. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  59109. * @returns the emitter
  59110. */
  59111. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  59112. if (radius === void 0) { radius = 1; }
  59113. if (height === void 0) { height = 1; }
  59114. if (radiusRange === void 0) { radiusRange = 1; }
  59115. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  59116. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  59117. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  59118. this.particleEmitterType = particleEmitter;
  59119. return particleEmitter;
  59120. };
  59121. /**
  59122. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  59123. * @param radius The radius of the cone to emit from
  59124. * @param angle The base angle of the cone
  59125. * @returns the emitter
  59126. */
  59127. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  59128. if (radius === void 0) { radius = 1; }
  59129. if (angle === void 0) { angle = Math.PI / 4; }
  59130. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  59131. this.particleEmitterType = particleEmitter;
  59132. return particleEmitter;
  59133. };
  59134. /**
  59135. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  59136. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  59137. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  59138. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  59139. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  59140. * @returns the emitter
  59141. */
  59142. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  59143. var particleEmitter = new BABYLON.BoxParticleEmitter();
  59144. this.particleEmitterType = particleEmitter;
  59145. this.direction1 = direction1;
  59146. this.direction2 = direction2;
  59147. this.minEmitBox = minEmitBox;
  59148. this.maxEmitBox = maxEmitBox;
  59149. return particleEmitter;
  59150. };
  59151. /**
  59152. * Source color is added to the destination color without alpha affecting the result
  59153. */
  59154. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  59155. /**
  59156. * Blend current color and particle color using particle’s alpha
  59157. */
  59158. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  59159. /**
  59160. * Add current color and particle color multiplied by particle’s alpha
  59161. */
  59162. BaseParticleSystem.BLENDMODE_ADD = 2;
  59163. /**
  59164. * Multiply current color with particle color
  59165. */
  59166. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  59167. /**
  59168. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  59169. */
  59170. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  59171. return BaseParticleSystem;
  59172. }());
  59173. BABYLON.BaseParticleSystem = BaseParticleSystem;
  59174. })(BABYLON || (BABYLON = {}));
  59175. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  59176. var BABYLON;
  59177. (function (BABYLON) {
  59178. /**
  59179. * This represents a particle system in Babylon.
  59180. * 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.
  59181. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  59182. * @example https://doc.babylonjs.com/babylon101/particles
  59183. */
  59184. var ParticleSystem = /** @class */ (function (_super) {
  59185. __extends(ParticleSystem, _super);
  59186. /**
  59187. * Instantiates a particle system.
  59188. * 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.
  59189. * @param name The name of the particle system
  59190. * @param capacity The max number of particles alive at the same time
  59191. * @param scene The scene the particle system belongs to
  59192. * @param customEffect a custom effect used to change the way particles are rendered by default
  59193. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59194. * @param epsilon Offset used to render the particles
  59195. */
  59196. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  59197. if (customEffect === void 0) { customEffect = null; }
  59198. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59199. if (epsilon === void 0) { epsilon = 0.01; }
  59200. var _this = _super.call(this, name) || this;
  59201. /**
  59202. * @hidden
  59203. */
  59204. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  59205. /**
  59206. * An event triggered when the system is disposed
  59207. */
  59208. _this.onDisposeObservable = new BABYLON.Observable();
  59209. _this._particles = new Array();
  59210. _this._stockParticles = new Array();
  59211. _this._newPartsExcess = 0;
  59212. _this._vertexBuffers = {};
  59213. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  59214. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  59215. _this._scaledDirection = BABYLON.Vector3.Zero();
  59216. _this._scaledGravity = BABYLON.Vector3.Zero();
  59217. _this._currentRenderId = -1;
  59218. _this._useInstancing = false;
  59219. _this._started = false;
  59220. _this._stopped = false;
  59221. _this._actualFrame = 0;
  59222. /** @hidden */
  59223. _this._currentEmitRate1 = 0;
  59224. /** @hidden */
  59225. _this._currentEmitRate2 = 0;
  59226. /** @hidden */
  59227. _this._currentStartSize1 = 0;
  59228. /** @hidden */
  59229. _this._currentStartSize2 = 0;
  59230. _this._rawTextureWidth = 256;
  59231. _this._useRampGradients = false;
  59232. /**
  59233. * @hidden
  59234. * If the particle systems emitter should be disposed when the particle system is disposed
  59235. */
  59236. _this._disposeEmitterOnDispose = false;
  59237. // start of sub system methods
  59238. /**
  59239. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  59240. * Its lifetime will start back at 0.
  59241. */
  59242. _this.recycleParticle = function (particle) {
  59243. // move particle from activeParticle list to stock particles
  59244. var lastParticle = _this._particles.pop();
  59245. if (lastParticle !== particle) {
  59246. lastParticle.copyTo(particle);
  59247. }
  59248. _this._stockParticles.push(lastParticle);
  59249. };
  59250. _this._createParticle = function () {
  59251. var particle;
  59252. if (_this._stockParticles.length !== 0) {
  59253. particle = _this._stockParticles.pop();
  59254. particle._reset();
  59255. }
  59256. else {
  59257. particle = new BABYLON.Particle(_this);
  59258. }
  59259. // Attach emitters
  59260. if (_this._subEmitters && _this._subEmitters.length > 0) {
  59261. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  59262. particle._attachedSubEmitters = [];
  59263. subEmitters.forEach(function (subEmitter) {
  59264. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  59265. var newEmitter = subEmitter.clone();
  59266. particle._attachedSubEmitters.push(newEmitter);
  59267. newEmitter.particleSystem.start();
  59268. }
  59269. });
  59270. }
  59271. return particle;
  59272. };
  59273. _this._emitFromParticle = function (particle) {
  59274. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  59275. return;
  59276. }
  59277. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  59278. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  59279. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  59280. var subSystem = subEmitter.clone();
  59281. particle._inheritParticleInfoToSubEmitter(subSystem);
  59282. subSystem.particleSystem._rootParticleSystem = _this;
  59283. _this.activeSubSystems.push(subSystem.particleSystem);
  59284. subSystem.particleSystem.start();
  59285. }
  59286. });
  59287. };
  59288. _this._capacity = capacity;
  59289. _this._epsilon = epsilon;
  59290. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59291. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59292. // Setup the default processing configuration to the scene.
  59293. _this._attachImageProcessingConfiguration(null);
  59294. _this._customEffect = customEffect;
  59295. _this._scene.particleSystems.push(_this);
  59296. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  59297. _this._createIndexBuffer();
  59298. _this._createVertexBuffers();
  59299. // Default emitter type
  59300. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59301. // Update
  59302. _this.updateFunction = function (particles) {
  59303. var noiseTextureSize = null;
  59304. var noiseTextureData = null;
  59305. if (_this.noiseTexture) { // We need to get texture data back to CPU
  59306. noiseTextureSize = _this.noiseTexture.getSize();
  59307. noiseTextureData = (_this.noiseTexture.getContent());
  59308. }
  59309. var _loop_1 = function () {
  59310. particle = particles[index];
  59311. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  59312. var previousAge = particle.age;
  59313. particle.age += scaledUpdateSpeed;
  59314. // Evaluate step to death
  59315. if (particle.age > particle.lifeTime) {
  59316. var diff = particle.age - previousAge;
  59317. var oldDiff = particle.lifeTime - previousAge;
  59318. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  59319. particle.age = particle.lifeTime;
  59320. }
  59321. var ratio = particle.age / particle.lifeTime;
  59322. // Color
  59323. if (_this._colorGradients && _this._colorGradients.length > 0) {
  59324. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  59325. if (currentGradient !== particle._currentColorGradient) {
  59326. particle._currentColor1.copyFrom(particle._currentColor2);
  59327. nextGradient.getColorToRef(particle._currentColor2);
  59328. particle._currentColorGradient = currentGradient;
  59329. }
  59330. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  59331. });
  59332. }
  59333. else {
  59334. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  59335. particle.color.addInPlace(_this._scaledColorStep);
  59336. if (particle.color.a < 0) {
  59337. particle.color.a = 0;
  59338. }
  59339. }
  59340. // Angular speed
  59341. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  59342. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  59343. if (currentGradient !== particle._currentAngularSpeedGradient) {
  59344. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  59345. particle._currentAngularSpeed2 = nextGradient.getFactor();
  59346. particle._currentAngularSpeedGradient = currentGradient;
  59347. }
  59348. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  59349. });
  59350. }
  59351. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  59352. // Direction
  59353. var directionScale = scaledUpdateSpeed;
  59354. /// Velocity
  59355. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  59356. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  59357. if (currentGradient !== particle._currentVelocityGradient) {
  59358. particle._currentVelocity1 = particle._currentVelocity2;
  59359. particle._currentVelocity2 = nextGradient.getFactor();
  59360. particle._currentVelocityGradient = currentGradient;
  59361. }
  59362. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  59363. });
  59364. }
  59365. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  59366. /// Limit velocity
  59367. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  59368. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  59369. if (currentGradient !== particle._currentLimitVelocityGradient) {
  59370. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  59371. particle._currentLimitVelocity2 = nextGradient.getFactor();
  59372. particle._currentLimitVelocityGradient = currentGradient;
  59373. }
  59374. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  59375. var currentVelocity = particle.direction.length();
  59376. if (currentVelocity > limitVelocity) {
  59377. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  59378. }
  59379. });
  59380. }
  59381. /// Drag
  59382. if (_this._dragGradients && _this._dragGradients.length > 0) {
  59383. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  59384. if (currentGradient !== particle._currentDragGradient) {
  59385. particle._currentDrag1 = particle._currentDrag2;
  59386. particle._currentDrag2 = nextGradient.getFactor();
  59387. particle._currentDragGradient = currentGradient;
  59388. }
  59389. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  59390. _this._scaledDirection.scaleInPlace(1.0 - drag);
  59391. });
  59392. }
  59393. particle.position.addInPlace(_this._scaledDirection);
  59394. // Noise
  59395. if (noiseTextureData && noiseTextureSize) {
  59396. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59397. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59398. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59399. var force = BABYLON.Tmp.Vector3[0];
  59400. var scaledForce = BABYLON.Tmp.Vector3[1];
  59401. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  59402. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  59403. particle.direction.addInPlace(scaledForce);
  59404. }
  59405. // Gravity
  59406. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  59407. particle.direction.addInPlace(_this._scaledGravity);
  59408. // Size
  59409. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  59410. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  59411. if (currentGradient !== particle._currentSizeGradient) {
  59412. particle._currentSize1 = particle._currentSize2;
  59413. particle._currentSize2 = nextGradient.getFactor();
  59414. particle._currentSizeGradient = currentGradient;
  59415. }
  59416. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  59417. });
  59418. }
  59419. // Remap data
  59420. if (_this._useRampGradients) {
  59421. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  59422. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  59423. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59424. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59425. particle.remapData.x = min;
  59426. particle.remapData.y = max - min;
  59427. });
  59428. }
  59429. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  59430. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  59431. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59432. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59433. particle.remapData.z = min;
  59434. particle.remapData.w = max - min;
  59435. });
  59436. }
  59437. }
  59438. if (_this._isAnimationSheetEnabled) {
  59439. particle.updateCellIndex();
  59440. }
  59441. // Update the position of the attached sub-emitters to match their attached particle
  59442. particle._inheritParticleInfoToSubEmitters();
  59443. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  59444. _this._emitFromParticle(particle);
  59445. if (particle._attachedSubEmitters) {
  59446. particle._attachedSubEmitters.forEach(function (subEmitter) {
  59447. subEmitter.particleSystem.disposeOnStop = true;
  59448. subEmitter.particleSystem.stop();
  59449. });
  59450. particle._attachedSubEmitters = null;
  59451. }
  59452. _this.recycleParticle(particle);
  59453. index--;
  59454. return "continue";
  59455. }
  59456. };
  59457. var particle;
  59458. for (var index = 0; index < particles.length; index++) {
  59459. _loop_1();
  59460. }
  59461. };
  59462. return _this;
  59463. }
  59464. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  59465. /**
  59466. * Sets a callback that will be triggered when the system is disposed
  59467. */
  59468. set: function (callback) {
  59469. if (this._onDisposeObserver) {
  59470. this.onDisposeObservable.remove(this._onDisposeObserver);
  59471. }
  59472. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  59473. },
  59474. enumerable: true,
  59475. configurable: true
  59476. });
  59477. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  59478. /** Gets or sets a boolean indicating that ramp gradients must be used
  59479. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  59480. */
  59481. get: function () {
  59482. return this._useRampGradients;
  59483. },
  59484. set: function (value) {
  59485. if (this._useRampGradients === value) {
  59486. return;
  59487. }
  59488. this._useRampGradients = value;
  59489. this._resetEffect();
  59490. },
  59491. enumerable: true,
  59492. configurable: true
  59493. });
  59494. Object.defineProperty(ParticleSystem.prototype, "particles", {
  59495. //end of Sub-emitter
  59496. /**
  59497. * Gets the current list of active particles
  59498. */
  59499. get: function () {
  59500. return this._particles;
  59501. },
  59502. enumerable: true,
  59503. configurable: true
  59504. });
  59505. /**
  59506. * Returns the string "ParticleSystem"
  59507. * @returns a string containing the class name
  59508. */
  59509. ParticleSystem.prototype.getClassName = function () {
  59510. return "ParticleSystem";
  59511. };
  59512. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  59513. var newGradient = new BABYLON.FactorGradient();
  59514. newGradient.gradient = gradient;
  59515. newGradient.factor1 = factor;
  59516. newGradient.factor2 = factor2;
  59517. factorGradients.push(newGradient);
  59518. factorGradients.sort(function (a, b) {
  59519. if (a.gradient < b.gradient) {
  59520. return -1;
  59521. }
  59522. else if (a.gradient > b.gradient) {
  59523. return 1;
  59524. }
  59525. return 0;
  59526. });
  59527. };
  59528. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  59529. if (!factorGradients) {
  59530. return;
  59531. }
  59532. var index = 0;
  59533. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  59534. var factorGradient = factorGradients_1[_i];
  59535. if (factorGradient.gradient === gradient) {
  59536. factorGradients.splice(index, 1);
  59537. break;
  59538. }
  59539. index++;
  59540. }
  59541. };
  59542. /**
  59543. * Adds a new life time gradient
  59544. * @param gradient defines the gradient to use (between 0 and 1)
  59545. * @param factor defines the life time factor to affect to the specified gradient
  59546. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59547. * @returns the current particle system
  59548. */
  59549. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  59550. if (!this._lifeTimeGradients) {
  59551. this._lifeTimeGradients = [];
  59552. }
  59553. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  59554. return this;
  59555. };
  59556. /**
  59557. * Remove a specific life time gradient
  59558. * @param gradient defines the gradient to remove
  59559. * @returns the current particle system
  59560. */
  59561. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  59562. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  59563. return this;
  59564. };
  59565. /**
  59566. * Adds a new size gradient
  59567. * @param gradient defines the gradient to use (between 0 and 1)
  59568. * @param factor defines the size factor to affect to the specified gradient
  59569. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59570. * @returns the current particle system
  59571. */
  59572. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  59573. if (!this._sizeGradients) {
  59574. this._sizeGradients = [];
  59575. }
  59576. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  59577. return this;
  59578. };
  59579. /**
  59580. * Remove a specific size gradient
  59581. * @param gradient defines the gradient to remove
  59582. * @returns the current particle system
  59583. */
  59584. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59585. this._removeFactorGradient(this._sizeGradients, gradient);
  59586. return this;
  59587. };
  59588. /**
  59589. * Adds a new color remap gradient
  59590. * @param gradient defines the gradient to use (between 0 and 1)
  59591. * @param min defines the color remap minimal range
  59592. * @param max defines the color remap maximal range
  59593. * @returns the current particle system
  59594. */
  59595. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  59596. if (!this._colorRemapGradients) {
  59597. this._colorRemapGradients = [];
  59598. }
  59599. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  59600. return this;
  59601. };
  59602. /**
  59603. * Remove a specific color remap gradient
  59604. * @param gradient defines the gradient to remove
  59605. * @returns the current particle system
  59606. */
  59607. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  59608. this._removeFactorGradient(this._colorRemapGradients, gradient);
  59609. return this;
  59610. };
  59611. /**
  59612. * Adds a new alpha remap gradient
  59613. * @param gradient defines the gradient to use (between 0 and 1)
  59614. * @param min defines the alpha remap minimal range
  59615. * @param max defines the alpha remap maximal range
  59616. * @returns the current particle system
  59617. */
  59618. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  59619. if (!this._alphaRemapGradients) {
  59620. this._alphaRemapGradients = [];
  59621. }
  59622. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  59623. return this;
  59624. };
  59625. /**
  59626. * Remove a specific alpha remap gradient
  59627. * @param gradient defines the gradient to remove
  59628. * @returns the current particle system
  59629. */
  59630. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  59631. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  59632. return this;
  59633. };
  59634. /**
  59635. * Adds a new angular speed gradient
  59636. * @param gradient defines the gradient to use (between 0 and 1)
  59637. * @param factor defines the angular speed to affect to the specified gradient
  59638. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59639. * @returns the current particle system
  59640. */
  59641. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  59642. if (!this._angularSpeedGradients) {
  59643. this._angularSpeedGradients = [];
  59644. }
  59645. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  59646. return this;
  59647. };
  59648. /**
  59649. * Remove a specific angular speed gradient
  59650. * @param gradient defines the gradient to remove
  59651. * @returns the current particle system
  59652. */
  59653. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59654. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  59655. return this;
  59656. };
  59657. /**
  59658. * Adds a new velocity gradient
  59659. * @param gradient defines the gradient to use (between 0 and 1)
  59660. * @param factor defines the velocity to affect to the specified gradient
  59661. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59662. * @returns the current particle system
  59663. */
  59664. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  59665. if (!this._velocityGradients) {
  59666. this._velocityGradients = [];
  59667. }
  59668. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  59669. return this;
  59670. };
  59671. /**
  59672. * Remove a specific velocity gradient
  59673. * @param gradient defines the gradient to remove
  59674. * @returns the current particle system
  59675. */
  59676. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  59677. this._removeFactorGradient(this._velocityGradients, gradient);
  59678. return this;
  59679. };
  59680. /**
  59681. * Adds a new limit velocity gradient
  59682. * @param gradient defines the gradient to use (between 0 and 1)
  59683. * @param factor defines the limit velocity value to affect to the specified gradient
  59684. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59685. * @returns the current particle system
  59686. */
  59687. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  59688. if (!this._limitVelocityGradients) {
  59689. this._limitVelocityGradients = [];
  59690. }
  59691. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  59692. return this;
  59693. };
  59694. /**
  59695. * Remove a specific limit velocity gradient
  59696. * @param gradient defines the gradient to remove
  59697. * @returns the current particle system
  59698. */
  59699. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  59700. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  59701. return this;
  59702. };
  59703. /**
  59704. * Adds a new drag gradient
  59705. * @param gradient defines the gradient to use (between 0 and 1)
  59706. * @param factor defines the drag value to affect to the specified gradient
  59707. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59708. * @returns the current particle system
  59709. */
  59710. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  59711. if (!this._dragGradients) {
  59712. this._dragGradients = [];
  59713. }
  59714. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  59715. return this;
  59716. };
  59717. /**
  59718. * Remove a specific drag gradient
  59719. * @param gradient defines the gradient to remove
  59720. * @returns the current particle system
  59721. */
  59722. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  59723. this._removeFactorGradient(this._dragGradients, gradient);
  59724. return this;
  59725. };
  59726. /**
  59727. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  59728. * @param gradient defines the gradient to use (between 0 and 1)
  59729. * @param factor defines the emit rate value to affect to the specified gradient
  59730. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59731. * @returns the current particle system
  59732. */
  59733. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  59734. if (!this._emitRateGradients) {
  59735. this._emitRateGradients = [];
  59736. }
  59737. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  59738. return this;
  59739. };
  59740. /**
  59741. * Remove a specific emit rate gradient
  59742. * @param gradient defines the gradient to remove
  59743. * @returns the current particle system
  59744. */
  59745. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  59746. this._removeFactorGradient(this._emitRateGradients, gradient);
  59747. return this;
  59748. };
  59749. /**
  59750. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  59751. * @param gradient defines the gradient to use (between 0 and 1)
  59752. * @param factor defines the start size value to affect to the specified gradient
  59753. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59754. * @returns the current particle system
  59755. */
  59756. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  59757. if (!this._startSizeGradients) {
  59758. this._startSizeGradients = [];
  59759. }
  59760. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  59761. return this;
  59762. };
  59763. /**
  59764. * Remove a specific start size gradient
  59765. * @param gradient defines the gradient to remove
  59766. * @returns the current particle system
  59767. */
  59768. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  59769. this._removeFactorGradient(this._emitRateGradients, gradient);
  59770. return this;
  59771. };
  59772. ParticleSystem.prototype._createRampGradientTexture = function () {
  59773. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  59774. return;
  59775. }
  59776. var data = new Uint8Array(this._rawTextureWidth * 4);
  59777. var tmpColor = BABYLON.Tmp.Color3[0];
  59778. for (var x = 0; x < this._rawTextureWidth; x++) {
  59779. var ratio = x / this._rawTextureWidth;
  59780. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  59781. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  59782. data[x * 4] = tmpColor.r * 255;
  59783. data[x * 4 + 1] = tmpColor.g * 255;
  59784. data[x * 4 + 2] = tmpColor.b * 255;
  59785. data[x * 4 + 3] = 255;
  59786. });
  59787. }
  59788. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59789. };
  59790. /**
  59791. * Gets the current list of ramp gradients.
  59792. * You must use addRampGradient and removeRampGradient to udpate this list
  59793. * @returns the list of ramp gradients
  59794. */
  59795. ParticleSystem.prototype.getRampGradients = function () {
  59796. return this._rampGradients;
  59797. };
  59798. /**
  59799. * Adds a new ramp gradient used to remap particle colors
  59800. * @param gradient defines the gradient to use (between 0 and 1)
  59801. * @param color defines the color to affect to the specified gradient
  59802. * @returns the current particle system
  59803. */
  59804. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  59805. if (!this._rampGradients) {
  59806. this._rampGradients = [];
  59807. }
  59808. var rampGradient = new BABYLON.Color3Gradient();
  59809. rampGradient.gradient = gradient;
  59810. rampGradient.color = color;
  59811. this._rampGradients.push(rampGradient);
  59812. this._rampGradients.sort(function (a, b) {
  59813. if (a.gradient < b.gradient) {
  59814. return -1;
  59815. }
  59816. else if (a.gradient > b.gradient) {
  59817. return 1;
  59818. }
  59819. return 0;
  59820. });
  59821. if (this._rampGradientsTexture) {
  59822. this._rampGradientsTexture.dispose();
  59823. this._rampGradientsTexture = null;
  59824. }
  59825. this._createRampGradientTexture();
  59826. return this;
  59827. };
  59828. /**
  59829. * Remove a specific ramp gradient
  59830. * @param gradient defines the gradient to remove
  59831. * @returns the current particle system
  59832. */
  59833. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  59834. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  59835. this._rampGradientsTexture = null;
  59836. if (this._rampGradients && this._rampGradients.length > 0) {
  59837. this._createRampGradientTexture();
  59838. }
  59839. return this;
  59840. };
  59841. /**
  59842. * Adds a new color gradient
  59843. * @param gradient defines the gradient to use (between 0 and 1)
  59844. * @param color1 defines the color to affect to the specified gradient
  59845. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59846. * @returns this particle system
  59847. */
  59848. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59849. if (!this._colorGradients) {
  59850. this._colorGradients = [];
  59851. }
  59852. var colorGradient = new BABYLON.ColorGradient();
  59853. colorGradient.gradient = gradient;
  59854. colorGradient.color1 = color1;
  59855. colorGradient.color2 = color2;
  59856. this._colorGradients.push(colorGradient);
  59857. this._colorGradients.sort(function (a, b) {
  59858. if (a.gradient < b.gradient) {
  59859. return -1;
  59860. }
  59861. else if (a.gradient > b.gradient) {
  59862. return 1;
  59863. }
  59864. return 0;
  59865. });
  59866. return this;
  59867. };
  59868. /**
  59869. * Remove a specific color gradient
  59870. * @param gradient defines the gradient to remove
  59871. * @returns this particle system
  59872. */
  59873. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  59874. if (!this._colorGradients) {
  59875. return this;
  59876. }
  59877. var index = 0;
  59878. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59879. var colorGradient = _a[_i];
  59880. if (colorGradient.gradient === gradient) {
  59881. this._colorGradients.splice(index, 1);
  59882. break;
  59883. }
  59884. index++;
  59885. }
  59886. return this;
  59887. };
  59888. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59889. u = Math.abs(u) * 0.5 + 0.5;
  59890. v = Math.abs(v) * 0.5 + 0.5;
  59891. var wrappedU = ((u * width) % width) | 0;
  59892. var wrappedV = ((v * height) % height) | 0;
  59893. var position = (wrappedU + wrappedV * width) * 4;
  59894. return pixels[position] / 255;
  59895. };
  59896. ParticleSystem.prototype._reset = function () {
  59897. this._resetEffect();
  59898. };
  59899. ParticleSystem.prototype._resetEffect = function () {
  59900. if (this._vertexBuffer) {
  59901. this._vertexBuffer.dispose();
  59902. this._vertexBuffer = null;
  59903. }
  59904. if (this._spriteBuffer) {
  59905. this._spriteBuffer.dispose();
  59906. this._spriteBuffer = null;
  59907. }
  59908. this._createVertexBuffers();
  59909. };
  59910. ParticleSystem.prototype._createVertexBuffers = function () {
  59911. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59912. if (this._isAnimationSheetEnabled) {
  59913. this._vertexBufferSize += 1;
  59914. }
  59915. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59916. this._vertexBufferSize += 3;
  59917. }
  59918. if (this._useRampGradients) {
  59919. this._vertexBufferSize += 4;
  59920. }
  59921. var engine = this._scene.getEngine();
  59922. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59923. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59924. var dataOffset = 0;
  59925. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59926. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59927. dataOffset += 3;
  59928. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59929. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59930. dataOffset += 4;
  59931. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59932. this._vertexBuffers["angle"] = options;
  59933. dataOffset += 1;
  59934. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59935. this._vertexBuffers["size"] = size;
  59936. dataOffset += 2;
  59937. if (this._isAnimationSheetEnabled) {
  59938. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59939. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59940. dataOffset += 1;
  59941. }
  59942. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59943. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59944. this._vertexBuffers["direction"] = directionBuffer;
  59945. dataOffset += 3;
  59946. }
  59947. if (this._useRampGradients) {
  59948. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59949. this._vertexBuffers["remapData"] = rampDataBuffer;
  59950. dataOffset += 4;
  59951. }
  59952. var offsets;
  59953. if (this._useInstancing) {
  59954. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59955. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59956. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59957. }
  59958. else {
  59959. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59960. dataOffset += 2;
  59961. }
  59962. this._vertexBuffers["offset"] = offsets;
  59963. };
  59964. ParticleSystem.prototype._createIndexBuffer = function () {
  59965. if (this._useInstancing) {
  59966. return;
  59967. }
  59968. var indices = [];
  59969. var index = 0;
  59970. for (var count = 0; count < this._capacity; count++) {
  59971. indices.push(index);
  59972. indices.push(index + 1);
  59973. indices.push(index + 2);
  59974. indices.push(index);
  59975. indices.push(index + 2);
  59976. indices.push(index + 3);
  59977. index += 4;
  59978. }
  59979. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  59980. };
  59981. /**
  59982. * Gets the maximum number of particles active at the same time.
  59983. * @returns The max number of active particles.
  59984. */
  59985. ParticleSystem.prototype.getCapacity = function () {
  59986. return this._capacity;
  59987. };
  59988. /**
  59989. * Gets whether there are still active particles in the system.
  59990. * @returns True if it is alive, otherwise false.
  59991. */
  59992. ParticleSystem.prototype.isAlive = function () {
  59993. return this._alive;
  59994. };
  59995. /**
  59996. * Gets if the system has been started. (Note: this will still be true after stop is called)
  59997. * @returns True if it has been started, otherwise false.
  59998. */
  59999. ParticleSystem.prototype.isStarted = function () {
  60000. return this._started;
  60001. };
  60002. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  60003. var _this = this;
  60004. this._subEmitters = new Array();
  60005. if (this.subEmitters) {
  60006. this.subEmitters.forEach(function (subEmitter) {
  60007. if (subEmitter instanceof ParticleSystem) {
  60008. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  60009. }
  60010. else if (subEmitter instanceof BABYLON.SubEmitter) {
  60011. _this._subEmitters.push([subEmitter]);
  60012. }
  60013. else if (subEmitter instanceof Array) {
  60014. _this._subEmitters.push(subEmitter);
  60015. }
  60016. });
  60017. }
  60018. };
  60019. /**
  60020. * Starts the particle system and begins to emit
  60021. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  60022. */
  60023. ParticleSystem.prototype.start = function (delay) {
  60024. var _this = this;
  60025. if (delay === void 0) { delay = this.startDelay; }
  60026. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  60027. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  60028. }
  60029. if (delay) {
  60030. setTimeout(function () {
  60031. _this.start(0);
  60032. }, delay);
  60033. return;
  60034. }
  60035. // Convert the subEmitters field to the constant type field _subEmitters
  60036. this._prepareSubEmitterInternalArray();
  60037. this._started = true;
  60038. this._stopped = false;
  60039. this._actualFrame = 0;
  60040. if (this._subEmitters && this._subEmitters.length != 0) {
  60041. this.activeSubSystems = new Array();
  60042. }
  60043. // Reset emit gradient so it acts the same on every start
  60044. if (this._emitRateGradients) {
  60045. if (this._emitRateGradients.length > 0) {
  60046. this._currentEmitRateGradient = this._emitRateGradients[0];
  60047. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  60048. this._currentEmitRate2 = this._currentEmitRate1;
  60049. }
  60050. if (this._emitRateGradients.length > 1) {
  60051. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  60052. }
  60053. }
  60054. // Reset start size gradient so it acts the same on every start
  60055. if (this._startSizeGradients) {
  60056. if (this._startSizeGradients.length > 0) {
  60057. this._currentStartSizeGradient = this._startSizeGradients[0];
  60058. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  60059. this._currentStartSize2 = this._currentStartSize1;
  60060. }
  60061. if (this._startSizeGradients.length > 1) {
  60062. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  60063. }
  60064. }
  60065. if (this.preWarmCycles) {
  60066. if (this.emitter instanceof BABYLON.AbstractMesh) {
  60067. this.emitter.computeWorldMatrix(true);
  60068. }
  60069. var noiseTextureAsProcedural_1 = this.noiseTexture;
  60070. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  60071. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  60072. setTimeout(function () {
  60073. for (var index = 0; index < _this.preWarmCycles; index++) {
  60074. _this.animate(true);
  60075. noiseTextureAsProcedural_1.render();
  60076. }
  60077. });
  60078. });
  60079. }
  60080. else {
  60081. for (var index = 0; index < this.preWarmCycles; index++) {
  60082. this.animate(true);
  60083. }
  60084. }
  60085. }
  60086. // Animations
  60087. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  60088. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  60089. }
  60090. };
  60091. /**
  60092. * Stops the particle system.
  60093. * @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.
  60094. */
  60095. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  60096. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  60097. this._stopped = true;
  60098. if (stopSubEmitters) {
  60099. this._stopSubEmitters();
  60100. }
  60101. };
  60102. // animation sheet
  60103. /**
  60104. * Remove all active particles
  60105. */
  60106. ParticleSystem.prototype.reset = function () {
  60107. this._stockParticles = [];
  60108. this._particles = [];
  60109. };
  60110. /**
  60111. * @hidden (for internal use only)
  60112. */
  60113. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  60114. var offset = index * this._vertexBufferSize;
  60115. this._vertexData[offset++] = particle.position.x;
  60116. this._vertexData[offset++] = particle.position.y;
  60117. this._vertexData[offset++] = particle.position.z;
  60118. this._vertexData[offset++] = particle.color.r;
  60119. this._vertexData[offset++] = particle.color.g;
  60120. this._vertexData[offset++] = particle.color.b;
  60121. this._vertexData[offset++] = particle.color.a;
  60122. this._vertexData[offset++] = particle.angle;
  60123. this._vertexData[offset++] = particle.scale.x * particle.size;
  60124. this._vertexData[offset++] = particle.scale.y * particle.size;
  60125. if (this._isAnimationSheetEnabled) {
  60126. this._vertexData[offset++] = particle.cellIndex;
  60127. }
  60128. if (!this._isBillboardBased) {
  60129. if (particle._initialDirection) {
  60130. this._vertexData[offset++] = particle._initialDirection.x;
  60131. this._vertexData[offset++] = particle._initialDirection.y;
  60132. this._vertexData[offset++] = particle._initialDirection.z;
  60133. }
  60134. else {
  60135. this._vertexData[offset++] = particle.direction.x;
  60136. this._vertexData[offset++] = particle.direction.y;
  60137. this._vertexData[offset++] = particle.direction.z;
  60138. }
  60139. }
  60140. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  60141. this._vertexData[offset++] = particle.direction.x;
  60142. this._vertexData[offset++] = particle.direction.y;
  60143. this._vertexData[offset++] = particle.direction.z;
  60144. }
  60145. if (this._useRampGradients) {
  60146. this._vertexData[offset++] = particle.remapData.x;
  60147. this._vertexData[offset++] = particle.remapData.y;
  60148. this._vertexData[offset++] = particle.remapData.z;
  60149. this._vertexData[offset++] = particle.remapData.w;
  60150. }
  60151. if (!this._useInstancing) {
  60152. if (this._isAnimationSheetEnabled) {
  60153. if (offsetX === 0) {
  60154. offsetX = this._epsilon;
  60155. }
  60156. else if (offsetX === 1) {
  60157. offsetX = 1 - this._epsilon;
  60158. }
  60159. if (offsetY === 0) {
  60160. offsetY = this._epsilon;
  60161. }
  60162. else if (offsetY === 1) {
  60163. offsetY = 1 - this._epsilon;
  60164. }
  60165. }
  60166. this._vertexData[offset++] = offsetX;
  60167. this._vertexData[offset++] = offsetY;
  60168. }
  60169. };
  60170. ParticleSystem.prototype._stopSubEmitters = function () {
  60171. if (!this.activeSubSystems) {
  60172. return;
  60173. }
  60174. this.activeSubSystems.forEach(function (subSystem) {
  60175. subSystem.stop(true);
  60176. });
  60177. this.activeSubSystems = new Array();
  60178. };
  60179. ParticleSystem.prototype._removeFromRoot = function () {
  60180. if (!this._rootParticleSystem) {
  60181. return;
  60182. }
  60183. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  60184. if (index !== -1) {
  60185. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  60186. }
  60187. this._rootParticleSystem = null;
  60188. };
  60189. // End of sub system methods
  60190. ParticleSystem.prototype._update = function (newParticles) {
  60191. var _this = this;
  60192. // Update current
  60193. this._alive = this._particles.length > 0;
  60194. if (this.emitter.position) {
  60195. var emitterMesh = this.emitter;
  60196. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  60197. }
  60198. else {
  60199. var emitterPosition = this.emitter;
  60200. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60201. }
  60202. this.updateFunction(this._particles);
  60203. // Add new ones
  60204. var particle;
  60205. var _loop_2 = function () {
  60206. if (this_1._particles.length === this_1._capacity) {
  60207. return "break";
  60208. }
  60209. particle = this_1._createParticle();
  60210. this_1._particles.push(particle);
  60211. // Emitter
  60212. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  60213. if (this_1.startPositionFunction) {
  60214. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  60215. }
  60216. else {
  60217. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  60218. }
  60219. if (this_1.startDirectionFunction) {
  60220. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  60221. }
  60222. else {
  60223. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  60224. }
  60225. if (emitPower === 0) {
  60226. if (!particle._initialDirection) {
  60227. particle._initialDirection = particle.direction.clone();
  60228. }
  60229. else {
  60230. particle._initialDirection.copyFrom(particle.direction);
  60231. }
  60232. }
  60233. else {
  60234. particle._initialDirection = null;
  60235. }
  60236. particle.direction.scaleInPlace(emitPower);
  60237. // Life time
  60238. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  60239. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  60240. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  60241. var factorGradient1 = currentGradient;
  60242. var factorGradient2 = nextGradient;
  60243. var lifeTime1 = factorGradient1.getFactor();
  60244. var lifeTime2 = factorGradient2.getFactor();
  60245. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  60246. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  60247. });
  60248. }
  60249. else {
  60250. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  60251. }
  60252. // Size
  60253. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  60254. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  60255. }
  60256. else {
  60257. particle._currentSizeGradient = this_1._sizeGradients[0];
  60258. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  60259. particle.size = particle._currentSize1;
  60260. if (this_1._sizeGradients.length > 1) {
  60261. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  60262. }
  60263. else {
  60264. particle._currentSize2 = particle._currentSize1;
  60265. }
  60266. }
  60267. // Size and scale
  60268. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  60269. // Adjust scale by start size
  60270. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  60271. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  60272. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  60273. if (currentGradient !== _this._currentStartSizeGradient) {
  60274. _this._currentStartSize1 = _this._currentStartSize2;
  60275. _this._currentStartSize2 = nextGradient.getFactor();
  60276. _this._currentStartSizeGradient = currentGradient;
  60277. }
  60278. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  60279. particle.scale.scaleInPlace(value);
  60280. });
  60281. }
  60282. // Angle
  60283. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  60284. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  60285. }
  60286. else {
  60287. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  60288. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  60289. particle._currentAngularSpeed1 = particle.angularSpeed;
  60290. if (this_1._angularSpeedGradients.length > 1) {
  60291. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  60292. }
  60293. else {
  60294. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  60295. }
  60296. }
  60297. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  60298. // Velocity
  60299. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  60300. particle._currentVelocityGradient = this_1._velocityGradients[0];
  60301. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  60302. if (this_1._velocityGradients.length > 1) {
  60303. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  60304. }
  60305. else {
  60306. particle._currentVelocity2 = particle._currentVelocity1;
  60307. }
  60308. }
  60309. // Limit velocity
  60310. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  60311. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  60312. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  60313. if (this_1._limitVelocityGradients.length > 1) {
  60314. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  60315. }
  60316. else {
  60317. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  60318. }
  60319. }
  60320. // Drag
  60321. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  60322. particle._currentDragGradient = this_1._dragGradients[0];
  60323. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  60324. if (this_1._dragGradients.length > 1) {
  60325. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  60326. }
  60327. else {
  60328. particle._currentDrag2 = particle._currentDrag1;
  60329. }
  60330. }
  60331. // Color
  60332. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  60333. step = BABYLON.Scalar.RandomRange(0, 1.0);
  60334. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  60335. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  60336. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  60337. }
  60338. else {
  60339. particle._currentColorGradient = this_1._colorGradients[0];
  60340. particle._currentColorGradient.getColorToRef(particle.color);
  60341. particle._currentColor1.copyFrom(particle.color);
  60342. if (this_1._colorGradients.length > 1) {
  60343. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  60344. }
  60345. else {
  60346. particle._currentColor2.copyFrom(particle.color);
  60347. }
  60348. }
  60349. // Sheet
  60350. if (this_1._isAnimationSheetEnabled) {
  60351. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  60352. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  60353. }
  60354. // Inherited Velocity
  60355. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  60356. // Ramp
  60357. if (this_1._useRampGradients) {
  60358. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  60359. }
  60360. // Noise texture coordinates
  60361. if (this_1.noiseTexture) {
  60362. if (particle._randomNoiseCoordinates1) {
  60363. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  60364. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  60365. }
  60366. else {
  60367. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60368. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60369. }
  60370. }
  60371. // Update the position of the attached sub-emitters to match their attached particle
  60372. particle._inheritParticleInfoToSubEmitters();
  60373. };
  60374. var this_1 = this, step;
  60375. for (var index = 0; index < newParticles; index++) {
  60376. var state_1 = _loop_2();
  60377. if (state_1 === "break")
  60378. break;
  60379. }
  60380. };
  60381. /** @hidden */
  60382. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  60383. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60384. if (isBillboardBased === void 0) { isBillboardBased = false; }
  60385. if (useRampGradients === void 0) { useRampGradients = false; }
  60386. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  60387. if (isAnimationSheetEnabled) {
  60388. attributeNamesOrOptions.push("cellIndex");
  60389. }
  60390. if (!isBillboardBased) {
  60391. attributeNamesOrOptions.push("direction");
  60392. }
  60393. if (useRampGradients) {
  60394. attributeNamesOrOptions.push("remapData");
  60395. }
  60396. return attributeNamesOrOptions;
  60397. };
  60398. /** @hidden */
  60399. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  60400. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60401. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  60402. if (isAnimationSheetEnabled) {
  60403. effectCreationOption.push("particlesInfos");
  60404. }
  60405. return effectCreationOption;
  60406. };
  60407. /** @hidden */
  60408. ParticleSystem.prototype._getEffect = function (blendMode) {
  60409. if (this._customEffect) {
  60410. return this._customEffect;
  60411. }
  60412. var defines = [];
  60413. if (this._scene.clipPlane) {
  60414. defines.push("#define CLIPPLANE");
  60415. }
  60416. if (this._scene.clipPlane2) {
  60417. defines.push("#define CLIPPLANE2");
  60418. }
  60419. if (this._scene.clipPlane3) {
  60420. defines.push("#define CLIPPLANE3");
  60421. }
  60422. if (this._scene.clipPlane4) {
  60423. defines.push("#define CLIPPLANE4");
  60424. }
  60425. if (this._isAnimationSheetEnabled) {
  60426. defines.push("#define ANIMATESHEET");
  60427. }
  60428. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  60429. defines.push("#define BLENDMULTIPLYMODE");
  60430. }
  60431. if (this._useRampGradients) {
  60432. defines.push("#define RAMPGRADIENT");
  60433. }
  60434. if (this._isBillboardBased) {
  60435. defines.push("#define BILLBOARD");
  60436. switch (this.billboardMode) {
  60437. case ParticleSystem.BILLBOARDMODE_Y:
  60438. defines.push("#define BILLBOARDY");
  60439. break;
  60440. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  60441. defines.push("#define BILLBOARDSTRETCHED");
  60442. break;
  60443. case ParticleSystem.BILLBOARDMODE_ALL:
  60444. default:
  60445. break;
  60446. }
  60447. }
  60448. if (this._imageProcessingConfiguration) {
  60449. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  60450. defines.push(this._imageProcessingConfigurationDefines.toString());
  60451. }
  60452. // Effect
  60453. var join = defines.join("\n");
  60454. if (this._cachedDefines !== join) {
  60455. this._cachedDefines = join;
  60456. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  60457. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  60458. var samplers = ["diffuseSampler", "rampSampler"];
  60459. if (BABYLON.ImageProcessingConfiguration) {
  60460. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  60461. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  60462. }
  60463. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  60464. }
  60465. return this._effect;
  60466. };
  60467. /**
  60468. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60469. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  60470. */
  60471. ParticleSystem.prototype.animate = function (preWarmOnly) {
  60472. var _this = this;
  60473. if (preWarmOnly === void 0) { preWarmOnly = false; }
  60474. if (!this._started) {
  60475. return;
  60476. }
  60477. if (!preWarmOnly) {
  60478. // Check
  60479. if (!this.isReady()) {
  60480. return;
  60481. }
  60482. if (this._currentRenderId === this._scene.getRenderId()) {
  60483. return;
  60484. }
  60485. this._currentRenderId = this._scene.getRenderId();
  60486. }
  60487. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60488. // Determine the number of particles we need to create
  60489. var newParticles;
  60490. if (this.manualEmitCount > -1) {
  60491. newParticles = this.manualEmitCount;
  60492. this._newPartsExcess = 0;
  60493. this.manualEmitCount = 0;
  60494. }
  60495. else {
  60496. var rate_1 = this.emitRate;
  60497. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  60498. var ratio = this._actualFrame / this.targetStopDuration;
  60499. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  60500. if (currentGradient !== _this._currentEmitRateGradient) {
  60501. _this._currentEmitRate1 = _this._currentEmitRate2;
  60502. _this._currentEmitRate2 = nextGradient.getFactor();
  60503. _this._currentEmitRateGradient = currentGradient;
  60504. }
  60505. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  60506. });
  60507. }
  60508. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  60509. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  60510. }
  60511. if (this._newPartsExcess > 1.0) {
  60512. newParticles += this._newPartsExcess >> 0;
  60513. this._newPartsExcess -= this._newPartsExcess >> 0;
  60514. }
  60515. this._alive = false;
  60516. if (!this._stopped) {
  60517. this._actualFrame += this._scaledUpdateSpeed;
  60518. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60519. this.stop();
  60520. }
  60521. }
  60522. else {
  60523. newParticles = 0;
  60524. }
  60525. this._update(newParticles);
  60526. // Stopped?
  60527. if (this._stopped) {
  60528. if (!this._alive) {
  60529. this._started = false;
  60530. if (this.onAnimationEnd) {
  60531. this.onAnimationEnd();
  60532. }
  60533. if (this.disposeOnStop) {
  60534. this._scene._toBeDisposed.push(this);
  60535. }
  60536. }
  60537. }
  60538. if (!preWarmOnly) {
  60539. // Update VBO
  60540. var offset = 0;
  60541. for (var index = 0; index < this._particles.length; index++) {
  60542. var particle = this._particles[index];
  60543. this._appendParticleVertices(offset, particle);
  60544. offset += this._useInstancing ? 1 : 4;
  60545. }
  60546. if (this._vertexBuffer) {
  60547. this._vertexBuffer.update(this._vertexData);
  60548. }
  60549. }
  60550. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  60551. this.stop();
  60552. }
  60553. };
  60554. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  60555. this._appendParticleVertex(offset++, particle, 0, 0);
  60556. if (!this._useInstancing) {
  60557. this._appendParticleVertex(offset++, particle, 1, 0);
  60558. this._appendParticleVertex(offset++, particle, 1, 1);
  60559. this._appendParticleVertex(offset++, particle, 0, 1);
  60560. }
  60561. };
  60562. /**
  60563. * Rebuilds the particle system.
  60564. */
  60565. ParticleSystem.prototype.rebuild = function () {
  60566. this._createIndexBuffer();
  60567. if (this._vertexBuffer) {
  60568. this._vertexBuffer._rebuild();
  60569. }
  60570. };
  60571. /**
  60572. * Is this system ready to be used/rendered
  60573. * @return true if the system is ready
  60574. */
  60575. ParticleSystem.prototype.isReady = function () {
  60576. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60577. return false;
  60578. }
  60579. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60580. if (!this._getEffect(this.blendMode).isReady()) {
  60581. return false;
  60582. }
  60583. }
  60584. else {
  60585. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  60586. return false;
  60587. }
  60588. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  60589. return false;
  60590. }
  60591. }
  60592. return true;
  60593. };
  60594. ParticleSystem.prototype._render = function (blendMode) {
  60595. var effect = this._getEffect(blendMode);
  60596. var engine = this._scene.getEngine();
  60597. // Render
  60598. engine.enableEffect(effect);
  60599. var viewMatrix = this._scene.getViewMatrix();
  60600. effect.setTexture("diffuseSampler", this.particleTexture);
  60601. effect.setMatrix("view", viewMatrix);
  60602. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  60603. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60604. var baseSize = this.particleTexture.getBaseSize();
  60605. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60606. }
  60607. effect.setVector2("translationPivot", this.translationPivot);
  60608. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  60609. if (this._isBillboardBased) {
  60610. var camera = this._scene.activeCamera;
  60611. effect.setVector3("eyePosition", camera.globalPosition);
  60612. }
  60613. if (this._rampGradientsTexture) {
  60614. effect.setTexture("rampSampler", this._rampGradientsTexture);
  60615. }
  60616. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  60617. var invView = viewMatrix.clone();
  60618. invView.invert();
  60619. effect.setMatrix("invView", invView);
  60620. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  60621. }
  60622. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  60623. // image processing
  60624. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  60625. this._imageProcessingConfiguration.bind(effect);
  60626. }
  60627. // Draw order
  60628. switch (blendMode) {
  60629. case ParticleSystem.BLENDMODE_ADD:
  60630. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60631. break;
  60632. case ParticleSystem.BLENDMODE_ONEONE:
  60633. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60634. break;
  60635. case ParticleSystem.BLENDMODE_STANDARD:
  60636. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60637. break;
  60638. case ParticleSystem.BLENDMODE_MULTIPLY:
  60639. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  60640. break;
  60641. }
  60642. if (this._useInstancing) {
  60643. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  60644. }
  60645. else {
  60646. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  60647. }
  60648. return this._particles.length;
  60649. };
  60650. /**
  60651. * Renders the particle system in its current state.
  60652. * @returns the current number of particles
  60653. */
  60654. ParticleSystem.prototype.render = function () {
  60655. // Check
  60656. if (!this.isReady() || !this._particles.length) {
  60657. return 0;
  60658. }
  60659. var engine = this._scene.getEngine();
  60660. engine.setState(false);
  60661. if (this.forceDepthWrite) {
  60662. engine.setDepthWrite(true);
  60663. }
  60664. var outparticles = 0;
  60665. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60666. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  60667. }
  60668. outparticles = this._render(this.blendMode);
  60669. engine.unbindInstanceAttributes();
  60670. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60671. return outparticles;
  60672. };
  60673. /**
  60674. * Disposes the particle system and free the associated resources
  60675. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60676. */
  60677. ParticleSystem.prototype.dispose = function (disposeTexture) {
  60678. if (disposeTexture === void 0) { disposeTexture = true; }
  60679. if (this._vertexBuffer) {
  60680. this._vertexBuffer.dispose();
  60681. this._vertexBuffer = null;
  60682. }
  60683. if (this._spriteBuffer) {
  60684. this._spriteBuffer.dispose();
  60685. this._spriteBuffer = null;
  60686. }
  60687. if (this._indexBuffer) {
  60688. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60689. this._indexBuffer = null;
  60690. }
  60691. if (disposeTexture && this.particleTexture) {
  60692. this.particleTexture.dispose();
  60693. this.particleTexture = null;
  60694. }
  60695. if (disposeTexture && this.noiseTexture) {
  60696. this.noiseTexture.dispose();
  60697. this.noiseTexture = null;
  60698. }
  60699. if (this._rampGradientsTexture) {
  60700. this._rampGradientsTexture.dispose();
  60701. this._rampGradientsTexture = null;
  60702. }
  60703. this._removeFromRoot();
  60704. if (this._subEmitters && this._subEmitters.length) {
  60705. for (var index = 0; index < this._subEmitters.length; index++) {
  60706. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  60707. var subEmitter = _a[_i];
  60708. subEmitter.dispose();
  60709. }
  60710. }
  60711. this._subEmitters = [];
  60712. this.subEmitters = [];
  60713. }
  60714. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  60715. this.emitter.dispose(true);
  60716. }
  60717. // Remove from scene
  60718. var index = this._scene.particleSystems.indexOf(this);
  60719. if (index > -1) {
  60720. this._scene.particleSystems.splice(index, 1);
  60721. }
  60722. this._scene._activeParticleSystems.dispose();
  60723. // Callback
  60724. this.onDisposeObservable.notifyObservers(this);
  60725. this.onDisposeObservable.clear();
  60726. this.reset();
  60727. };
  60728. // Clone
  60729. /**
  60730. * Clones the particle system.
  60731. * @param name The name of the cloned object
  60732. * @param newEmitter The new emitter to use
  60733. * @returns the cloned particle system
  60734. */
  60735. ParticleSystem.prototype.clone = function (name, newEmitter) {
  60736. var custom = null;
  60737. var program = null;
  60738. if (this.customShader != null) {
  60739. program = this.customShader;
  60740. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60741. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60742. }
  60743. else if (this._customEffect) {
  60744. custom = this._customEffect;
  60745. }
  60746. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  60747. result.customShader = program;
  60748. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  60749. if (newEmitter === undefined) {
  60750. newEmitter = this.emitter;
  60751. }
  60752. result.noiseTexture = this.noiseTexture;
  60753. result.emitter = newEmitter;
  60754. if (this.particleTexture) {
  60755. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60756. }
  60757. // Clone gradients
  60758. if (this._colorGradients) {
  60759. this._colorGradients.forEach(function (v) {
  60760. result.addColorGradient(v.gradient, v.color1, v.color2);
  60761. });
  60762. }
  60763. if (this._dragGradients) {
  60764. this._dragGradients.forEach(function (v) {
  60765. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  60766. });
  60767. }
  60768. if (this._angularSpeedGradients) {
  60769. this._angularSpeedGradients.forEach(function (v) {
  60770. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  60771. });
  60772. }
  60773. if (this._emitRateGradients) {
  60774. this._emitRateGradients.forEach(function (v) {
  60775. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  60776. });
  60777. }
  60778. if (this._lifeTimeGradients) {
  60779. this._lifeTimeGradients.forEach(function (v) {
  60780. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  60781. });
  60782. }
  60783. if (this._limitVelocityGradients) {
  60784. this._limitVelocityGradients.forEach(function (v) {
  60785. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  60786. });
  60787. }
  60788. if (this._sizeGradients) {
  60789. this._sizeGradients.forEach(function (v) {
  60790. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  60791. });
  60792. }
  60793. if (this._startSizeGradients) {
  60794. this._startSizeGradients.forEach(function (v) {
  60795. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  60796. });
  60797. }
  60798. if (this._velocityGradients) {
  60799. this._velocityGradients.forEach(function (v) {
  60800. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  60801. });
  60802. }
  60803. if (this._rampGradients) {
  60804. this._rampGradients.forEach(function (v) {
  60805. result.addRampGradient(v.gradient, v.color);
  60806. });
  60807. }
  60808. if (this._colorRemapGradients) {
  60809. this._colorRemapGradients.forEach(function (v) {
  60810. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  60811. });
  60812. }
  60813. if (this._alphaRemapGradients) {
  60814. this._alphaRemapGradients.forEach(function (v) {
  60815. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  60816. });
  60817. }
  60818. if (!this.preventAutoStart) {
  60819. result.start();
  60820. }
  60821. return result;
  60822. };
  60823. /**
  60824. * Serializes the particle system to a JSON object.
  60825. * @returns the JSON object
  60826. */
  60827. ParticleSystem.prototype.serialize = function () {
  60828. var serializationObject = {};
  60829. ParticleSystem._Serialize(serializationObject, this);
  60830. serializationObject.textureMask = this.textureMask.asArray();
  60831. serializationObject.customShader = this.customShader;
  60832. serializationObject.preventAutoStart = this.preventAutoStart;
  60833. // SubEmitters
  60834. if (this.subEmitters) {
  60835. serializationObject.subEmitters = [];
  60836. if (!this._subEmitters) {
  60837. this._prepareSubEmitterInternalArray();
  60838. }
  60839. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  60840. var subs = _a[_i];
  60841. var cell = [];
  60842. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  60843. var sub = subs_1[_b];
  60844. cell.push(sub.serialize());
  60845. }
  60846. serializationObject.subEmitters.push(cell);
  60847. }
  60848. }
  60849. return serializationObject;
  60850. };
  60851. /** @hidden */
  60852. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  60853. serializationObject.name = particleSystem.name;
  60854. serializationObject.id = particleSystem.id;
  60855. serializationObject.capacity = particleSystem.getCapacity();
  60856. // Emitter
  60857. if (particleSystem.emitter.position) {
  60858. var emitterMesh = particleSystem.emitter;
  60859. serializationObject.emitterId = emitterMesh.id;
  60860. }
  60861. else {
  60862. var emitterPosition = particleSystem.emitter;
  60863. serializationObject.emitter = emitterPosition.asArray();
  60864. }
  60865. // Emitter
  60866. if (particleSystem.particleEmitterType) {
  60867. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  60868. }
  60869. if (particleSystem.particleTexture) {
  60870. serializationObject.textureName = particleSystem.particleTexture.name;
  60871. serializationObject.invertY = particleSystem.particleTexture._invertY;
  60872. }
  60873. // Animations
  60874. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  60875. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  60876. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  60877. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  60878. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  60879. // Particle system
  60880. serializationObject.startDelay = particleSystem.startDelay;
  60881. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  60882. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  60883. serializationObject.billboardMode = particleSystem.billboardMode;
  60884. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  60885. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  60886. serializationObject.minSize = particleSystem.minSize;
  60887. serializationObject.maxSize = particleSystem.maxSize;
  60888. serializationObject.minScaleX = particleSystem.minScaleX;
  60889. serializationObject.maxScaleX = particleSystem.maxScaleX;
  60890. serializationObject.minScaleY = particleSystem.minScaleY;
  60891. serializationObject.maxScaleY = particleSystem.maxScaleY;
  60892. serializationObject.minEmitPower = particleSystem.minEmitPower;
  60893. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  60894. serializationObject.minLifeTime = particleSystem.minLifeTime;
  60895. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  60896. serializationObject.emitRate = particleSystem.emitRate;
  60897. serializationObject.gravity = particleSystem.gravity.asArray();
  60898. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  60899. serializationObject.color1 = particleSystem.color1.asArray();
  60900. serializationObject.color2 = particleSystem.color2.asArray();
  60901. serializationObject.colorDead = particleSystem.colorDead.asArray();
  60902. serializationObject.updateSpeed = particleSystem.updateSpeed;
  60903. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60904. serializationObject.blendMode = particleSystem.blendMode;
  60905. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60906. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60907. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60908. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60909. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60910. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60911. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60912. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60913. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60914. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60915. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60916. var colorGradients = particleSystem.getColorGradients();
  60917. if (colorGradients) {
  60918. serializationObject.colorGradients = [];
  60919. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60920. var colorGradient = colorGradients_1[_i];
  60921. var serializedGradient = {
  60922. gradient: colorGradient.gradient,
  60923. color1: colorGradient.color1.asArray()
  60924. };
  60925. if (colorGradient.color2) {
  60926. serializedGradient.color2 = colorGradient.color2.asArray();
  60927. }
  60928. serializationObject.colorGradients.push(serializedGradient);
  60929. }
  60930. }
  60931. var rampGradients = particleSystem.getRampGradients();
  60932. if (rampGradients) {
  60933. serializationObject.rampGradients = [];
  60934. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60935. var rampGradient = rampGradients_1[_a];
  60936. var serializedGradient = {
  60937. gradient: rampGradient.gradient,
  60938. color: rampGradient.color.asArray()
  60939. };
  60940. serializationObject.rampGradients.push(serializedGradient);
  60941. }
  60942. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60943. }
  60944. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60945. if (colorRemapGradients) {
  60946. serializationObject.colorRemapGradients = [];
  60947. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60948. var colorRemapGradient = colorRemapGradients_1[_b];
  60949. var serializedGradient = {
  60950. gradient: colorRemapGradient.gradient,
  60951. factor1: colorRemapGradient.factor1
  60952. };
  60953. if (colorRemapGradient.factor2 !== undefined) {
  60954. serializedGradient.factor2 = colorRemapGradient.factor2;
  60955. }
  60956. serializationObject.colorRemapGradients.push(serializedGradient);
  60957. }
  60958. }
  60959. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60960. if (alphaRemapGradients) {
  60961. serializationObject.alphaRemapGradients = [];
  60962. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60963. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60964. var serializedGradient = {
  60965. gradient: alphaRemapGradient.gradient,
  60966. factor1: alphaRemapGradient.factor1
  60967. };
  60968. if (alphaRemapGradient.factor2 !== undefined) {
  60969. serializedGradient.factor2 = alphaRemapGradient.factor2;
  60970. }
  60971. serializationObject.alphaRemapGradients.push(serializedGradient);
  60972. }
  60973. }
  60974. var sizeGradients = particleSystem.getSizeGradients();
  60975. if (sizeGradients) {
  60976. serializationObject.sizeGradients = [];
  60977. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  60978. var sizeGradient = sizeGradients_1[_d];
  60979. var serializedGradient = {
  60980. gradient: sizeGradient.gradient,
  60981. factor1: sizeGradient.factor1
  60982. };
  60983. if (sizeGradient.factor2 !== undefined) {
  60984. serializedGradient.factor2 = sizeGradient.factor2;
  60985. }
  60986. serializationObject.sizeGradients.push(serializedGradient);
  60987. }
  60988. }
  60989. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  60990. if (angularSpeedGradients) {
  60991. serializationObject.angularSpeedGradients = [];
  60992. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  60993. var angularSpeedGradient = angularSpeedGradients_1[_e];
  60994. var serializedGradient = {
  60995. gradient: angularSpeedGradient.gradient,
  60996. factor1: angularSpeedGradient.factor1
  60997. };
  60998. if (angularSpeedGradient.factor2 !== undefined) {
  60999. serializedGradient.factor2 = angularSpeedGradient.factor2;
  61000. }
  61001. serializationObject.angularSpeedGradients.push(serializedGradient);
  61002. }
  61003. }
  61004. var velocityGradients = particleSystem.getVelocityGradients();
  61005. if (velocityGradients) {
  61006. serializationObject.velocityGradients = [];
  61007. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  61008. var velocityGradient = velocityGradients_1[_f];
  61009. var serializedGradient = {
  61010. gradient: velocityGradient.gradient,
  61011. factor1: velocityGradient.factor1
  61012. };
  61013. if (velocityGradient.factor2 !== undefined) {
  61014. serializedGradient.factor2 = velocityGradient.factor2;
  61015. }
  61016. serializationObject.velocityGradients.push(serializedGradient);
  61017. }
  61018. }
  61019. var dragGradients = particleSystem.getDragGradients();
  61020. if (dragGradients) {
  61021. serializationObject.dragyGradients = [];
  61022. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  61023. var dragGradient = dragGradients_1[_g];
  61024. var serializedGradient = {
  61025. gradient: dragGradient.gradient,
  61026. factor1: dragGradient.factor1
  61027. };
  61028. if (dragGradient.factor2 !== undefined) {
  61029. serializedGradient.factor2 = dragGradient.factor2;
  61030. }
  61031. serializationObject.dragGradients.push(serializedGradient);
  61032. }
  61033. }
  61034. var emitRateGradients = particleSystem.getEmitRateGradients();
  61035. if (emitRateGradients) {
  61036. serializationObject.emitRateGradients = [];
  61037. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  61038. var emitRateGradient = emitRateGradients_1[_h];
  61039. var serializedGradient = {
  61040. gradient: emitRateGradient.gradient,
  61041. factor1: emitRateGradient.factor1
  61042. };
  61043. if (emitRateGradient.factor2 !== undefined) {
  61044. serializedGradient.factor2 = emitRateGradient.factor2;
  61045. }
  61046. serializationObject.emitRateGradients.push(serializedGradient);
  61047. }
  61048. }
  61049. var startSizeGradients = particleSystem.getStartSizeGradients();
  61050. if (startSizeGradients) {
  61051. serializationObject.startSizeGradients = [];
  61052. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  61053. var startSizeGradient = startSizeGradients_1[_j];
  61054. var serializedGradient = {
  61055. gradient: startSizeGradient.gradient,
  61056. factor1: startSizeGradient.factor1
  61057. };
  61058. if (startSizeGradient.factor2 !== undefined) {
  61059. serializedGradient.factor2 = startSizeGradient.factor2;
  61060. }
  61061. serializationObject.startSizeGradients.push(serializedGradient);
  61062. }
  61063. }
  61064. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  61065. if (lifeTimeGradients) {
  61066. serializationObject.lifeTimeGradients = [];
  61067. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  61068. var lifeTimeGradient = lifeTimeGradients_1[_k];
  61069. var serializedGradient = {
  61070. gradient: lifeTimeGradient.gradient,
  61071. factor1: lifeTimeGradient.factor1
  61072. };
  61073. if (lifeTimeGradient.factor2 !== undefined) {
  61074. serializedGradient.factor2 = lifeTimeGradient.factor2;
  61075. }
  61076. serializationObject.lifeTimeGradients.push(serializedGradient);
  61077. }
  61078. }
  61079. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  61080. if (limitVelocityGradients) {
  61081. serializationObject.limitVelocityGradients = [];
  61082. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  61083. var limitVelocityGradient = limitVelocityGradients_1[_l];
  61084. var serializedGradient = {
  61085. gradient: limitVelocityGradient.gradient,
  61086. factor1: limitVelocityGradient.factor1
  61087. };
  61088. if (limitVelocityGradient.factor2 !== undefined) {
  61089. serializedGradient.factor2 = limitVelocityGradient.factor2;
  61090. }
  61091. serializationObject.limitVelocityGradients.push(serializedGradient);
  61092. }
  61093. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  61094. }
  61095. if (particleSystem.noiseTexture) {
  61096. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  61097. }
  61098. };
  61099. /** @hidden */
  61100. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  61101. // Texture
  61102. if (parsedParticleSystem.textureName) {
  61103. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  61104. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  61105. }
  61106. // Emitter
  61107. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  61108. particleSystem.emitter = BABYLON.Vector3.Zero();
  61109. }
  61110. else if (parsedParticleSystem.emitterId) {
  61111. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  61112. }
  61113. else {
  61114. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  61115. }
  61116. // Misc.
  61117. if (parsedParticleSystem.renderingGroupId !== undefined) {
  61118. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  61119. }
  61120. if (parsedParticleSystem.isBillboardBased !== undefined) {
  61121. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  61122. }
  61123. if (parsedParticleSystem.billboardMode !== undefined) {
  61124. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  61125. }
  61126. // Animations
  61127. if (parsedParticleSystem.animations) {
  61128. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  61129. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  61130. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61131. }
  61132. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  61133. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  61134. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  61135. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  61136. }
  61137. if (parsedParticleSystem.autoAnimate) {
  61138. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  61139. }
  61140. // Particle system
  61141. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  61142. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  61143. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  61144. particleSystem.minSize = parsedParticleSystem.minSize;
  61145. particleSystem.maxSize = parsedParticleSystem.maxSize;
  61146. if (parsedParticleSystem.minScaleX) {
  61147. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  61148. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  61149. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  61150. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  61151. }
  61152. if (parsedParticleSystem.preWarmCycles !== undefined) {
  61153. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  61154. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  61155. }
  61156. if (parsedParticleSystem.minInitialRotation !== undefined) {
  61157. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  61158. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  61159. }
  61160. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  61161. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  61162. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  61163. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  61164. particleSystem.emitRate = parsedParticleSystem.emitRate;
  61165. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  61166. if (parsedParticleSystem.noiseStrength) {
  61167. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  61168. }
  61169. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  61170. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  61171. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  61172. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  61173. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  61174. particleSystem.blendMode = parsedParticleSystem.blendMode;
  61175. if (parsedParticleSystem.colorGradients) {
  61176. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  61177. var colorGradient = _a[_i];
  61178. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  61179. }
  61180. }
  61181. if (parsedParticleSystem.rampGradients) {
  61182. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  61183. var rampGradient = _c[_b];
  61184. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  61185. }
  61186. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  61187. }
  61188. if (parsedParticleSystem.colorRemapGradients) {
  61189. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  61190. var colorRemapGradient = _e[_d];
  61191. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  61192. }
  61193. }
  61194. if (parsedParticleSystem.alphaRemapGradients) {
  61195. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  61196. var alphaRemapGradient = _g[_f];
  61197. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  61198. }
  61199. }
  61200. if (parsedParticleSystem.sizeGradients) {
  61201. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  61202. var sizeGradient = _j[_h];
  61203. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  61204. }
  61205. }
  61206. if (parsedParticleSystem.sizeGradients) {
  61207. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  61208. var sizeGradient = _l[_k];
  61209. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  61210. }
  61211. }
  61212. if (parsedParticleSystem.angularSpeedGradients) {
  61213. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  61214. var angularSpeedGradient = _o[_m];
  61215. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  61216. }
  61217. }
  61218. if (parsedParticleSystem.velocityGradients) {
  61219. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  61220. var velocityGradient = _q[_p];
  61221. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  61222. }
  61223. }
  61224. if (parsedParticleSystem.dragGradients) {
  61225. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  61226. var dragGradient = _s[_r];
  61227. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  61228. }
  61229. }
  61230. if (parsedParticleSystem.emitRateGradients) {
  61231. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  61232. var emitRateGradient = _u[_t];
  61233. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  61234. }
  61235. }
  61236. if (parsedParticleSystem.startSizeGradients) {
  61237. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  61238. var startSizeGradient = _w[_v];
  61239. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  61240. }
  61241. }
  61242. if (parsedParticleSystem.lifeTimeGradients) {
  61243. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  61244. var lifeTimeGradient = _y[_x];
  61245. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  61246. }
  61247. }
  61248. if (parsedParticleSystem.limitVelocityGradients) {
  61249. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  61250. var limitVelocityGradient = _0[_z];
  61251. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  61252. }
  61253. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  61254. }
  61255. if (parsedParticleSystem.noiseTexture) {
  61256. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  61257. }
  61258. // Emitter
  61259. var emitterType;
  61260. if (parsedParticleSystem.particleEmitterType) {
  61261. switch (parsedParticleSystem.particleEmitterType.type) {
  61262. case "SphereParticleEmitter":
  61263. emitterType = new BABYLON.SphereParticleEmitter();
  61264. break;
  61265. case "SphereDirectedParticleEmitter":
  61266. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  61267. break;
  61268. case "ConeEmitter":
  61269. case "ConeParticleEmitter":
  61270. emitterType = new BABYLON.ConeParticleEmitter();
  61271. break;
  61272. case "CylinderParticleEmitter":
  61273. emitterType = new BABYLON.CylinderParticleEmitter();
  61274. break;
  61275. case "HemisphericParticleEmitter":
  61276. emitterType = new BABYLON.HemisphericParticleEmitter();
  61277. break;
  61278. case "BoxEmitter":
  61279. case "BoxParticleEmitter":
  61280. default:
  61281. emitterType = new BABYLON.BoxParticleEmitter();
  61282. break;
  61283. }
  61284. emitterType.parse(parsedParticleSystem.particleEmitterType);
  61285. }
  61286. else {
  61287. emitterType = new BABYLON.BoxParticleEmitter();
  61288. emitterType.parse(parsedParticleSystem);
  61289. }
  61290. particleSystem.particleEmitterType = emitterType;
  61291. // Animation sheet
  61292. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  61293. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  61294. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  61295. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  61296. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  61297. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  61298. };
  61299. /**
  61300. * Parses a JSON object to create a particle system.
  61301. * @param parsedParticleSystem The JSON object to parse
  61302. * @param scene The scene to create the particle system in
  61303. * @param rootUrl The root url to use to load external dependencies like texture
  61304. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  61305. * @returns the Parsed particle system
  61306. */
  61307. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  61308. if (doNotStart === void 0) { doNotStart = false; }
  61309. var name = parsedParticleSystem.name;
  61310. var custom = null;
  61311. var program = null;
  61312. if (parsedParticleSystem.customShader) {
  61313. program = parsedParticleSystem.customShader;
  61314. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61315. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61316. }
  61317. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  61318. particleSystem.customShader = program;
  61319. if (parsedParticleSystem.id) {
  61320. particleSystem.id = parsedParticleSystem.id;
  61321. }
  61322. // SubEmitters
  61323. if (parsedParticleSystem.subEmitters) {
  61324. particleSystem.subEmitters = [];
  61325. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  61326. var cell = _a[_i];
  61327. var cellArray = [];
  61328. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  61329. var sub = cell_1[_b];
  61330. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  61331. }
  61332. particleSystem.subEmitters.push(cellArray);
  61333. }
  61334. }
  61335. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61336. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  61337. // Auto start
  61338. if (parsedParticleSystem.preventAutoStart) {
  61339. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  61340. }
  61341. if (!doNotStart && !particleSystem.preventAutoStart) {
  61342. particleSystem.start();
  61343. }
  61344. return particleSystem;
  61345. };
  61346. /**
  61347. * Billboard mode will only apply to Y axis
  61348. */
  61349. ParticleSystem.BILLBOARDMODE_Y = 2;
  61350. /**
  61351. * Billboard mode will apply to all axes
  61352. */
  61353. ParticleSystem.BILLBOARDMODE_ALL = 7;
  61354. /**
  61355. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  61356. */
  61357. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  61358. return ParticleSystem;
  61359. }(BABYLON.BaseParticleSystem));
  61360. BABYLON.ParticleSystem = ParticleSystem;
  61361. })(BABYLON || (BABYLON = {}));
  61362. //# sourceMappingURL=babylon.particleSystem.js.map
  61363. var BABYLON;
  61364. (function (BABYLON) {
  61365. /**
  61366. * Particle emitter emitting particles from the inside of a box.
  61367. * It emits the particles randomly between 2 given directions.
  61368. */
  61369. var BoxParticleEmitter = /** @class */ (function () {
  61370. /**
  61371. * Creates a new instance BoxParticleEmitter
  61372. */
  61373. function BoxParticleEmitter() {
  61374. /**
  61375. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61376. */
  61377. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61378. /**
  61379. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61380. */
  61381. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61382. /**
  61383. * 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.
  61384. */
  61385. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  61386. /**
  61387. * 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.
  61388. */
  61389. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  61390. }
  61391. /**
  61392. * Called by the particle System when the direction is computed for the created particle.
  61393. * @param worldMatrix is the world matrix of the particle system
  61394. * @param directionToUpdate is the direction vector to update with the result
  61395. * @param particle is the particle we are computed the direction for
  61396. */
  61397. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61398. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61399. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61400. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61401. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61402. };
  61403. /**
  61404. * Called by the particle System when the position is computed for the created particle.
  61405. * @param worldMatrix is the world matrix of the particle system
  61406. * @param positionToUpdate is the position vector to update with the result
  61407. * @param particle is the particle we are computed the position for
  61408. */
  61409. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61410. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  61411. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  61412. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  61413. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61414. };
  61415. /**
  61416. * Clones the current emitter and returns a copy of it
  61417. * @returns the new emitter
  61418. */
  61419. BoxParticleEmitter.prototype.clone = function () {
  61420. var newOne = new BoxParticleEmitter();
  61421. BABYLON.Tools.DeepCopy(this, newOne);
  61422. return newOne;
  61423. };
  61424. /**
  61425. * Called by the GPUParticleSystem to setup the update shader
  61426. * @param effect defines the update shader
  61427. */
  61428. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  61429. effect.setVector3("direction1", this.direction1);
  61430. effect.setVector3("direction2", this.direction2);
  61431. effect.setVector3("minEmitBox", this.minEmitBox);
  61432. effect.setVector3("maxEmitBox", this.maxEmitBox);
  61433. };
  61434. /**
  61435. * Returns a string to use to update the GPU particles update shader
  61436. * @returns a string containng the defines string
  61437. */
  61438. BoxParticleEmitter.prototype.getEffectDefines = function () {
  61439. return "#define BOXEMITTER";
  61440. };
  61441. /**
  61442. * Returns the string "BoxParticleEmitter"
  61443. * @returns a string containing the class name
  61444. */
  61445. BoxParticleEmitter.prototype.getClassName = function () {
  61446. return "BoxParticleEmitter";
  61447. };
  61448. /**
  61449. * Serializes the particle system to a JSON object.
  61450. * @returns the JSON object
  61451. */
  61452. BoxParticleEmitter.prototype.serialize = function () {
  61453. var serializationObject = {};
  61454. serializationObject.type = this.getClassName();
  61455. serializationObject.direction1 = this.direction1.asArray();
  61456. serializationObject.direction2 = this.direction2.asArray();
  61457. serializationObject.minEmitBox = this.minEmitBox.asArray();
  61458. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  61459. return serializationObject;
  61460. };
  61461. /**
  61462. * Parse properties from a JSON object
  61463. * @param serializationObject defines the JSON object
  61464. */
  61465. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  61466. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61467. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61468. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  61469. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  61470. };
  61471. return BoxParticleEmitter;
  61472. }());
  61473. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  61474. })(BABYLON || (BABYLON = {}));
  61475. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  61476. var BABYLON;
  61477. (function (BABYLON) {
  61478. /**
  61479. * Particle emitter emitting particles from the inside of a cylinder.
  61480. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  61481. */
  61482. var CylinderParticleEmitter = /** @class */ (function () {
  61483. /**
  61484. * Creates a new instance CylinderParticleEmitter
  61485. * @param radius the radius of the emission cylinder (1 by default)
  61486. * @param height the height of the emission cylinder (1 by default)
  61487. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61488. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61489. */
  61490. function CylinderParticleEmitter(
  61491. /**
  61492. * The radius of the emission cylinder.
  61493. */
  61494. radius,
  61495. /**
  61496. * The height of the emission cylinder.
  61497. */
  61498. height,
  61499. /**
  61500. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61501. */
  61502. radiusRange,
  61503. /**
  61504. * How much to randomize the particle direction [0-1].
  61505. */
  61506. directionRandomizer) {
  61507. if (radius === void 0) { radius = 1; }
  61508. if (height === void 0) { height = 1; }
  61509. if (radiusRange === void 0) { radiusRange = 1; }
  61510. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61511. this.radius = radius;
  61512. this.height = height;
  61513. this.radiusRange = radiusRange;
  61514. this.directionRandomizer = directionRandomizer;
  61515. }
  61516. /**
  61517. * Called by the particle System when the direction is computed for the created particle.
  61518. * @param worldMatrix is the world matrix of the particle system
  61519. * @param directionToUpdate is the direction vector to update with the result
  61520. * @param particle is the particle we are computed the direction for
  61521. */
  61522. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61523. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61524. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  61525. var angle = Math.atan2(direction.x, direction.z);
  61526. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  61527. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  61528. direction.x = Math.sin(angle);
  61529. direction.z = Math.cos(angle);
  61530. direction.normalize();
  61531. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61532. };
  61533. /**
  61534. * Called by the particle System when the position is computed for the created particle.
  61535. * @param worldMatrix is the world matrix of the particle system
  61536. * @param positionToUpdate is the position vector to update with the result
  61537. * @param particle is the particle we are computed the position for
  61538. */
  61539. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61540. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  61541. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61542. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  61543. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  61544. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  61545. var xPos = positionRadius * Math.cos(angle);
  61546. var zPos = positionRadius * Math.sin(angle);
  61547. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  61548. };
  61549. /**
  61550. * Clones the current emitter and returns a copy of it
  61551. * @returns the new emitter
  61552. */
  61553. CylinderParticleEmitter.prototype.clone = function () {
  61554. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  61555. BABYLON.Tools.DeepCopy(this, newOne);
  61556. return newOne;
  61557. };
  61558. /**
  61559. * Called by the GPUParticleSystem to setup the update shader
  61560. * @param effect defines the update shader
  61561. */
  61562. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  61563. effect.setFloat("radius", this.radius);
  61564. effect.setFloat("height", this.height);
  61565. effect.setFloat("radiusRange", this.radiusRange);
  61566. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61567. };
  61568. /**
  61569. * Returns a string to use to update the GPU particles update shader
  61570. * @returns a string containng the defines string
  61571. */
  61572. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  61573. return "#define CYLINDEREMITTER";
  61574. };
  61575. /**
  61576. * Returns the string "CylinderParticleEmitter"
  61577. * @returns a string containing the class name
  61578. */
  61579. CylinderParticleEmitter.prototype.getClassName = function () {
  61580. return "CylinderParticleEmitter";
  61581. };
  61582. /**
  61583. * Serializes the particle system to a JSON object.
  61584. * @returns the JSON object
  61585. */
  61586. CylinderParticleEmitter.prototype.serialize = function () {
  61587. var serializationObject = {};
  61588. serializationObject.type = this.getClassName();
  61589. serializationObject.radius = this.radius;
  61590. serializationObject.height = this.height;
  61591. serializationObject.radiusRange = this.radiusRange;
  61592. serializationObject.directionRandomizer = this.directionRandomizer;
  61593. return serializationObject;
  61594. };
  61595. /**
  61596. * Parse properties from a JSON object
  61597. * @param serializationObject defines the JSON object
  61598. */
  61599. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  61600. this.radius = serializationObject.radius;
  61601. this.height = serializationObject.height;
  61602. this.radiusRange = serializationObject.radiusRange;
  61603. this.directionRandomizer = serializationObject.directionRandomizer;
  61604. };
  61605. return CylinderParticleEmitter;
  61606. }());
  61607. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  61608. /**
  61609. * Particle emitter emitting particles from the inside of a cylinder.
  61610. * It emits the particles randomly between two vectors.
  61611. */
  61612. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  61613. __extends(CylinderDirectedParticleEmitter, _super);
  61614. /**
  61615. * Creates a new instance CylinderDirectedParticleEmitter
  61616. * @param radius the radius of the emission cylinder (1 by default)
  61617. * @param height the height of the emission cylinder (1 by default)
  61618. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61619. * @param direction1 the min limit of the emission direction (up vector by default)
  61620. * @param direction2 the max limit of the emission direction (up vector by default)
  61621. */
  61622. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  61623. /**
  61624. * The min limit of the emission direction.
  61625. */
  61626. direction1,
  61627. /**
  61628. * The max limit of the emission direction.
  61629. */
  61630. direction2) {
  61631. if (radius === void 0) { radius = 1; }
  61632. if (height === void 0) { height = 1; }
  61633. if (radiusRange === void 0) { radiusRange = 1; }
  61634. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61635. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61636. var _this = _super.call(this, radius, height, radiusRange) || this;
  61637. _this.direction1 = direction1;
  61638. _this.direction2 = direction2;
  61639. return _this;
  61640. }
  61641. /**
  61642. * Called by the particle System when the direction is computed for the created particle.
  61643. * @param worldMatrix is the world matrix of the particle system
  61644. * @param directionToUpdate is the direction vector to update with the result
  61645. * @param particle is the particle we are computed the direction for
  61646. */
  61647. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61648. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61649. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61650. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61651. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61652. };
  61653. /**
  61654. * Clones the current emitter and returns a copy of it
  61655. * @returns the new emitter
  61656. */
  61657. CylinderDirectedParticleEmitter.prototype.clone = function () {
  61658. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  61659. BABYLON.Tools.DeepCopy(this, newOne);
  61660. return newOne;
  61661. };
  61662. /**
  61663. * Called by the GPUParticleSystem to setup the update shader
  61664. * @param effect defines the update shader
  61665. */
  61666. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61667. effect.setFloat("radius", this.radius);
  61668. effect.setFloat("height", this.height);
  61669. effect.setFloat("radiusRange", this.radiusRange);
  61670. effect.setVector3("direction1", this.direction1);
  61671. effect.setVector3("direction2", this.direction2);
  61672. };
  61673. /**
  61674. * Returns a string to use to update the GPU particles update shader
  61675. * @returns a string containng the defines string
  61676. */
  61677. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61678. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  61679. };
  61680. /**
  61681. * Returns the string "CylinderDirectedParticleEmitter"
  61682. * @returns a string containing the class name
  61683. */
  61684. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  61685. return "CylinderDirectedParticleEmitter";
  61686. };
  61687. /**
  61688. * Serializes the particle system to a JSON object.
  61689. * @returns the JSON object
  61690. */
  61691. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  61692. var serializationObject = _super.prototype.serialize.call(this);
  61693. serializationObject.direction1 = this.direction1.asArray();
  61694. serializationObject.direction2 = this.direction2.asArray();
  61695. return serializationObject;
  61696. };
  61697. /**
  61698. * Parse properties from a JSON object
  61699. * @param serializationObject defines the JSON object
  61700. */
  61701. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61702. _super.prototype.parse.call(this, serializationObject);
  61703. this.direction1.copyFrom(serializationObject.direction1);
  61704. this.direction2.copyFrom(serializationObject.direction2);
  61705. };
  61706. return CylinderDirectedParticleEmitter;
  61707. }(CylinderParticleEmitter));
  61708. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  61709. })(BABYLON || (BABYLON = {}));
  61710. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  61711. var BABYLON;
  61712. (function (BABYLON) {
  61713. /**
  61714. * Particle emitter emitting particles from the inside of a cone.
  61715. * It emits the particles alongside the cone volume from the base to the particle.
  61716. * The emission direction might be randomized.
  61717. */
  61718. var ConeParticleEmitter = /** @class */ (function () {
  61719. /**
  61720. * Creates a new instance ConeParticleEmitter
  61721. * @param radius the radius of the emission cone (1 by default)
  61722. * @param angles the cone base angle (PI by default)
  61723. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  61724. */
  61725. function ConeParticleEmitter(radius, angle,
  61726. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  61727. directionRandomizer) {
  61728. if (radius === void 0) { radius = 1; }
  61729. if (angle === void 0) { angle = Math.PI; }
  61730. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61731. this.directionRandomizer = directionRandomizer;
  61732. /**
  61733. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  61734. */
  61735. this.radiusRange = 1;
  61736. /**
  61737. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  61738. */
  61739. this.heightRange = 1;
  61740. /**
  61741. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  61742. */
  61743. this.emitFromSpawnPointOnly = false;
  61744. this.angle = angle;
  61745. this.radius = radius;
  61746. }
  61747. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  61748. /**
  61749. * Gets or sets the radius of the emission cone
  61750. */
  61751. get: function () {
  61752. return this._radius;
  61753. },
  61754. set: function (value) {
  61755. this._radius = value;
  61756. this._buildHeight();
  61757. },
  61758. enumerable: true,
  61759. configurable: true
  61760. });
  61761. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  61762. /**
  61763. * Gets or sets the angle of the emission cone
  61764. */
  61765. get: function () {
  61766. return this._angle;
  61767. },
  61768. set: function (value) {
  61769. this._angle = value;
  61770. this._buildHeight();
  61771. },
  61772. enumerable: true,
  61773. configurable: true
  61774. });
  61775. ConeParticleEmitter.prototype._buildHeight = function () {
  61776. if (this._angle !== 0) {
  61777. this._height = this._radius / Math.tan(this._angle / 2);
  61778. }
  61779. else {
  61780. this._height = 1;
  61781. }
  61782. };
  61783. /**
  61784. * Called by the particle System when the direction is computed for the created particle.
  61785. * @param worldMatrix is the world matrix of the particle system
  61786. * @param directionToUpdate is the direction vector to update with the result
  61787. * @param particle is the particle we are computed the direction for
  61788. */
  61789. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61790. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  61791. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  61792. }
  61793. else {
  61794. // measure the direction Vector from the emitter to the particle.
  61795. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61796. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61797. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61798. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61799. direction.x += randX;
  61800. direction.y += randY;
  61801. direction.z += randZ;
  61802. direction.normalize();
  61803. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61804. }
  61805. };
  61806. /**
  61807. * Called by the particle System when the position is computed for the created particle.
  61808. * @param worldMatrix is the world matrix of the particle system
  61809. * @param positionToUpdate is the position vector to update with the result
  61810. * @param particle is the particle we are computed the position for
  61811. */
  61812. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61813. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  61814. var h;
  61815. if (!this.emitFromSpawnPointOnly) {
  61816. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  61817. // Better distribution in a cone at normal angles.
  61818. h = 1 - h * h;
  61819. }
  61820. else {
  61821. h = 0.0001;
  61822. }
  61823. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  61824. radius = radius * h;
  61825. var randX = radius * Math.sin(s);
  61826. var randZ = radius * Math.cos(s);
  61827. var randY = h * this._height;
  61828. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61829. };
  61830. /**
  61831. * Clones the current emitter and returns a copy of it
  61832. * @returns the new emitter
  61833. */
  61834. ConeParticleEmitter.prototype.clone = function () {
  61835. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  61836. BABYLON.Tools.DeepCopy(this, newOne);
  61837. return newOne;
  61838. };
  61839. /**
  61840. * Called by the GPUParticleSystem to setup the update shader
  61841. * @param effect defines the update shader
  61842. */
  61843. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  61844. effect.setFloat2("radius", this._radius, this.radiusRange);
  61845. effect.setFloat("coneAngle", this._angle);
  61846. effect.setFloat2("height", this._height, this.heightRange);
  61847. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61848. };
  61849. /**
  61850. * Returns a string to use to update the GPU particles update shader
  61851. * @returns a string containng the defines string
  61852. */
  61853. ConeParticleEmitter.prototype.getEffectDefines = function () {
  61854. var defines = "#define CONEEMITTER";
  61855. if (this.emitFromSpawnPointOnly) {
  61856. defines += "\n#define CONEEMITTERSPAWNPOINT";
  61857. }
  61858. return defines;
  61859. };
  61860. /**
  61861. * Returns the string "ConeParticleEmitter"
  61862. * @returns a string containing the class name
  61863. */
  61864. ConeParticleEmitter.prototype.getClassName = function () {
  61865. return "ConeParticleEmitter";
  61866. };
  61867. /**
  61868. * Serializes the particle system to a JSON object.
  61869. * @returns the JSON object
  61870. */
  61871. ConeParticleEmitter.prototype.serialize = function () {
  61872. var serializationObject = {};
  61873. serializationObject.type = this.getClassName();
  61874. serializationObject.radius = this._radius;
  61875. serializationObject.angle = this._angle;
  61876. serializationObject.directionRandomizer = this.directionRandomizer;
  61877. return serializationObject;
  61878. };
  61879. /**
  61880. * Parse properties from a JSON object
  61881. * @param serializationObject defines the JSON object
  61882. */
  61883. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  61884. this.radius = serializationObject.radius;
  61885. this.angle = serializationObject.angle;
  61886. this.directionRandomizer = serializationObject.directionRandomizer;
  61887. };
  61888. return ConeParticleEmitter;
  61889. }());
  61890. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  61891. })(BABYLON || (BABYLON = {}));
  61892. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  61893. var BABYLON;
  61894. (function (BABYLON) {
  61895. /**
  61896. * Particle emitter emitting particles from the inside of a sphere.
  61897. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  61898. */
  61899. var SphereParticleEmitter = /** @class */ (function () {
  61900. /**
  61901. * Creates a new instance SphereParticleEmitter
  61902. * @param radius the radius of the emission sphere (1 by default)
  61903. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61904. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61905. */
  61906. function SphereParticleEmitter(
  61907. /**
  61908. * The radius of the emission sphere.
  61909. */
  61910. radius,
  61911. /**
  61912. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61913. */
  61914. radiusRange,
  61915. /**
  61916. * How much to randomize the particle direction [0-1].
  61917. */
  61918. directionRandomizer) {
  61919. if (radius === void 0) { radius = 1; }
  61920. if (radiusRange === void 0) { radiusRange = 1; }
  61921. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61922. this.radius = radius;
  61923. this.radiusRange = radiusRange;
  61924. this.directionRandomizer = directionRandomizer;
  61925. }
  61926. /**
  61927. * Called by the particle System when the direction is computed for the created particle.
  61928. * @param worldMatrix is the world matrix of the particle system
  61929. * @param directionToUpdate is the direction vector to update with the result
  61930. * @param particle is the particle we are computed the direction for
  61931. */
  61932. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61933. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61934. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61935. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61936. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61937. direction.x += randX;
  61938. direction.y += randY;
  61939. direction.z += randZ;
  61940. direction.normalize();
  61941. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61942. };
  61943. /**
  61944. * Called by the particle System when the position is computed for the created particle.
  61945. * @param worldMatrix is the world matrix of the particle system
  61946. * @param positionToUpdate is the position vector to update with the result
  61947. * @param particle is the particle we are computed the position for
  61948. */
  61949. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61950. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61951. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61952. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61953. var theta = Math.acos(2 * v - 1);
  61954. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61955. var randY = randRadius * Math.cos(theta);
  61956. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61957. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61958. };
  61959. /**
  61960. * Clones the current emitter and returns a copy of it
  61961. * @returns the new emitter
  61962. */
  61963. SphereParticleEmitter.prototype.clone = function () {
  61964. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61965. BABYLON.Tools.DeepCopy(this, newOne);
  61966. return newOne;
  61967. };
  61968. /**
  61969. * Called by the GPUParticleSystem to setup the update shader
  61970. * @param effect defines the update shader
  61971. */
  61972. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  61973. effect.setFloat("radius", this.radius);
  61974. effect.setFloat("radiusRange", this.radiusRange);
  61975. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61976. };
  61977. /**
  61978. * Returns a string to use to update the GPU particles update shader
  61979. * @returns a string containng the defines string
  61980. */
  61981. SphereParticleEmitter.prototype.getEffectDefines = function () {
  61982. return "#define SPHEREEMITTER";
  61983. };
  61984. /**
  61985. * Returns the string "SphereParticleEmitter"
  61986. * @returns a string containing the class name
  61987. */
  61988. SphereParticleEmitter.prototype.getClassName = function () {
  61989. return "SphereParticleEmitter";
  61990. };
  61991. /**
  61992. * Serializes the particle system to a JSON object.
  61993. * @returns the JSON object
  61994. */
  61995. SphereParticleEmitter.prototype.serialize = function () {
  61996. var serializationObject = {};
  61997. serializationObject.type = this.getClassName();
  61998. serializationObject.radius = this.radius;
  61999. serializationObject.radiusRange = this.radiusRange;
  62000. serializationObject.directionRandomizer = this.directionRandomizer;
  62001. return serializationObject;
  62002. };
  62003. /**
  62004. * Parse properties from a JSON object
  62005. * @param serializationObject defines the JSON object
  62006. */
  62007. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  62008. this.radius = serializationObject.radius;
  62009. this.radiusRange = serializationObject.radiusRange;
  62010. this.directionRandomizer = serializationObject.directionRandomizer;
  62011. };
  62012. return SphereParticleEmitter;
  62013. }());
  62014. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  62015. /**
  62016. * Particle emitter emitting particles from the inside of a sphere.
  62017. * It emits the particles randomly between two vectors.
  62018. */
  62019. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  62020. __extends(SphereDirectedParticleEmitter, _super);
  62021. /**
  62022. * Creates a new instance SphereDirectedParticleEmitter
  62023. * @param radius the radius of the emission sphere (1 by default)
  62024. * @param direction1 the min limit of the emission direction (up vector by default)
  62025. * @param direction2 the max limit of the emission direction (up vector by default)
  62026. */
  62027. function SphereDirectedParticleEmitter(radius,
  62028. /**
  62029. * The min limit of the emission direction.
  62030. */
  62031. direction1,
  62032. /**
  62033. * The max limit of the emission direction.
  62034. */
  62035. direction2) {
  62036. if (radius === void 0) { radius = 1; }
  62037. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  62038. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  62039. var _this = _super.call(this, radius) || this;
  62040. _this.direction1 = direction1;
  62041. _this.direction2 = direction2;
  62042. return _this;
  62043. }
  62044. /**
  62045. * Called by the particle System when the direction is computed for the created particle.
  62046. * @param worldMatrix is the world matrix of the particle system
  62047. * @param directionToUpdate is the direction vector to update with the result
  62048. * @param particle is the particle we are computed the direction for
  62049. */
  62050. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62051. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62052. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62053. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62054. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62055. };
  62056. /**
  62057. * Clones the current emitter and returns a copy of it
  62058. * @returns the new emitter
  62059. */
  62060. SphereDirectedParticleEmitter.prototype.clone = function () {
  62061. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  62062. BABYLON.Tools.DeepCopy(this, newOne);
  62063. return newOne;
  62064. };
  62065. /**
  62066. * Called by the GPUParticleSystem to setup the update shader
  62067. * @param effect defines the update shader
  62068. */
  62069. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  62070. effect.setFloat("radius", this.radius);
  62071. effect.setFloat("radiusRange", this.radiusRange);
  62072. effect.setVector3("direction1", this.direction1);
  62073. effect.setVector3("direction2", this.direction2);
  62074. };
  62075. /**
  62076. * Returns a string to use to update the GPU particles update shader
  62077. * @returns a string containng the defines string
  62078. */
  62079. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  62080. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  62081. };
  62082. /**
  62083. * Returns the string "SphereDirectedParticleEmitter"
  62084. * @returns a string containing the class name
  62085. */
  62086. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  62087. return "SphereDirectedParticleEmitter";
  62088. };
  62089. /**
  62090. * Serializes the particle system to a JSON object.
  62091. * @returns the JSON object
  62092. */
  62093. SphereDirectedParticleEmitter.prototype.serialize = function () {
  62094. var serializationObject = _super.prototype.serialize.call(this);
  62095. serializationObject.direction1 = this.direction1.asArray();
  62096. serializationObject.direction2 = this.direction2.asArray();
  62097. return serializationObject;
  62098. };
  62099. /**
  62100. * Parse properties from a JSON object
  62101. * @param serializationObject defines the JSON object
  62102. */
  62103. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  62104. _super.prototype.parse.call(this, serializationObject);
  62105. this.direction1.copyFrom(serializationObject.direction1);
  62106. this.direction2.copyFrom(serializationObject.direction2);
  62107. };
  62108. return SphereDirectedParticleEmitter;
  62109. }(SphereParticleEmitter));
  62110. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  62111. })(BABYLON || (BABYLON = {}));
  62112. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  62113. var BABYLON;
  62114. (function (BABYLON) {
  62115. /**
  62116. * Particle emitter emitting particles from the inside of a hemisphere.
  62117. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  62118. */
  62119. var HemisphericParticleEmitter = /** @class */ (function () {
  62120. /**
  62121. * Creates a new instance HemisphericParticleEmitter
  62122. * @param radius the radius of the emission hemisphere (1 by default)
  62123. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62124. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  62125. */
  62126. function HemisphericParticleEmitter(
  62127. /**
  62128. * The radius of the emission hemisphere.
  62129. */
  62130. radius,
  62131. /**
  62132. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  62133. */
  62134. radiusRange,
  62135. /**
  62136. * How much to randomize the particle direction [0-1].
  62137. */
  62138. directionRandomizer) {
  62139. if (radius === void 0) { radius = 1; }
  62140. if (radiusRange === void 0) { radiusRange = 1; }
  62141. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62142. this.radius = radius;
  62143. this.radiusRange = radiusRange;
  62144. this.directionRandomizer = directionRandomizer;
  62145. }
  62146. /**
  62147. * Called by the particle System when the direction is computed for the created particle.
  62148. * @param worldMatrix is the world matrix of the particle system
  62149. * @param directionToUpdate is the direction vector to update with the result
  62150. * @param particle is the particle we are computed the direction for
  62151. */
  62152. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62153. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62154. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62155. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62156. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62157. direction.x += randX;
  62158. direction.y += randY;
  62159. direction.z += randZ;
  62160. direction.normalize();
  62161. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62162. };
  62163. /**
  62164. * Called by the particle System when the position is computed for the created particle.
  62165. * @param worldMatrix is the world matrix of the particle system
  62166. * @param positionToUpdate is the position vector to update with the result
  62167. * @param particle is the particle we are computed the position for
  62168. */
  62169. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62170. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  62171. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  62172. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  62173. var theta = Math.acos(2 * v - 1);
  62174. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  62175. var randY = randRadius * Math.cos(theta);
  62176. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  62177. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  62178. };
  62179. /**
  62180. * Clones the current emitter and returns a copy of it
  62181. * @returns the new emitter
  62182. */
  62183. HemisphericParticleEmitter.prototype.clone = function () {
  62184. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  62185. BABYLON.Tools.DeepCopy(this, newOne);
  62186. return newOne;
  62187. };
  62188. /**
  62189. * Called by the GPUParticleSystem to setup the update shader
  62190. * @param effect defines the update shader
  62191. */
  62192. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  62193. effect.setFloat("radius", this.radius);
  62194. effect.setFloat("radiusRange", this.radiusRange);
  62195. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62196. };
  62197. /**
  62198. * Returns a string to use to update the GPU particles update shader
  62199. * @returns a string containng the defines string
  62200. */
  62201. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  62202. return "#define HEMISPHERICEMITTER";
  62203. };
  62204. /**
  62205. * Returns the string "HemisphericParticleEmitter"
  62206. * @returns a string containing the class name
  62207. */
  62208. HemisphericParticleEmitter.prototype.getClassName = function () {
  62209. return "HemisphericParticleEmitter";
  62210. };
  62211. /**
  62212. * Serializes the particle system to a JSON object.
  62213. * @returns the JSON object
  62214. */
  62215. HemisphericParticleEmitter.prototype.serialize = function () {
  62216. var serializationObject = {};
  62217. serializationObject.type = this.getClassName();
  62218. serializationObject.radius = this.radius;
  62219. serializationObject.radiusRange = this.radiusRange;
  62220. serializationObject.directionRandomizer = this.directionRandomizer;
  62221. return serializationObject;
  62222. };
  62223. /**
  62224. * Parse properties from a JSON object
  62225. * @param serializationObject defines the JSON object
  62226. */
  62227. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  62228. this.radius = serializationObject.radius;
  62229. this.radiusRange = serializationObject.radiusRange;
  62230. this.directionRandomizer = serializationObject.directionRandomizer;
  62231. };
  62232. return HemisphericParticleEmitter;
  62233. }());
  62234. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  62235. })(BABYLON || (BABYLON = {}));
  62236. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  62237. var BABYLON;
  62238. (function (BABYLON) {
  62239. /**
  62240. * Particle emitter emitting particles from a point.
  62241. * It emits the particles randomly between 2 given directions.
  62242. */
  62243. var PointParticleEmitter = /** @class */ (function () {
  62244. /**
  62245. * Creates a new instance PointParticleEmitter
  62246. */
  62247. function PointParticleEmitter() {
  62248. /**
  62249. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62250. */
  62251. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62252. /**
  62253. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62254. */
  62255. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62256. }
  62257. /**
  62258. * Called by the particle System when the direction is computed for the created particle.
  62259. * @param worldMatrix is the world matrix of the particle system
  62260. * @param directionToUpdate is the direction vector to update with the result
  62261. * @param particle is the particle we are computed the direction for
  62262. */
  62263. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62264. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62265. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62266. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62267. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62268. };
  62269. /**
  62270. * Called by the particle System when the position is computed for the created particle.
  62271. * @param worldMatrix is the world matrix of the particle system
  62272. * @param positionToUpdate is the position vector to update with the result
  62273. * @param particle is the particle we are computed the position for
  62274. */
  62275. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62276. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  62277. };
  62278. /**
  62279. * Clones the current emitter and returns a copy of it
  62280. * @returns the new emitter
  62281. */
  62282. PointParticleEmitter.prototype.clone = function () {
  62283. var newOne = new PointParticleEmitter();
  62284. BABYLON.Tools.DeepCopy(this, newOne);
  62285. return newOne;
  62286. };
  62287. /**
  62288. * Called by the GPUParticleSystem to setup the update shader
  62289. * @param effect defines the update shader
  62290. */
  62291. PointParticleEmitter.prototype.applyToShader = function (effect) {
  62292. effect.setVector3("direction1", this.direction1);
  62293. effect.setVector3("direction2", this.direction2);
  62294. };
  62295. /**
  62296. * Returns a string to use to update the GPU particles update shader
  62297. * @returns a string containng the defines string
  62298. */
  62299. PointParticleEmitter.prototype.getEffectDefines = function () {
  62300. return "#define POINTEMITTER";
  62301. };
  62302. /**
  62303. * Returns the string "PointParticleEmitter"
  62304. * @returns a string containing the class name
  62305. */
  62306. PointParticleEmitter.prototype.getClassName = function () {
  62307. return "PointParticleEmitter";
  62308. };
  62309. /**
  62310. * Serializes the particle system to a JSON object.
  62311. * @returns the JSON object
  62312. */
  62313. PointParticleEmitter.prototype.serialize = function () {
  62314. var serializationObject = {};
  62315. serializationObject.type = this.getClassName();
  62316. serializationObject.direction1 = this.direction1.asArray();
  62317. serializationObject.direction2 = this.direction2.asArray();
  62318. return serializationObject;
  62319. };
  62320. /**
  62321. * Parse properties from a JSON object
  62322. * @param serializationObject defines the JSON object
  62323. */
  62324. PointParticleEmitter.prototype.parse = function (serializationObject) {
  62325. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62326. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62327. };
  62328. return PointParticleEmitter;
  62329. }());
  62330. BABYLON.PointParticleEmitter = PointParticleEmitter;
  62331. })(BABYLON || (BABYLON = {}));
  62332. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  62333. var BABYLON;
  62334. (function (BABYLON) {
  62335. // Adds the parsers to the scene parsers.
  62336. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  62337. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  62338. if (!individualParser) {
  62339. return;
  62340. }
  62341. // Particles Systems
  62342. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62343. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62344. var parsedParticleSystem = parsedData.particleSystems[index];
  62345. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  62346. }
  62347. }
  62348. });
  62349. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  62350. if (parsedParticleSystem.activeParticleCount) {
  62351. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62352. return ps;
  62353. }
  62354. else {
  62355. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62356. return ps;
  62357. }
  62358. });
  62359. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  62360. if (uniformsNames === void 0) { uniformsNames = []; }
  62361. if (samplers === void 0) { samplers = []; }
  62362. if (defines === void 0) { defines = ""; }
  62363. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  62364. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  62365. if (defines.indexOf(" BILLBOARD") === -1) {
  62366. defines += "\n#define BILLBOARD\n";
  62367. }
  62368. if (samplers.indexOf("diffuseSampler") === -1) {
  62369. samplers.push("diffuseSampler");
  62370. }
  62371. return this.createEffect({
  62372. vertex: "particles",
  62373. fragmentElement: fragmentName
  62374. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  62375. };
  62376. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  62377. var results = new Array();
  62378. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62379. var particleSystem = this.getScene().particleSystems[index];
  62380. if (particleSystem.emitter === this) {
  62381. results.push(particleSystem);
  62382. }
  62383. }
  62384. return results;
  62385. };
  62386. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  62387. var results = new Array();
  62388. var descendants = this.getDescendants();
  62389. descendants.push(this);
  62390. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62391. var particleSystem = this.getScene().particleSystems[index];
  62392. var emitter = particleSystem.emitter;
  62393. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  62394. results.push(particleSystem);
  62395. }
  62396. }
  62397. return results;
  62398. };
  62399. })(BABYLON || (BABYLON = {}));
  62400. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  62401. var BABYLON;
  62402. (function (BABYLON) {
  62403. /**
  62404. * Type of sub emitter
  62405. */
  62406. var SubEmitterType;
  62407. (function (SubEmitterType) {
  62408. /**
  62409. * Attached to the particle over it's lifetime
  62410. */
  62411. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  62412. /**
  62413. * Created when the particle dies
  62414. */
  62415. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  62416. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  62417. /**
  62418. * Sub emitter class used to emit particles from an existing particle
  62419. */
  62420. var SubEmitter = /** @class */ (function () {
  62421. /**
  62422. * Creates a sub emitter
  62423. * @param particleSystem the particle system to be used by the sub emitter
  62424. */
  62425. function SubEmitter(
  62426. /**
  62427. * the particle system to be used by the sub emitter
  62428. */
  62429. particleSystem) {
  62430. this.particleSystem = particleSystem;
  62431. /**
  62432. * Type of the submitter (Default: END)
  62433. */
  62434. this.type = SubEmitterType.END;
  62435. /**
  62436. * 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)
  62437. * Note: This only is supported when using an emitter of type Mesh
  62438. */
  62439. this.inheritDirection = false;
  62440. /**
  62441. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  62442. */
  62443. this.inheritedVelocityAmount = 0;
  62444. // Create mesh as emitter to support rotation
  62445. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  62446. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  62447. }
  62448. // Automatically dispose of subemitter when system is disposed
  62449. particleSystem.onDisposeObservable.add(function () {
  62450. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  62451. particleSystem.emitter.dispose();
  62452. }
  62453. });
  62454. }
  62455. /**
  62456. * Clones the sub emitter
  62457. * @returns the cloned sub emitter
  62458. */
  62459. SubEmitter.prototype.clone = function () {
  62460. // Clone particle system
  62461. var emitter = this.particleSystem.emitter;
  62462. if (!emitter) {
  62463. emitter = new BABYLON.Vector3();
  62464. }
  62465. else if (emitter instanceof BABYLON.Vector3) {
  62466. emitter = emitter.clone();
  62467. }
  62468. else if (emitter instanceof BABYLON.AbstractMesh) {
  62469. emitter = new BABYLON.Mesh("", emitter.getScene());
  62470. emitter.isVisible = false;
  62471. }
  62472. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  62473. // Clone properties
  62474. clone.type = this.type;
  62475. clone.inheritDirection = this.inheritDirection;
  62476. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62477. clone.particleSystem._disposeEmitterOnDispose = true;
  62478. clone.particleSystem.disposeOnStop = true;
  62479. return clone;
  62480. };
  62481. /**
  62482. * Serialize current object to a JSON object
  62483. * @returns the serialized object
  62484. */
  62485. SubEmitter.prototype.serialize = function () {
  62486. var serializationObject = {};
  62487. serializationObject.type = this.type;
  62488. serializationObject.inheritDirection = this.inheritDirection;
  62489. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62490. serializationObject.particleSystem = this.particleSystem.serialize();
  62491. return serializationObject;
  62492. };
  62493. /**
  62494. * Creates a new SubEmitter from a serialized JSON version
  62495. * @param serializationObject defines the JSON object to read from
  62496. * @param scene defines the hosting scene
  62497. * @param rootUrl defines the rootUrl for data loading
  62498. * @returns a new SubEmitter
  62499. */
  62500. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  62501. var system = serializationObject.particleSystem;
  62502. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  62503. subEmitter.type = serializationObject.type;
  62504. subEmitter.inheritDirection = serializationObject.inheritDirection;
  62505. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  62506. subEmitter.particleSystem._isSubEmitter = true;
  62507. return subEmitter;
  62508. };
  62509. /** Release associated resources */
  62510. SubEmitter.prototype.dispose = function () {
  62511. this.particleSystem.dispose();
  62512. };
  62513. return SubEmitter;
  62514. }());
  62515. BABYLON.SubEmitter = SubEmitter;
  62516. })(BABYLON || (BABYLON = {}));
  62517. //# sourceMappingURL=babylon.subEmitter.js.map
  62518. var BABYLON;
  62519. (function (BABYLON) {
  62520. /**
  62521. * 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.
  62522. *
  62523. * This returned material effects how the mesh will look based on the code in the shaders.
  62524. *
  62525. * @see http://doc.babylonjs.com/how_to/shader_material
  62526. */
  62527. var ShaderMaterial = /** @class */ (function (_super) {
  62528. __extends(ShaderMaterial, _super);
  62529. /**
  62530. * Instantiate a new shader material.
  62531. * 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.
  62532. * This returned material effects how the mesh will look based on the code in the shaders.
  62533. * @see http://doc.babylonjs.com/how_to/shader_material
  62534. * @param name Define the name of the material in the scene
  62535. * @param scene Define the scene the material belongs to
  62536. * @param shaderPath Defines the route to the shader code in one of three ways:
  62537. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  62538. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  62539. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  62540. * @param options Define the options used to create the shader
  62541. */
  62542. function ShaderMaterial(name, scene, shaderPath, options) {
  62543. if (options === void 0) { options = {}; }
  62544. var _this = _super.call(this, name, scene) || this;
  62545. _this._textures = {};
  62546. _this._textureArrays = {};
  62547. _this._floats = {};
  62548. _this._ints = {};
  62549. _this._floatsArrays = {};
  62550. _this._colors3 = {};
  62551. _this._colors3Arrays = {};
  62552. _this._colors4 = {};
  62553. _this._vectors2 = {};
  62554. _this._vectors3 = {};
  62555. _this._vectors4 = {};
  62556. _this._matrices = {};
  62557. _this._matrices3x3 = {};
  62558. _this._matrices2x2 = {};
  62559. _this._vectors2Arrays = {};
  62560. _this._vectors3Arrays = {};
  62561. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  62562. _this._shaderPath = shaderPath;
  62563. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  62564. return _this;
  62565. }
  62566. /**
  62567. * Gets the current class name of the material e.g. "ShaderMaterial"
  62568. * Mainly use in serialization.
  62569. * @returns the class name
  62570. */
  62571. ShaderMaterial.prototype.getClassName = function () {
  62572. return "ShaderMaterial";
  62573. };
  62574. /**
  62575. * Specifies if the material will require alpha blending
  62576. * @returns a boolean specifying if alpha blending is needed
  62577. */
  62578. ShaderMaterial.prototype.needAlphaBlending = function () {
  62579. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  62580. };
  62581. /**
  62582. * Specifies if this material should be rendered in alpha test mode
  62583. * @returns a boolean specifying if an alpha test is needed.
  62584. */
  62585. ShaderMaterial.prototype.needAlphaTesting = function () {
  62586. return this._options.needAlphaTesting;
  62587. };
  62588. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  62589. if (this._options.uniforms.indexOf(uniformName) === -1) {
  62590. this._options.uniforms.push(uniformName);
  62591. }
  62592. };
  62593. /**
  62594. * Set a texture in the shader.
  62595. * @param name Define the name of the uniform samplers as defined in the shader
  62596. * @param texture Define the texture to bind to this sampler
  62597. * @return the material itself allowing "fluent" like uniform updates
  62598. */
  62599. ShaderMaterial.prototype.setTexture = function (name, texture) {
  62600. if (this._options.samplers.indexOf(name) === -1) {
  62601. this._options.samplers.push(name);
  62602. }
  62603. this._textures[name] = texture;
  62604. return this;
  62605. };
  62606. /**
  62607. * Set a texture array in the shader.
  62608. * @param name Define the name of the uniform sampler array as defined in the shader
  62609. * @param textures Define the list of textures to bind to this sampler
  62610. * @return the material itself allowing "fluent" like uniform updates
  62611. */
  62612. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  62613. if (this._options.samplers.indexOf(name) === -1) {
  62614. this._options.samplers.push(name);
  62615. }
  62616. this._checkUniform(name);
  62617. this._textureArrays[name] = textures;
  62618. return this;
  62619. };
  62620. /**
  62621. * Set a float in the shader.
  62622. * @param name Define the name of the uniform as defined in the shader
  62623. * @param value Define the value to give to the uniform
  62624. * @return the material itself allowing "fluent" like uniform updates
  62625. */
  62626. ShaderMaterial.prototype.setFloat = function (name, value) {
  62627. this._checkUniform(name);
  62628. this._floats[name] = value;
  62629. return this;
  62630. };
  62631. /**
  62632. * Set a int in the shader.
  62633. * @param name Define the name of the uniform as defined in the shader
  62634. * @param value Define the value to give to the uniform
  62635. * @return the material itself allowing "fluent" like uniform updates
  62636. */
  62637. ShaderMaterial.prototype.setInt = function (name, value) {
  62638. this._checkUniform(name);
  62639. this._ints[name] = value;
  62640. return this;
  62641. };
  62642. /**
  62643. * Set an array of floats in the shader.
  62644. * @param name Define the name of the uniform as defined in the shader
  62645. * @param value Define the value to give to the uniform
  62646. * @return the material itself allowing "fluent" like uniform updates
  62647. */
  62648. ShaderMaterial.prototype.setFloats = function (name, value) {
  62649. this._checkUniform(name);
  62650. this._floatsArrays[name] = value;
  62651. return this;
  62652. };
  62653. /**
  62654. * Set a vec3 in the shader from a Color3.
  62655. * @param name Define the name of the uniform as defined in the shader
  62656. * @param value Define the value to give to the uniform
  62657. * @return the material itself allowing "fluent" like uniform updates
  62658. */
  62659. ShaderMaterial.prototype.setColor3 = function (name, value) {
  62660. this._checkUniform(name);
  62661. this._colors3[name] = value;
  62662. return this;
  62663. };
  62664. /**
  62665. * Set a vec3 array in the shader from a Color3 array.
  62666. * @param name Define the name of the uniform as defined in the shader
  62667. * @param value Define the value to give to the uniform
  62668. * @return the material itself allowing "fluent" like uniform updates
  62669. */
  62670. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  62671. this._checkUniform(name);
  62672. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  62673. color.toArray(arr, arr.length);
  62674. return arr;
  62675. }, []);
  62676. return this;
  62677. };
  62678. /**
  62679. * Set a vec4 in the shader from a Color4.
  62680. * @param name Define the name of the uniform as defined in the shader
  62681. * @param value Define the value to give to the uniform
  62682. * @return the material itself allowing "fluent" like uniform updates
  62683. */
  62684. ShaderMaterial.prototype.setColor4 = function (name, value) {
  62685. this._checkUniform(name);
  62686. this._colors4[name] = value;
  62687. return this;
  62688. };
  62689. /**
  62690. * Set a vec2 in the shader from a Vector2.
  62691. * @param name Define the name of the uniform as defined in the shader
  62692. * @param value Define the value to give to the uniform
  62693. * @return the material itself allowing "fluent" like uniform updates
  62694. */
  62695. ShaderMaterial.prototype.setVector2 = function (name, value) {
  62696. this._checkUniform(name);
  62697. this._vectors2[name] = value;
  62698. return this;
  62699. };
  62700. /**
  62701. * Set a vec3 in the shader from a Vector3.
  62702. * @param name Define the name of the uniform as defined in the shader
  62703. * @param value Define the value to give to the uniform
  62704. * @return the material itself allowing "fluent" like uniform updates
  62705. */
  62706. ShaderMaterial.prototype.setVector3 = function (name, value) {
  62707. this._checkUniform(name);
  62708. this._vectors3[name] = value;
  62709. return this;
  62710. };
  62711. /**
  62712. * Set a vec4 in the shader from a Vector4.
  62713. * @param name Define the name of the uniform as defined in the shader
  62714. * @param value Define the value to give to the uniform
  62715. * @return the material itself allowing "fluent" like uniform updates
  62716. */
  62717. ShaderMaterial.prototype.setVector4 = function (name, value) {
  62718. this._checkUniform(name);
  62719. this._vectors4[name] = value;
  62720. return this;
  62721. };
  62722. /**
  62723. * Set a mat4 in the shader from a Matrix.
  62724. * @param name Define the name of the uniform as defined in the shader
  62725. * @param value Define the value to give to the uniform
  62726. * @return the material itself allowing "fluent" like uniform updates
  62727. */
  62728. ShaderMaterial.prototype.setMatrix = function (name, value) {
  62729. this._checkUniform(name);
  62730. this._matrices[name] = value;
  62731. return this;
  62732. };
  62733. /**
  62734. * Set a mat3 in the shader from a Float32Array.
  62735. * @param name Define the name of the uniform as defined in the shader
  62736. * @param value Define the value to give to the uniform
  62737. * @return the material itself allowing "fluent" like uniform updates
  62738. */
  62739. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  62740. this._checkUniform(name);
  62741. this._matrices3x3[name] = value;
  62742. return this;
  62743. };
  62744. /**
  62745. * Set a mat2 in the shader from a Float32Array.
  62746. * @param name Define the name of the uniform as defined in the shader
  62747. * @param value Define the value to give to the uniform
  62748. * @return the material itself allowing "fluent" like uniform updates
  62749. */
  62750. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  62751. this._checkUniform(name);
  62752. this._matrices2x2[name] = value;
  62753. return this;
  62754. };
  62755. /**
  62756. * Set a vec2 array in the shader from a number array.
  62757. * @param name Define the name of the uniform as defined in the shader
  62758. * @param value Define the value to give to the uniform
  62759. * @return the material itself allowing "fluent" like uniform updates
  62760. */
  62761. ShaderMaterial.prototype.setArray2 = function (name, value) {
  62762. this._checkUniform(name);
  62763. this._vectors2Arrays[name] = value;
  62764. return this;
  62765. };
  62766. /**
  62767. * Set a vec3 array in the shader from a number array.
  62768. * @param name Define the name of the uniform as defined in the shader
  62769. * @param value Define the value to give to the uniform
  62770. * @return the material itself allowing "fluent" like uniform updates
  62771. */
  62772. ShaderMaterial.prototype.setArray3 = function (name, value) {
  62773. this._checkUniform(name);
  62774. this._vectors3Arrays[name] = value;
  62775. return this;
  62776. };
  62777. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  62778. if (!mesh) {
  62779. return true;
  62780. }
  62781. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  62782. return false;
  62783. }
  62784. return false;
  62785. };
  62786. /**
  62787. * Checks if the material is ready to render the requested mesh
  62788. * @param mesh Define the mesh to render
  62789. * @param useInstances Define whether or not the material is used with instances
  62790. * @returns true if ready, otherwise false
  62791. */
  62792. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  62793. var scene = this.getScene();
  62794. var engine = scene.getEngine();
  62795. if (!this.checkReadyOnEveryCall) {
  62796. if (this._renderId === scene.getRenderId()) {
  62797. if (this._checkCache(scene, mesh, useInstances)) {
  62798. return true;
  62799. }
  62800. }
  62801. }
  62802. // Instances
  62803. var defines = [];
  62804. var attribs = [];
  62805. var fallbacks = new BABYLON.EffectFallbacks();
  62806. for (var index = 0; index < this._options.defines.length; index++) {
  62807. defines.push(this._options.defines[index]);
  62808. }
  62809. for (var index = 0; index < this._options.attributes.length; index++) {
  62810. attribs.push(this._options.attributes[index]);
  62811. }
  62812. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  62813. attribs.push(BABYLON.VertexBuffer.ColorKind);
  62814. defines.push("#define VERTEXCOLOR");
  62815. }
  62816. if (useInstances) {
  62817. defines.push("#define INSTANCES");
  62818. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  62819. }
  62820. // Bones
  62821. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62822. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62823. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62824. if (mesh.numBoneInfluencers > 4) {
  62825. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62826. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62827. }
  62828. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62829. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62830. fallbacks.addCPUSkinningFallback(0, mesh);
  62831. if (this._options.uniforms.indexOf("mBones") === -1) {
  62832. this._options.uniforms.push("mBones");
  62833. }
  62834. }
  62835. else {
  62836. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62837. }
  62838. // Textures
  62839. for (var name in this._textures) {
  62840. if (!this._textures[name].isReady()) {
  62841. return false;
  62842. }
  62843. }
  62844. // Alpha test
  62845. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  62846. defines.push("#define ALPHATEST");
  62847. }
  62848. var previousEffect = this._effect;
  62849. var join = defines.join("\n");
  62850. this._effect = engine.createEffect(this._shaderPath, {
  62851. attributes: attribs,
  62852. uniformsNames: this._options.uniforms,
  62853. uniformBuffersNames: this._options.uniformBuffers,
  62854. samplers: this._options.samplers,
  62855. defines: join,
  62856. fallbacks: fallbacks,
  62857. onCompiled: this.onCompiled,
  62858. onError: this.onError
  62859. }, engine);
  62860. if (!this._effect.isReady()) {
  62861. return false;
  62862. }
  62863. if (previousEffect !== this._effect) {
  62864. scene.resetCachedMaterial();
  62865. }
  62866. this._renderId = scene.getRenderId();
  62867. return true;
  62868. };
  62869. /**
  62870. * Binds the world matrix to the material
  62871. * @param world defines the world transformation matrix
  62872. */
  62873. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62874. var scene = this.getScene();
  62875. if (!this._effect) {
  62876. return;
  62877. }
  62878. if (this._options.uniforms.indexOf("world") !== -1) {
  62879. this._effect.setMatrix("world", world);
  62880. }
  62881. if (this._options.uniforms.indexOf("worldView") !== -1) {
  62882. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  62883. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  62884. }
  62885. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  62886. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  62887. }
  62888. };
  62889. /**
  62890. * Binds the material to the mesh
  62891. * @param world defines the world transformation matrix
  62892. * @param mesh defines the mesh to bind the material to
  62893. */
  62894. ShaderMaterial.prototype.bind = function (world, mesh) {
  62895. // Std values
  62896. this.bindOnlyWorldMatrix(world);
  62897. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  62898. if (this._options.uniforms.indexOf("view") !== -1) {
  62899. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  62900. }
  62901. if (this._options.uniforms.indexOf("projection") !== -1) {
  62902. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  62903. }
  62904. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  62905. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  62906. }
  62907. // Bones
  62908. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62909. var name;
  62910. // Texture
  62911. for (name in this._textures) {
  62912. this._effect.setTexture(name, this._textures[name]);
  62913. }
  62914. // Texture arrays
  62915. for (name in this._textureArrays) {
  62916. this._effect.setTextureArray(name, this._textureArrays[name]);
  62917. }
  62918. // Int
  62919. for (name in this._ints) {
  62920. this._effect.setInt(name, this._ints[name]);
  62921. }
  62922. // Float
  62923. for (name in this._floats) {
  62924. this._effect.setFloat(name, this._floats[name]);
  62925. }
  62926. // Floats
  62927. for (name in this._floatsArrays) {
  62928. this._effect.setArray(name, this._floatsArrays[name]);
  62929. }
  62930. // Color3
  62931. for (name in this._colors3) {
  62932. this._effect.setColor3(name, this._colors3[name]);
  62933. }
  62934. for (name in this._colors3Arrays) {
  62935. this._effect.setArray3(name, this._colors3Arrays[name]);
  62936. }
  62937. // Color4
  62938. for (name in this._colors4) {
  62939. var color = this._colors4[name];
  62940. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62941. }
  62942. // Vector2
  62943. for (name in this._vectors2) {
  62944. this._effect.setVector2(name, this._vectors2[name]);
  62945. }
  62946. // Vector3
  62947. for (name in this._vectors3) {
  62948. this._effect.setVector3(name, this._vectors3[name]);
  62949. }
  62950. // Vector4
  62951. for (name in this._vectors4) {
  62952. this._effect.setVector4(name, this._vectors4[name]);
  62953. }
  62954. // Matrix
  62955. for (name in this._matrices) {
  62956. this._effect.setMatrix(name, this._matrices[name]);
  62957. }
  62958. // Matrix 3x3
  62959. for (name in this._matrices3x3) {
  62960. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62961. }
  62962. // Matrix 2x2
  62963. for (name in this._matrices2x2) {
  62964. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62965. }
  62966. // Vector2Array
  62967. for (name in this._vectors2Arrays) {
  62968. this._effect.setArray2(name, this._vectors2Arrays[name]);
  62969. }
  62970. // Vector3Array
  62971. for (name in this._vectors3Arrays) {
  62972. this._effect.setArray3(name, this._vectors3Arrays[name]);
  62973. }
  62974. }
  62975. this._afterBind(mesh);
  62976. };
  62977. /**
  62978. * Gets the active textures from the material
  62979. * @returns an array of textures
  62980. */
  62981. ShaderMaterial.prototype.getActiveTextures = function () {
  62982. var activeTextures = _super.prototype.getActiveTextures.call(this);
  62983. for (var name in this._textures) {
  62984. activeTextures.push(this._textures[name]);
  62985. }
  62986. for (var name in this._textureArrays) {
  62987. var array = this._textureArrays[name];
  62988. for (var index = 0; index < array.length; index++) {
  62989. activeTextures.push(array[index]);
  62990. }
  62991. }
  62992. return activeTextures;
  62993. };
  62994. /**
  62995. * Specifies if the material uses a texture
  62996. * @param texture defines the texture to check against the material
  62997. * @returns a boolean specifying if the material uses the texture
  62998. */
  62999. ShaderMaterial.prototype.hasTexture = function (texture) {
  63000. if (_super.prototype.hasTexture.call(this, texture)) {
  63001. return true;
  63002. }
  63003. for (var name in this._textures) {
  63004. if (this._textures[name] === texture) {
  63005. return true;
  63006. }
  63007. }
  63008. for (var name in this._textureArrays) {
  63009. var array = this._textureArrays[name];
  63010. for (var index = 0; index < array.length; index++) {
  63011. if (array[index] === texture) {
  63012. return true;
  63013. }
  63014. }
  63015. }
  63016. return false;
  63017. };
  63018. /**
  63019. * Makes a duplicate of the material, and gives it a new name
  63020. * @param name defines the new name for the duplicated material
  63021. * @returns the cloned material
  63022. */
  63023. ShaderMaterial.prototype.clone = function (name) {
  63024. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  63025. return newShaderMaterial;
  63026. };
  63027. /**
  63028. * Disposes the material
  63029. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  63030. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  63031. */
  63032. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63033. if (forceDisposeTextures) {
  63034. var name;
  63035. for (name in this._textures) {
  63036. this._textures[name].dispose();
  63037. }
  63038. for (name in this._textureArrays) {
  63039. var array = this._textureArrays[name];
  63040. for (var index = 0; index < array.length; index++) {
  63041. array[index].dispose();
  63042. }
  63043. }
  63044. }
  63045. this._textures = {};
  63046. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63047. };
  63048. /**
  63049. * Serializes this material in a JSON representation
  63050. * @returns the serialized material object
  63051. */
  63052. ShaderMaterial.prototype.serialize = function () {
  63053. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63054. serializationObject.customType = "BABYLON.ShaderMaterial";
  63055. serializationObject.options = this._options;
  63056. serializationObject.shaderPath = this._shaderPath;
  63057. var name;
  63058. // Texture
  63059. serializationObject.textures = {};
  63060. for (name in this._textures) {
  63061. serializationObject.textures[name] = this._textures[name].serialize();
  63062. }
  63063. // Texture arrays
  63064. serializationObject.textureArrays = {};
  63065. for (name in this._textureArrays) {
  63066. serializationObject.textureArrays[name] = [];
  63067. var array = this._textureArrays[name];
  63068. for (var index = 0; index < array.length; index++) {
  63069. serializationObject.textureArrays[name].push(array[index].serialize());
  63070. }
  63071. }
  63072. // Float
  63073. serializationObject.floats = {};
  63074. for (name in this._floats) {
  63075. serializationObject.floats[name] = this._floats[name];
  63076. }
  63077. // Float s
  63078. serializationObject.FloatArrays = {};
  63079. for (name in this._floatsArrays) {
  63080. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  63081. }
  63082. // Color3
  63083. serializationObject.colors3 = {};
  63084. for (name in this._colors3) {
  63085. serializationObject.colors3[name] = this._colors3[name].asArray();
  63086. }
  63087. // Color3 array
  63088. serializationObject.colors3Arrays = {};
  63089. for (name in this._colors3Arrays) {
  63090. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  63091. }
  63092. // Color4
  63093. serializationObject.colors4 = {};
  63094. for (name in this._colors4) {
  63095. serializationObject.colors4[name] = this._colors4[name].asArray();
  63096. }
  63097. // Vector2
  63098. serializationObject.vectors2 = {};
  63099. for (name in this._vectors2) {
  63100. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  63101. }
  63102. // Vector3
  63103. serializationObject.vectors3 = {};
  63104. for (name in this._vectors3) {
  63105. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  63106. }
  63107. // Vector4
  63108. serializationObject.vectors4 = {};
  63109. for (name in this._vectors4) {
  63110. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  63111. }
  63112. // Matrix
  63113. serializationObject.matrices = {};
  63114. for (name in this._matrices) {
  63115. serializationObject.matrices[name] = this._matrices[name].asArray();
  63116. }
  63117. // Matrix 3x3
  63118. serializationObject.matrices3x3 = {};
  63119. for (name in this._matrices3x3) {
  63120. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  63121. }
  63122. // Matrix 2x2
  63123. serializationObject.matrices2x2 = {};
  63124. for (name in this._matrices2x2) {
  63125. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  63126. }
  63127. // Vector2Array
  63128. serializationObject.vectors2Arrays = {};
  63129. for (name in this._vectors2Arrays) {
  63130. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  63131. }
  63132. // Vector3Array
  63133. serializationObject.vectors3Arrays = {};
  63134. for (name in this._vectors3Arrays) {
  63135. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  63136. }
  63137. return serializationObject;
  63138. };
  63139. /**
  63140. * Creates a shader material from parsed shader material data
  63141. * @param source defines the JSON represnetation of the material
  63142. * @param scene defines the hosting scene
  63143. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  63144. * @returns a new material
  63145. */
  63146. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  63147. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  63148. var name;
  63149. // Texture
  63150. for (name in source.textures) {
  63151. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  63152. }
  63153. // Texture arrays
  63154. for (name in source.textureArrays) {
  63155. var array = source.textureArrays[name];
  63156. var textureArray = new Array();
  63157. for (var index = 0; index < array.length; index++) {
  63158. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  63159. }
  63160. material.setTextureArray(name, textureArray);
  63161. }
  63162. // Float
  63163. for (name in source.floats) {
  63164. material.setFloat(name, source.floats[name]);
  63165. }
  63166. // Float s
  63167. for (name in source.floatsArrays) {
  63168. material.setFloats(name, source.floatsArrays[name]);
  63169. }
  63170. // Color3
  63171. for (name in source.colors3) {
  63172. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  63173. }
  63174. // Color3 arrays
  63175. for (name in source.colors3Arrays) {
  63176. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  63177. if (i % 3 === 0) {
  63178. arr.push([num]);
  63179. }
  63180. else {
  63181. arr[arr.length - 1].push(num);
  63182. }
  63183. return arr;
  63184. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  63185. material.setColor3Array(name, colors);
  63186. }
  63187. // Color4
  63188. for (name in source.colors4) {
  63189. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  63190. }
  63191. // Vector2
  63192. for (name in source.vectors2) {
  63193. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  63194. }
  63195. // Vector3
  63196. for (name in source.vectors3) {
  63197. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  63198. }
  63199. // Vector4
  63200. for (name in source.vectors4) {
  63201. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  63202. }
  63203. // Matrix
  63204. for (name in source.matrices) {
  63205. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  63206. }
  63207. // Matrix 3x3
  63208. for (name in source.matrices3x3) {
  63209. material.setMatrix3x3(name, source.matrices3x3[name]);
  63210. }
  63211. // Matrix 2x2
  63212. for (name in source.matrices2x2) {
  63213. material.setMatrix2x2(name, source.matrices2x2[name]);
  63214. }
  63215. // Vector2Array
  63216. for (name in source.vectors2Arrays) {
  63217. material.setArray2(name, source.vectors2Arrays[name]);
  63218. }
  63219. // Vector3Array
  63220. for (name in source.vectors3Arrays) {
  63221. material.setArray3(name, source.vectors3Arrays[name]);
  63222. }
  63223. return material;
  63224. };
  63225. return ShaderMaterial;
  63226. }(BABYLON.Material));
  63227. BABYLON.ShaderMaterial = ShaderMaterial;
  63228. })(BABYLON || (BABYLON = {}));
  63229. //# sourceMappingURL=babylon.shaderMaterial.js.map
  63230. var BABYLON;
  63231. (function (BABYLON) {
  63232. /**
  63233. * Mesh representing the gorund
  63234. */
  63235. var GroundMesh = /** @class */ (function (_super) {
  63236. __extends(GroundMesh, _super);
  63237. function GroundMesh(name, scene) {
  63238. var _this = _super.call(this, name, scene) || this;
  63239. /** If octree should be generated */
  63240. _this.generateOctree = false;
  63241. return _this;
  63242. }
  63243. /**
  63244. * "GroundMesh"
  63245. * @returns "GroundMesh"
  63246. */
  63247. GroundMesh.prototype.getClassName = function () {
  63248. return "GroundMesh";
  63249. };
  63250. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  63251. /**
  63252. * The minimum of x and y subdivisions
  63253. */
  63254. get: function () {
  63255. return Math.min(this._subdivisionsX, this._subdivisionsY);
  63256. },
  63257. enumerable: true,
  63258. configurable: true
  63259. });
  63260. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  63261. /**
  63262. * X subdivisions
  63263. */
  63264. get: function () {
  63265. return this._subdivisionsX;
  63266. },
  63267. enumerable: true,
  63268. configurable: true
  63269. });
  63270. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  63271. /**
  63272. * Y subdivisions
  63273. */
  63274. get: function () {
  63275. return this._subdivisionsY;
  63276. },
  63277. enumerable: true,
  63278. configurable: true
  63279. });
  63280. /**
  63281. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  63282. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  63283. * @param chunksCount the number of subdivisions for x and y
  63284. * @param octreeBlocksSize (Default: 32)
  63285. */
  63286. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  63287. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  63288. this._subdivisionsX = chunksCount;
  63289. this._subdivisionsY = chunksCount;
  63290. this.subdivide(chunksCount);
  63291. // Call the octree system optimization if it is defined.
  63292. var thisAsAny = this;
  63293. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  63294. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  63295. }
  63296. };
  63297. /**
  63298. * Returns a height (y) value in the Worl system :
  63299. * the ground altitude at the coordinates (x, z) expressed in the World system.
  63300. * @param x x coordinate
  63301. * @param z z coordinate
  63302. * @returns the ground y position if (x, z) are outside the ground surface.
  63303. */
  63304. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  63305. var world = this.getWorldMatrix();
  63306. var invMat = BABYLON.Tmp.Matrix[5];
  63307. world.invertToRef(invMat);
  63308. var tmpVect = BABYLON.Tmp.Vector3[8];
  63309. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  63310. x = tmpVect.x;
  63311. z = tmpVect.z;
  63312. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63313. return this.position.y;
  63314. }
  63315. if (!this._heightQuads || this._heightQuads.length == 0) {
  63316. this._initHeightQuads();
  63317. this._computeHeightQuads();
  63318. }
  63319. var facet = this._getFacetAt(x, z);
  63320. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  63321. // return y in the World system
  63322. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  63323. return tmpVect.y;
  63324. };
  63325. /**
  63326. * Returns a normalized vector (Vector3) orthogonal to the ground
  63327. * at the ground coordinates (x, z) expressed in the World system.
  63328. * @param x x coordinate
  63329. * @param z z coordinate
  63330. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  63331. */
  63332. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  63333. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  63334. this.getNormalAtCoordinatesToRef(x, z, normal);
  63335. return normal;
  63336. };
  63337. /**
  63338. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  63339. * at the ground coordinates (x, z) expressed in the World system.
  63340. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  63341. * @param x x coordinate
  63342. * @param z z coordinate
  63343. * @param ref vector to store the result
  63344. * @returns the GroundMesh.
  63345. */
  63346. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  63347. var world = this.getWorldMatrix();
  63348. var tmpMat = BABYLON.Tmp.Matrix[5];
  63349. world.invertToRef(tmpMat);
  63350. var tmpVect = BABYLON.Tmp.Vector3[8];
  63351. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  63352. x = tmpVect.x;
  63353. z = tmpVect.z;
  63354. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63355. return this;
  63356. }
  63357. if (!this._heightQuads || this._heightQuads.length == 0) {
  63358. this._initHeightQuads();
  63359. this._computeHeightQuads();
  63360. }
  63361. var facet = this._getFacetAt(x, z);
  63362. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  63363. return this;
  63364. };
  63365. /**
  63366. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  63367. * if the ground has been updated.
  63368. * This can be used in the render loop.
  63369. * @returns the GroundMesh.
  63370. */
  63371. GroundMesh.prototype.updateCoordinateHeights = function () {
  63372. if (!this._heightQuads || this._heightQuads.length == 0) {
  63373. this._initHeightQuads();
  63374. }
  63375. this._computeHeightQuads();
  63376. return this;
  63377. };
  63378. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  63379. GroundMesh.prototype._getFacetAt = function (x, z) {
  63380. // retrieve col and row from x, z coordinates in the ground local system
  63381. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  63382. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  63383. var quad = this._heightQuads[row * this._subdivisionsX + col];
  63384. var facet;
  63385. if (z < quad.slope.x * x + quad.slope.y) {
  63386. facet = quad.facet1;
  63387. }
  63388. else {
  63389. facet = quad.facet2;
  63390. }
  63391. return facet;
  63392. };
  63393. // Creates and populates the heightMap array with "facet" elements :
  63394. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  63395. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63396. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63397. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63398. // Returns the GroundMesh.
  63399. GroundMesh.prototype._initHeightQuads = function () {
  63400. var subdivisionsX = this._subdivisionsX;
  63401. var subdivisionsY = this._subdivisionsY;
  63402. this._heightQuads = new Array();
  63403. for (var row = 0; row < subdivisionsY; row++) {
  63404. for (var col = 0; col < subdivisionsX; col++) {
  63405. 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) };
  63406. this._heightQuads[row * subdivisionsX + col] = quad;
  63407. }
  63408. }
  63409. return this;
  63410. };
  63411. // Compute each quad element values and update the the heightMap array :
  63412. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63413. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63414. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63415. // Returns the GroundMesh.
  63416. GroundMesh.prototype._computeHeightQuads = function () {
  63417. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63418. if (!positions) {
  63419. return this;
  63420. }
  63421. var v1 = BABYLON.Tmp.Vector3[3];
  63422. var v2 = BABYLON.Tmp.Vector3[2];
  63423. var v3 = BABYLON.Tmp.Vector3[1];
  63424. var v4 = BABYLON.Tmp.Vector3[0];
  63425. var v1v2 = BABYLON.Tmp.Vector3[4];
  63426. var v1v3 = BABYLON.Tmp.Vector3[5];
  63427. var v1v4 = BABYLON.Tmp.Vector3[6];
  63428. var norm1 = BABYLON.Tmp.Vector3[7];
  63429. var norm2 = BABYLON.Tmp.Vector3[8];
  63430. var i = 0;
  63431. var j = 0;
  63432. var k = 0;
  63433. var cd = 0; // 2D slope coefficient : z = cd * x + h
  63434. var h = 0;
  63435. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  63436. var d2 = 0;
  63437. var subdivisionsX = this._subdivisionsX;
  63438. var subdivisionsY = this._subdivisionsY;
  63439. for (var row = 0; row < subdivisionsY; row++) {
  63440. for (var col = 0; col < subdivisionsX; col++) {
  63441. i = col * 3;
  63442. j = row * (subdivisionsX + 1) * 3;
  63443. k = (row + 1) * (subdivisionsX + 1) * 3;
  63444. v1.x = positions[j + i];
  63445. v1.y = positions[j + i + 1];
  63446. v1.z = positions[j + i + 2];
  63447. v2.x = positions[j + i + 3];
  63448. v2.y = positions[j + i + 4];
  63449. v2.z = positions[j + i + 5];
  63450. v3.x = positions[k + i];
  63451. v3.y = positions[k + i + 1];
  63452. v3.z = positions[k + i + 2];
  63453. v4.x = positions[k + i + 3];
  63454. v4.y = positions[k + i + 4];
  63455. v4.z = positions[k + i + 5];
  63456. // 2D slope V1V4
  63457. cd = (v4.z - v1.z) / (v4.x - v1.x);
  63458. h = v1.z - cd * v1.x; // v1 belongs to the slope
  63459. // facet equations :
  63460. // we compute each facet normal vector
  63461. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  63462. // we compute the value d by applying the equation to v1 which belongs to the plane
  63463. // then we store the facet equation in a Vector4
  63464. v2.subtractToRef(v1, v1v2);
  63465. v3.subtractToRef(v1, v1v3);
  63466. v4.subtractToRef(v1, v1v4);
  63467. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  63468. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  63469. norm1.normalize();
  63470. norm2.normalize();
  63471. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  63472. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  63473. var quad = this._heightQuads[row * subdivisionsX + col];
  63474. quad.slope.copyFromFloats(cd, h);
  63475. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  63476. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  63477. }
  63478. }
  63479. return this;
  63480. };
  63481. /**
  63482. * Serializes this ground mesh
  63483. * @param serializationObject object to write serialization to
  63484. */
  63485. GroundMesh.prototype.serialize = function (serializationObject) {
  63486. _super.prototype.serialize.call(this, serializationObject);
  63487. serializationObject.subdivisionsX = this._subdivisionsX;
  63488. serializationObject.subdivisionsY = this._subdivisionsY;
  63489. serializationObject.minX = this._minX;
  63490. serializationObject.maxX = this._maxX;
  63491. serializationObject.minZ = this._minZ;
  63492. serializationObject.maxZ = this._maxZ;
  63493. serializationObject.width = this._width;
  63494. serializationObject.height = this._height;
  63495. };
  63496. /**
  63497. * Parses a serialized ground mesh
  63498. * @param parsedMesh the serialized mesh
  63499. * @param scene the scene to create the ground mesh in
  63500. * @returns the created ground mesh
  63501. */
  63502. GroundMesh.Parse = function (parsedMesh, scene) {
  63503. var result = new GroundMesh(parsedMesh.name, scene);
  63504. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  63505. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  63506. result._minX = parsedMesh.minX;
  63507. result._maxX = parsedMesh.maxX;
  63508. result._minZ = parsedMesh.minZ;
  63509. result._maxZ = parsedMesh.maxZ;
  63510. result._width = parsedMesh.width;
  63511. result._height = parsedMesh.height;
  63512. return result;
  63513. };
  63514. return GroundMesh;
  63515. }(BABYLON.Mesh));
  63516. BABYLON.GroundMesh = GroundMesh;
  63517. })(BABYLON || (BABYLON = {}));
  63518. //# sourceMappingURL=babylon.groundMesh.js.map
  63519. var BABYLON;
  63520. (function (BABYLON) {
  63521. /**
  63522. * Creates an instance based on a source mesh.
  63523. */
  63524. var InstancedMesh = /** @class */ (function (_super) {
  63525. __extends(InstancedMesh, _super);
  63526. function InstancedMesh(name, source) {
  63527. var _this = _super.call(this, name, source.getScene()) || this;
  63528. source.instances.push(_this);
  63529. _this._sourceMesh = source;
  63530. _this.position.copyFrom(source.position);
  63531. _this.rotation.copyFrom(source.rotation);
  63532. _this.scaling.copyFrom(source.scaling);
  63533. if (source.rotationQuaternion) {
  63534. _this.rotationQuaternion = source.rotationQuaternion.clone();
  63535. }
  63536. _this.infiniteDistance = source.infiniteDistance;
  63537. _this.setPivotMatrix(source.getPivotMatrix());
  63538. _this.refreshBoundingInfo();
  63539. _this._syncSubMeshes();
  63540. return _this;
  63541. }
  63542. /**
  63543. * Returns the string "InstancedMesh".
  63544. */
  63545. InstancedMesh.prototype.getClassName = function () {
  63546. return "InstancedMesh";
  63547. };
  63548. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  63549. // Methods
  63550. /**
  63551. * If the source mesh receives shadows
  63552. */
  63553. get: function () {
  63554. return this._sourceMesh.receiveShadows;
  63555. },
  63556. enumerable: true,
  63557. configurable: true
  63558. });
  63559. Object.defineProperty(InstancedMesh.prototype, "material", {
  63560. /**
  63561. * The material of the source mesh
  63562. */
  63563. get: function () {
  63564. return this._sourceMesh.material;
  63565. },
  63566. enumerable: true,
  63567. configurable: true
  63568. });
  63569. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  63570. /**
  63571. * Visibility of the source mesh
  63572. */
  63573. get: function () {
  63574. return this._sourceMesh.visibility;
  63575. },
  63576. enumerable: true,
  63577. configurable: true
  63578. });
  63579. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  63580. /**
  63581. * Skeleton of the source mesh
  63582. */
  63583. get: function () {
  63584. return this._sourceMesh.skeleton;
  63585. },
  63586. enumerable: true,
  63587. configurable: true
  63588. });
  63589. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  63590. /**
  63591. * Rendering ground id of the source mesh
  63592. */
  63593. get: function () {
  63594. return this._sourceMesh.renderingGroupId;
  63595. },
  63596. set: function (value) {
  63597. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  63598. return;
  63599. }
  63600. //no-op with warning
  63601. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  63602. },
  63603. enumerable: true,
  63604. configurable: true
  63605. });
  63606. /**
  63607. * Returns the total number of vertices (integer).
  63608. */
  63609. InstancedMesh.prototype.getTotalVertices = function () {
  63610. return this._sourceMesh.getTotalVertices();
  63611. };
  63612. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  63613. /**
  63614. * The source mesh of the instance
  63615. */
  63616. get: function () {
  63617. return this._sourceMesh;
  63618. },
  63619. enumerable: true,
  63620. configurable: true
  63621. });
  63622. /**
  63623. * Is this node ready to be used/rendered
  63624. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  63625. * @return {boolean} is it ready
  63626. */
  63627. InstancedMesh.prototype.isReady = function (completeCheck) {
  63628. if (completeCheck === void 0) { completeCheck = false; }
  63629. return this._sourceMesh.isReady(completeCheck, true);
  63630. };
  63631. /**
  63632. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  63633. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  63634. * @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.
  63635. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  63636. */
  63637. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  63638. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  63639. };
  63640. /**
  63641. * Sets the vertex data of the mesh geometry for the requested `kind`.
  63642. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  63643. * The `data` are either a numeric array either a Float32Array.
  63644. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  63645. * 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).
  63646. * Note that a new underlying VertexBuffer object is created each call.
  63647. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  63648. *
  63649. * Possible `kind` values :
  63650. * - BABYLON.VertexBuffer.PositionKind
  63651. * - BABYLON.VertexBuffer.UVKind
  63652. * - BABYLON.VertexBuffer.UV2Kind
  63653. * - BABYLON.VertexBuffer.UV3Kind
  63654. * - BABYLON.VertexBuffer.UV4Kind
  63655. * - BABYLON.VertexBuffer.UV5Kind
  63656. * - BABYLON.VertexBuffer.UV6Kind
  63657. * - BABYLON.VertexBuffer.ColorKind
  63658. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63659. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63660. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63661. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63662. *
  63663. * Returns the Mesh.
  63664. */
  63665. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  63666. if (this.sourceMesh) {
  63667. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  63668. }
  63669. return this.sourceMesh;
  63670. };
  63671. /**
  63672. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  63673. * If the mesh has no geometry, it is simply returned as it is.
  63674. * The `data` are either a numeric array either a Float32Array.
  63675. * No new underlying VertexBuffer object is created.
  63676. * 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.
  63677. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  63678. *
  63679. * Possible `kind` values :
  63680. * - BABYLON.VertexBuffer.PositionKind
  63681. * - BABYLON.VertexBuffer.UVKind
  63682. * - BABYLON.VertexBuffer.UV2Kind
  63683. * - BABYLON.VertexBuffer.UV3Kind
  63684. * - BABYLON.VertexBuffer.UV4Kind
  63685. * - BABYLON.VertexBuffer.UV5Kind
  63686. * - BABYLON.VertexBuffer.UV6Kind
  63687. * - BABYLON.VertexBuffer.ColorKind
  63688. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63689. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63690. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63691. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63692. *
  63693. * Returns the Mesh.
  63694. */
  63695. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  63696. if (this.sourceMesh) {
  63697. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  63698. }
  63699. return this.sourceMesh;
  63700. };
  63701. /**
  63702. * Sets the mesh indices.
  63703. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  63704. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  63705. * This method creates a new index buffer each call.
  63706. * Returns the Mesh.
  63707. */
  63708. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  63709. if (totalVertices === void 0) { totalVertices = null; }
  63710. if (this.sourceMesh) {
  63711. this.sourceMesh.setIndices(indices, totalVertices);
  63712. }
  63713. return this.sourceMesh;
  63714. };
  63715. /**
  63716. * Boolean : True if the mesh owns the requested kind of data.
  63717. */
  63718. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  63719. return this._sourceMesh.isVerticesDataPresent(kind);
  63720. };
  63721. /**
  63722. * Returns an array of indices (IndicesArray).
  63723. */
  63724. InstancedMesh.prototype.getIndices = function () {
  63725. return this._sourceMesh.getIndices();
  63726. };
  63727. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  63728. get: function () {
  63729. return this._sourceMesh._positions;
  63730. },
  63731. enumerable: true,
  63732. configurable: true
  63733. });
  63734. /**
  63735. * Sets a new updated BoundingInfo to the mesh.
  63736. * @returns the mesh.
  63737. */
  63738. InstancedMesh.prototype.refreshBoundingInfo = function () {
  63739. var meshBB = this._sourceMesh.getBoundingInfo();
  63740. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  63741. this._updateBoundingInfo();
  63742. return this;
  63743. };
  63744. /** @hidden */
  63745. InstancedMesh.prototype._preActivate = function () {
  63746. if (this._currentLOD) {
  63747. this._currentLOD._preActivate();
  63748. }
  63749. return this;
  63750. };
  63751. /** @hidden */
  63752. InstancedMesh.prototype._activate = function (renderId) {
  63753. if (this._currentLOD) {
  63754. this._currentLOD._registerInstanceForRenderId(this, renderId);
  63755. }
  63756. return this;
  63757. };
  63758. /**
  63759. * Returns the current associated LOD AbstractMesh.
  63760. */
  63761. InstancedMesh.prototype.getLOD = function (camera) {
  63762. if (!camera) {
  63763. return this;
  63764. }
  63765. var boundingInfo = this.getBoundingInfo();
  63766. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  63767. if (this._currentLOD === this.sourceMesh) {
  63768. return this;
  63769. }
  63770. return this._currentLOD;
  63771. };
  63772. /** @hidden */
  63773. InstancedMesh.prototype._syncSubMeshes = function () {
  63774. this.releaseSubMeshes();
  63775. if (this._sourceMesh.subMeshes) {
  63776. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  63777. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  63778. }
  63779. }
  63780. return this;
  63781. };
  63782. /** @hidden */
  63783. InstancedMesh.prototype._generatePointsArray = function () {
  63784. return this._sourceMesh._generatePointsArray();
  63785. };
  63786. /**
  63787. * Creates a new InstancedMesh from the current mesh.
  63788. * - name (string) : the cloned mesh name
  63789. * - newParent (optional Node) : the optional Node to parent the clone to.
  63790. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  63791. *
  63792. * Returns the clone.
  63793. */
  63794. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63795. var result = this._sourceMesh.createInstance(name);
  63796. // Deep copy
  63797. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  63798. // Bounding info
  63799. this.refreshBoundingInfo();
  63800. // Parent
  63801. if (newParent) {
  63802. result.parent = newParent;
  63803. }
  63804. if (!doNotCloneChildren) {
  63805. // Children
  63806. for (var index = 0; index < this.getScene().meshes.length; index++) {
  63807. var mesh = this.getScene().meshes[index];
  63808. if (mesh.parent === this) {
  63809. mesh.clone(mesh.name, result);
  63810. }
  63811. }
  63812. }
  63813. result.computeWorldMatrix(true);
  63814. return result;
  63815. };
  63816. /**
  63817. * Disposes the InstancedMesh.
  63818. * Returns nothing.
  63819. */
  63820. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  63821. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  63822. // Remove from mesh
  63823. var index = this._sourceMesh.instances.indexOf(this);
  63824. this._sourceMesh.instances.splice(index, 1);
  63825. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  63826. };
  63827. return InstancedMesh;
  63828. }(BABYLON.AbstractMesh));
  63829. BABYLON.InstancedMesh = InstancedMesh;
  63830. })(BABYLON || (BABYLON = {}));
  63831. //# sourceMappingURL=babylon.instancedMesh.js.map
  63832. var BABYLON;
  63833. (function (BABYLON) {
  63834. /**
  63835. * Line mesh
  63836. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  63837. */
  63838. var LinesMesh = /** @class */ (function (_super) {
  63839. __extends(LinesMesh, _super);
  63840. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  63841. /**
  63842. * If vertex color should be applied to the mesh
  63843. */
  63844. useVertexColor,
  63845. /**
  63846. * If vertex alpha should be applied to the mesh
  63847. */
  63848. useVertexAlpha) {
  63849. if (scene === void 0) { scene = null; }
  63850. if (parent === void 0) { parent = null; }
  63851. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  63852. _this.useVertexColor = useVertexColor;
  63853. _this.useVertexAlpha = useVertexAlpha;
  63854. /**
  63855. * Color of the line (Default: White)
  63856. */
  63857. _this.color = new BABYLON.Color3(1, 1, 1);
  63858. /**
  63859. * Alpha of the line (Default: 1)
  63860. */
  63861. _this.alpha = 1;
  63862. if (source) {
  63863. _this.color = source.color.clone();
  63864. _this.alpha = source.alpha;
  63865. _this.useVertexColor = source.useVertexColor;
  63866. _this.useVertexAlpha = source.useVertexAlpha;
  63867. }
  63868. _this._intersectionThreshold = 0.1;
  63869. var defines = [];
  63870. var options = {
  63871. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  63872. uniforms: ["world", "viewProjection"],
  63873. needAlphaBlending: true,
  63874. defines: defines
  63875. };
  63876. if (useVertexAlpha === false) {
  63877. options.needAlphaBlending = false;
  63878. }
  63879. if (!useVertexColor) {
  63880. options.uniforms.push("color");
  63881. }
  63882. else {
  63883. options.defines.push("#define VERTEXCOLOR");
  63884. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  63885. }
  63886. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  63887. return _this;
  63888. }
  63889. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  63890. /**
  63891. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63892. * This margin is expressed in world space coordinates, so its value may vary.
  63893. * Default value is 0.1
  63894. * @returns the intersection Threshold value.
  63895. */
  63896. get: function () {
  63897. return this._intersectionThreshold;
  63898. },
  63899. /**
  63900. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63901. * This margin is expressed in world space coordinates, so its value may vary.
  63902. */
  63903. set: function (value) {
  63904. if (this._intersectionThreshold === value) {
  63905. return;
  63906. }
  63907. this._intersectionThreshold = value;
  63908. if (this.geometry) {
  63909. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  63910. }
  63911. },
  63912. enumerable: true,
  63913. configurable: true
  63914. });
  63915. /**
  63916. * Returns the string "LineMesh"
  63917. */
  63918. LinesMesh.prototype.getClassName = function () {
  63919. return "LinesMesh";
  63920. };
  63921. Object.defineProperty(LinesMesh.prototype, "material", {
  63922. /**
  63923. * @hidden
  63924. */
  63925. get: function () {
  63926. return this._colorShader;
  63927. },
  63928. /**
  63929. * @hidden
  63930. */
  63931. set: function (value) {
  63932. // Do nothing
  63933. },
  63934. enumerable: true,
  63935. configurable: true
  63936. });
  63937. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  63938. /**
  63939. * @hidden
  63940. */
  63941. get: function () {
  63942. return false;
  63943. },
  63944. enumerable: true,
  63945. configurable: true
  63946. });
  63947. /** @hidden */
  63948. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  63949. if (!this._geometry) {
  63950. return this;
  63951. }
  63952. // VBOs
  63953. this._geometry._bind(this._colorShader.getEffect());
  63954. // Color
  63955. if (!this.useVertexColor) {
  63956. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  63957. }
  63958. return this;
  63959. };
  63960. /** @hidden */
  63961. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  63962. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  63963. return this;
  63964. }
  63965. var engine = this.getScene().getEngine();
  63966. // Draw order
  63967. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  63968. return this;
  63969. };
  63970. /**
  63971. * Disposes of the line mesh
  63972. * @param doNotRecurse If children should be disposed
  63973. */
  63974. LinesMesh.prototype.dispose = function (doNotRecurse) {
  63975. this._colorShader.dispose();
  63976. _super.prototype.dispose.call(this, doNotRecurse);
  63977. };
  63978. /**
  63979. * Returns a new LineMesh object cloned from the current one.
  63980. */
  63981. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63982. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  63983. };
  63984. return LinesMesh;
  63985. }(BABYLON.Mesh));
  63986. BABYLON.LinesMesh = LinesMesh;
  63987. })(BABYLON || (BABYLON = {}));
  63988. //# sourceMappingURL=babylon.linesMesh.js.map
  63989. var BABYLON;
  63990. (function (BABYLON) {
  63991. /**
  63992. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63993. * The underlying implementation relies on an associative array to ensure the best performances.
  63994. * The value can be anything including 'null' but except 'undefined'
  63995. */
  63996. var StringDictionary = /** @class */ (function () {
  63997. function StringDictionary() {
  63998. this._count = 0;
  63999. this._data = {};
  64000. }
  64001. /**
  64002. * This will clear this dictionary and copy the content from the 'source' one.
  64003. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64004. * @param source the dictionary to take the content from and copy to this dictionary
  64005. */
  64006. StringDictionary.prototype.copyFrom = function (source) {
  64007. var _this = this;
  64008. this.clear();
  64009. source.forEach(function (t, v) { return _this.add(t, v); });
  64010. };
  64011. /**
  64012. * Get a value based from its key
  64013. * @param key the given key to get the matching value from
  64014. * @return the value if found, otherwise undefined is returned
  64015. */
  64016. StringDictionary.prototype.get = function (key) {
  64017. var val = this._data[key];
  64018. if (val !== undefined) {
  64019. return val;
  64020. }
  64021. return undefined;
  64022. };
  64023. /**
  64024. * Get a value from its key or add it if it doesn't exist.
  64025. * This method will ensure you that a given key/data will be present in the dictionary.
  64026. * @param key the given key to get the matching value from
  64027. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64028. * The factory will only be invoked if there's no data for the given key.
  64029. * @return the value corresponding to the key.
  64030. */
  64031. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64032. var val = this.get(key);
  64033. if (val !== undefined) {
  64034. return val;
  64035. }
  64036. val = factory(key);
  64037. if (val) {
  64038. this.add(key, val);
  64039. }
  64040. return val;
  64041. };
  64042. /**
  64043. * Get a value from its key if present in the dictionary otherwise add it
  64044. * @param key the key to get the value from
  64045. * @param val if there's no such key/value pair in the dictionary add it with this value
  64046. * @return the value corresponding to the key
  64047. */
  64048. StringDictionary.prototype.getOrAdd = function (key, val) {
  64049. var curVal = this.get(key);
  64050. if (curVal !== undefined) {
  64051. return curVal;
  64052. }
  64053. this.add(key, val);
  64054. return val;
  64055. };
  64056. /**
  64057. * Check if there's a given key in the dictionary
  64058. * @param key the key to check for
  64059. * @return true if the key is present, false otherwise
  64060. */
  64061. StringDictionary.prototype.contains = function (key) {
  64062. return this._data[key] !== undefined;
  64063. };
  64064. /**
  64065. * Add a new key and its corresponding value
  64066. * @param key the key to add
  64067. * @param value the value corresponding to the key
  64068. * @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
  64069. */
  64070. StringDictionary.prototype.add = function (key, value) {
  64071. if (this._data[key] !== undefined) {
  64072. return false;
  64073. }
  64074. this._data[key] = value;
  64075. ++this._count;
  64076. return true;
  64077. };
  64078. /**
  64079. * Update a specific value associated to a key
  64080. * @param key defines the key to use
  64081. * @param value defines the value to store
  64082. * @returns true if the value was updated (or false if the key was not found)
  64083. */
  64084. StringDictionary.prototype.set = function (key, value) {
  64085. if (this._data[key] === undefined) {
  64086. return false;
  64087. }
  64088. this._data[key] = value;
  64089. return true;
  64090. };
  64091. /**
  64092. * Get the element of the given key and remove it from the dictionary
  64093. * @param key defines the key to search
  64094. * @returns the value associated with the key or null if not found
  64095. */
  64096. StringDictionary.prototype.getAndRemove = function (key) {
  64097. var val = this.get(key);
  64098. if (val !== undefined) {
  64099. delete this._data[key];
  64100. --this._count;
  64101. return val;
  64102. }
  64103. return null;
  64104. };
  64105. /**
  64106. * Remove a key/value from the dictionary.
  64107. * @param key the key to remove
  64108. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64109. */
  64110. StringDictionary.prototype.remove = function (key) {
  64111. if (this.contains(key)) {
  64112. delete this._data[key];
  64113. --this._count;
  64114. return true;
  64115. }
  64116. return false;
  64117. };
  64118. /**
  64119. * Clear the whole content of the dictionary
  64120. */
  64121. StringDictionary.prototype.clear = function () {
  64122. this._data = {};
  64123. this._count = 0;
  64124. };
  64125. Object.defineProperty(StringDictionary.prototype, "count", {
  64126. /**
  64127. * Gets the current count
  64128. */
  64129. get: function () {
  64130. return this._count;
  64131. },
  64132. enumerable: true,
  64133. configurable: true
  64134. });
  64135. /**
  64136. * Execute a callback on each key/val of the dictionary.
  64137. * Note that you can remove any element in this dictionary in the callback implementation
  64138. * @param callback the callback to execute on a given key/value pair
  64139. */
  64140. StringDictionary.prototype.forEach = function (callback) {
  64141. for (var cur in this._data) {
  64142. var val = this._data[cur];
  64143. callback(cur, val);
  64144. }
  64145. };
  64146. /**
  64147. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64148. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64149. * Note that you can remove any element in this dictionary in the callback implementation
  64150. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64151. * @returns the first item
  64152. */
  64153. StringDictionary.prototype.first = function (callback) {
  64154. for (var cur in this._data) {
  64155. var val = this._data[cur];
  64156. var res = callback(cur, val);
  64157. if (res) {
  64158. return res;
  64159. }
  64160. }
  64161. return null;
  64162. };
  64163. return StringDictionary;
  64164. }());
  64165. BABYLON.StringDictionary = StringDictionary;
  64166. })(BABYLON || (BABYLON = {}));
  64167. //# sourceMappingURL=babylon.stringDictionary.js.map
  64168. var BABYLON;
  64169. (function (BABYLON) {
  64170. var Debug;
  64171. (function (Debug) {
  64172. /**
  64173. * Class used to render a debug view of a given skeleton
  64174. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  64175. */
  64176. var SkeletonViewer = /** @class */ (function () {
  64177. /**
  64178. * Creates a new SkeletonViewer
  64179. * @param skeleton defines the skeleton to render
  64180. * @param mesh defines the mesh attached to the skeleton
  64181. * @param scene defines the hosting scene
  64182. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  64183. * @param renderingGroupId defines the rendering group id to use with the viewer
  64184. */
  64185. function SkeletonViewer(
  64186. /** defines the skeleton to render */
  64187. skeleton,
  64188. /** defines the mesh attached to the skeleton */
  64189. mesh, scene,
  64190. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  64191. autoUpdateBonesMatrices,
  64192. /** defines the rendering group id to use with the viewer */
  64193. renderingGroupId) {
  64194. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  64195. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  64196. this.skeleton = skeleton;
  64197. this.mesh = mesh;
  64198. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  64199. this.renderingGroupId = renderingGroupId;
  64200. /** Gets or sets the color used to render the skeleton */
  64201. this.color = BABYLON.Color3.White();
  64202. this._debugLines = new Array();
  64203. this._isEnabled = false;
  64204. this._scene = scene;
  64205. this.update();
  64206. this._renderFunction = this.update.bind(this);
  64207. }
  64208. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  64209. get: function () {
  64210. return this._isEnabled;
  64211. },
  64212. /** Gets or sets a boolean indicating if the viewer is enabled */
  64213. set: function (value) {
  64214. if (this._isEnabled === value) {
  64215. return;
  64216. }
  64217. this._isEnabled = value;
  64218. if (value) {
  64219. this._scene.registerBeforeRender(this._renderFunction);
  64220. }
  64221. else {
  64222. this._scene.unregisterBeforeRender(this._renderFunction);
  64223. }
  64224. },
  64225. enumerable: true,
  64226. configurable: true
  64227. });
  64228. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  64229. if (x === void 0) { x = 0; }
  64230. if (y === void 0) { y = 0; }
  64231. if (z === void 0) { z = 0; }
  64232. var tmat = BABYLON.Tmp.Matrix[0];
  64233. var parentBone = bone.getParent();
  64234. tmat.copyFrom(bone.getLocalMatrix());
  64235. if (x !== 0 || y !== 0 || z !== 0) {
  64236. var tmat2 = BABYLON.Tmp.Matrix[1];
  64237. BABYLON.Matrix.IdentityToRef(tmat2);
  64238. tmat2.m[12] = x;
  64239. tmat2.m[13] = y;
  64240. tmat2.m[14] = z;
  64241. tmat2.multiplyToRef(tmat, tmat);
  64242. }
  64243. if (parentBone) {
  64244. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  64245. }
  64246. tmat.multiplyToRef(meshMat, tmat);
  64247. position.x = tmat.m[12];
  64248. position.y = tmat.m[13];
  64249. position.z = tmat.m[14];
  64250. };
  64251. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  64252. var len = bones.length;
  64253. var meshPos = this.mesh.position;
  64254. for (var i = 0; i < len; i++) {
  64255. var bone = bones[i];
  64256. var points = this._debugLines[i];
  64257. if (!points) {
  64258. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64259. this._debugLines[i] = points;
  64260. }
  64261. this._getBonePosition(points[0], bone, meshMat);
  64262. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  64263. points[0].subtractInPlace(meshPos);
  64264. points[1].subtractInPlace(meshPos);
  64265. }
  64266. };
  64267. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  64268. var len = bones.length;
  64269. var boneNum = 0;
  64270. var meshPos = this.mesh.position;
  64271. for (var i = len - 1; i >= 0; i--) {
  64272. var childBone = bones[i];
  64273. var parentBone = childBone.getParent();
  64274. if (!parentBone) {
  64275. continue;
  64276. }
  64277. var points = this._debugLines[boneNum];
  64278. if (!points) {
  64279. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64280. this._debugLines[boneNum] = points;
  64281. }
  64282. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64283. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64284. points[0].subtractInPlace(meshPos);
  64285. points[1].subtractInPlace(meshPos);
  64286. boneNum++;
  64287. }
  64288. };
  64289. /** Update the viewer to sync with current skeleton state */
  64290. SkeletonViewer.prototype.update = function () {
  64291. if (this.autoUpdateBonesMatrices) {
  64292. this.skeleton.computeAbsoluteTransforms();
  64293. }
  64294. if (this.skeleton.bones[0].length === undefined) {
  64295. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64296. }
  64297. else {
  64298. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64299. }
  64300. if (!this._debugMesh) {
  64301. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  64302. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64303. }
  64304. else {
  64305. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64306. }
  64307. this._debugMesh.position.copyFrom(this.mesh.position);
  64308. this._debugMesh.color = this.color;
  64309. };
  64310. /** Release associated resources */
  64311. SkeletonViewer.prototype.dispose = function () {
  64312. if (this._debugMesh) {
  64313. this.isEnabled = false;
  64314. this._debugMesh.dispose();
  64315. this._debugMesh = null;
  64316. }
  64317. };
  64318. return SkeletonViewer;
  64319. }());
  64320. Debug.SkeletonViewer = SkeletonViewer;
  64321. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64322. })(BABYLON || (BABYLON = {}));
  64323. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64324. /**
  64325. * Module Debug contains the (visual) components to debug a scene correctly
  64326. */
  64327. var BABYLON;
  64328. (function (BABYLON) {
  64329. var Debug;
  64330. (function (Debug) {
  64331. /**
  64332. * The Axes viewer will show 3 axes in a specific point in space
  64333. */
  64334. var AxesViewer = /** @class */ (function () {
  64335. /**
  64336. * Creates a new AxesViewer
  64337. * @param scene defines the hosting scene
  64338. * @param scaleLines defines a number used to scale line length (1 by default)
  64339. */
  64340. function AxesViewer(scene, scaleLines) {
  64341. if (scaleLines === void 0) { scaleLines = 1; }
  64342. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64343. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64344. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64345. /**
  64346. * Gets or sets a number used to scale line length
  64347. */
  64348. this.scaleLines = 1;
  64349. this.scaleLines = scaleLines;
  64350. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64351. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64352. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64353. this._xmesh.renderingGroupId = 2;
  64354. this._ymesh.renderingGroupId = 2;
  64355. this._zmesh.renderingGroupId = 2;
  64356. this._xmesh.material.checkReadyOnlyOnce = true;
  64357. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64358. this._ymesh.material.checkReadyOnlyOnce = true;
  64359. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64360. this._zmesh.material.checkReadyOnlyOnce = true;
  64361. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64362. this.scene = scene;
  64363. }
  64364. /**
  64365. * Force the viewer to update
  64366. * @param position defines the position of the viewer
  64367. * @param xaxis defines the x axis of the viewer
  64368. * @param yaxis defines the y axis of the viewer
  64369. * @param zaxis defines the z axis of the viewer
  64370. */
  64371. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64372. var scaleLines = this.scaleLines;
  64373. if (this._xmesh) {
  64374. this._xmesh.position.copyFrom(position);
  64375. }
  64376. if (this._ymesh) {
  64377. this._ymesh.position.copyFrom(position);
  64378. }
  64379. if (this._zmesh) {
  64380. this._zmesh.position.copyFrom(position);
  64381. }
  64382. var point2 = this._xline[1];
  64383. point2.x = xaxis.x * scaleLines;
  64384. point2.y = xaxis.y * scaleLines;
  64385. point2.z = xaxis.z * scaleLines;
  64386. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  64387. point2 = this._yline[1];
  64388. point2.x = yaxis.x * scaleLines;
  64389. point2.y = yaxis.y * scaleLines;
  64390. point2.z = yaxis.z * scaleLines;
  64391. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  64392. point2 = this._zline[1];
  64393. point2.x = zaxis.x * scaleLines;
  64394. point2.y = zaxis.y * scaleLines;
  64395. point2.z = zaxis.z * scaleLines;
  64396. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  64397. };
  64398. /** Releases resources */
  64399. AxesViewer.prototype.dispose = function () {
  64400. if (this._xmesh) {
  64401. this._xmesh.dispose();
  64402. }
  64403. if (this._ymesh) {
  64404. this._ymesh.dispose();
  64405. }
  64406. if (this._zmesh) {
  64407. this._zmesh.dispose();
  64408. }
  64409. this._xmesh = null;
  64410. this._ymesh = null;
  64411. this._zmesh = null;
  64412. this.scene = null;
  64413. };
  64414. return AxesViewer;
  64415. }());
  64416. Debug.AxesViewer = AxesViewer;
  64417. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64418. })(BABYLON || (BABYLON = {}));
  64419. //# sourceMappingURL=babylon.axesViewer.js.map
  64420. var BABYLON;
  64421. (function (BABYLON) {
  64422. var Debug;
  64423. (function (Debug) {
  64424. /**
  64425. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  64426. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  64427. */
  64428. var BoneAxesViewer = /** @class */ (function (_super) {
  64429. __extends(BoneAxesViewer, _super);
  64430. /**
  64431. * Creates a new BoneAxesViewer
  64432. * @param scene defines the hosting scene
  64433. * @param bone defines the target bone
  64434. * @param mesh defines the target mesh
  64435. * @param scaleLines defines a scaling factor for line length (1 by default)
  64436. */
  64437. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64438. if (scaleLines === void 0) { scaleLines = 1; }
  64439. var _this = _super.call(this, scene, scaleLines) || this;
  64440. /** Gets current position */
  64441. _this.pos = BABYLON.Vector3.Zero();
  64442. /** Gets direction of X axis */
  64443. _this.xaxis = BABYLON.Vector3.Zero();
  64444. /** Gets direction of Y axis */
  64445. _this.yaxis = BABYLON.Vector3.Zero();
  64446. /** Gets direction of Z axis */
  64447. _this.zaxis = BABYLON.Vector3.Zero();
  64448. _this.mesh = mesh;
  64449. _this.bone = bone;
  64450. return _this;
  64451. }
  64452. /**
  64453. * Force the viewer to update
  64454. */
  64455. BoneAxesViewer.prototype.update = function () {
  64456. if (!this.mesh || !this.bone) {
  64457. return;
  64458. }
  64459. var bone = this.bone;
  64460. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64461. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64462. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64463. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64464. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64465. };
  64466. /** Releases resources */
  64467. BoneAxesViewer.prototype.dispose = function () {
  64468. if (this.mesh) {
  64469. this.mesh = null;
  64470. this.bone = null;
  64471. _super.prototype.dispose.call(this);
  64472. }
  64473. };
  64474. return BoneAxesViewer;
  64475. }(Debug.AxesViewer));
  64476. Debug.BoneAxesViewer = BoneAxesViewer;
  64477. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64478. })(BABYLON || (BABYLON = {}));
  64479. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64480. var BABYLON;
  64481. (function (BABYLON) {
  64482. /**
  64483. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64484. * in order to better appreciate the issue one might have.
  64485. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64486. */
  64487. var RayHelper = /** @class */ (function () {
  64488. /**
  64489. * Instantiate a new ray helper.
  64490. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64491. * in order to better appreciate the issue one might have.
  64492. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64493. * @param ray Defines the ray we are currently tryin to visualize
  64494. */
  64495. function RayHelper(ray) {
  64496. this.ray = ray;
  64497. }
  64498. /**
  64499. * Helper function to create a colored helper in a scene in one line.
  64500. * @param ray Defines the ray we are currently tryin to visualize
  64501. * @param scene Defines the scene the ray is used in
  64502. * @param color Defines the color we want to see the ray in
  64503. * @returns The newly created ray helper.
  64504. */
  64505. RayHelper.CreateAndShow = function (ray, scene, color) {
  64506. var helper = new RayHelper(ray);
  64507. helper.show(scene, color);
  64508. return helper;
  64509. };
  64510. /**
  64511. * Shows the ray we are willing to debug.
  64512. * @param scene Defines the scene the ray needs to be rendered in
  64513. * @param color Defines the color the ray needs to be rendered in
  64514. */
  64515. RayHelper.prototype.show = function (scene, color) {
  64516. if (!this._renderFunction && this.ray) {
  64517. var ray = this.ray;
  64518. this._renderFunction = this._render.bind(this);
  64519. this._scene = scene;
  64520. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64521. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64522. if (this._renderFunction) {
  64523. this._scene.registerBeforeRender(this._renderFunction);
  64524. }
  64525. }
  64526. if (color && this._renderLine) {
  64527. this._renderLine.color.copyFrom(color);
  64528. }
  64529. };
  64530. /**
  64531. * Hides the ray we are debugging.
  64532. */
  64533. RayHelper.prototype.hide = function () {
  64534. if (this._renderFunction && this._scene) {
  64535. this._scene.unregisterBeforeRender(this._renderFunction);
  64536. this._scene = null;
  64537. this._renderFunction = null;
  64538. if (this._renderLine) {
  64539. this._renderLine.dispose();
  64540. this._renderLine = null;
  64541. }
  64542. this._renderPoints = [];
  64543. }
  64544. };
  64545. RayHelper.prototype._render = function () {
  64546. var ray = this.ray;
  64547. if (!ray) {
  64548. return;
  64549. }
  64550. var point = this._renderPoints[1];
  64551. var len = Math.min(ray.length, 1000000);
  64552. point.copyFrom(ray.direction);
  64553. point.scaleInPlace(len);
  64554. point.addInPlace(ray.origin);
  64555. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64556. };
  64557. /**
  64558. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  64559. * @param mesh Defines the mesh we want the helper attached to
  64560. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  64561. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  64562. * @param length Defines the length of the ray
  64563. */
  64564. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64565. this._attachedToMesh = mesh;
  64566. var ray = this.ray;
  64567. if (!ray) {
  64568. return;
  64569. }
  64570. if (!ray.direction) {
  64571. ray.direction = BABYLON.Vector3.Zero();
  64572. }
  64573. if (!ray.origin) {
  64574. ray.origin = BABYLON.Vector3.Zero();
  64575. }
  64576. if (length) {
  64577. ray.length = length;
  64578. }
  64579. if (!meshSpaceOrigin) {
  64580. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64581. }
  64582. if (!meshSpaceDirection) {
  64583. // -1 so that this will work with Mesh.lookAt
  64584. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64585. }
  64586. if (!this._meshSpaceDirection) {
  64587. this._meshSpaceDirection = meshSpaceDirection.clone();
  64588. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64589. }
  64590. else {
  64591. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64592. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64593. }
  64594. if (!this._updateToMeshFunction) {
  64595. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64596. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64597. }
  64598. this._updateToMesh();
  64599. };
  64600. /**
  64601. * Detach the ray helper from the mesh it has previously been attached to.
  64602. */
  64603. RayHelper.prototype.detachFromMesh = function () {
  64604. if (this._attachedToMesh) {
  64605. if (this._updateToMeshFunction) {
  64606. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64607. }
  64608. this._attachedToMesh = null;
  64609. this._updateToMeshFunction = null;
  64610. }
  64611. };
  64612. RayHelper.prototype._updateToMesh = function () {
  64613. var ray = this.ray;
  64614. if (!this._attachedToMesh || !ray) {
  64615. return;
  64616. }
  64617. if (this._attachedToMesh._isDisposed) {
  64618. this.detachFromMesh();
  64619. return;
  64620. }
  64621. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64622. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64623. };
  64624. /**
  64625. * Dispose the helper and release its associated resources.
  64626. */
  64627. RayHelper.prototype.dispose = function () {
  64628. this.hide();
  64629. this.detachFromMesh();
  64630. this.ray = null;
  64631. };
  64632. return RayHelper;
  64633. }());
  64634. BABYLON.RayHelper = RayHelper;
  64635. })(BABYLON || (BABYLON = {}));
  64636. //# sourceMappingURL=babylon.rayHelper.js.map
  64637. var BABYLON;
  64638. (function (BABYLON) {
  64639. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  64640. get: function () {
  64641. if (!this._debugLayer) {
  64642. this._debugLayer = new DebugLayer(this);
  64643. }
  64644. return this._debugLayer;
  64645. },
  64646. enumerable: true,
  64647. configurable: true
  64648. });
  64649. /**
  64650. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64651. * what is happening in your scene
  64652. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64653. */
  64654. var DebugLayer = /** @class */ (function () {
  64655. /**
  64656. * Instantiates a new debug layer.
  64657. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64658. * what is happening in your scene
  64659. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64660. * @param scene Defines the scene to inspect
  64661. */
  64662. function DebugLayer(scene) {
  64663. var _this = this;
  64664. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64665. /**
  64666. * Observable triggered when a property is changed through the inspector.
  64667. */
  64668. this.onPropertyChangedObservable = new BABYLON.Observable();
  64669. this._scene = scene;
  64670. this._scene.onDisposeObservable.add(function () {
  64671. // Debug layer
  64672. if (_this._scene._debugLayer) {
  64673. _this._scene._debugLayer.hide();
  64674. }
  64675. });
  64676. }
  64677. /** Creates the inspector window. */
  64678. DebugLayer.prototype._createInspector = function (config) {
  64679. if (config === void 0) { config = {}; }
  64680. var popup = config.popup || false;
  64681. var initialTab = config.initialTab || 0;
  64682. var parentElement = config.parentElement || null;
  64683. if (!this._inspector) {
  64684. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64685. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64686. } // else nothing to do as instance is already created
  64687. };
  64688. /**
  64689. * Get if the inspector is visible or not.
  64690. * @returns true if visible otherwise, false
  64691. */
  64692. DebugLayer.prototype.isVisible = function () {
  64693. if (!this._inspector) {
  64694. return false;
  64695. }
  64696. return true;
  64697. };
  64698. /**
  64699. * Hide the inspector and close its window.
  64700. */
  64701. DebugLayer.prototype.hide = function () {
  64702. if (this._inspector) {
  64703. try {
  64704. this._inspector.dispose();
  64705. }
  64706. catch (e) {
  64707. // If the inspector has been removed directly from the inspector tool
  64708. }
  64709. this.onPropertyChangedObservable.clear();
  64710. this._inspector = null;
  64711. }
  64712. };
  64713. /**
  64714. *
  64715. * Launch the debugLayer.
  64716. *
  64717. * initialTab:
  64718. * | Value | Tab Name |
  64719. * | --- | --- |
  64720. * | 0 | Scene |
  64721. * | 1 | Console |
  64722. * | 2 | Stats |
  64723. * | 3 | Textures |
  64724. * | 4 | Mesh |
  64725. * | 5 | Light |
  64726. * | 6 | Material |
  64727. * | 7 | GLTF |
  64728. * | 8 | GUI |
  64729. * | 9 | Physics |
  64730. * | 10 | Camera |
  64731. * | 11 | Audio |
  64732. *
  64733. * @param config Define the configuration of the inspector
  64734. */
  64735. DebugLayer.prototype.show = function (config) {
  64736. if (config === void 0) { config = {}; }
  64737. if (typeof this.BJSINSPECTOR == 'undefined') {
  64738. // Load inspector and add it to the DOM
  64739. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64740. }
  64741. else {
  64742. // Otherwise creates the inspector
  64743. this._createInspector(config);
  64744. }
  64745. };
  64746. /**
  64747. * Gets the active tab
  64748. * @return the index of the active tab or -1 if the inspector is hidden
  64749. */
  64750. DebugLayer.prototype.getActiveTab = function () {
  64751. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  64752. };
  64753. /**
  64754. * Define the url to get the inspector script from.
  64755. * By default it uses the babylonjs CDN.
  64756. * @ignoreNaming
  64757. */
  64758. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64759. return DebugLayer;
  64760. }());
  64761. BABYLON.DebugLayer = DebugLayer;
  64762. })(BABYLON || (BABYLON = {}));
  64763. //# sourceMappingURL=babylon.debugLayer.js.map
  64764. var BABYLON;
  64765. (function (BABYLON) {
  64766. var Debug;
  64767. (function (Debug) {
  64768. /**
  64769. * Used to show the physics impostor around the specific mesh
  64770. */
  64771. var PhysicsViewer = /** @class */ (function () {
  64772. /**
  64773. * Creates a new PhysicsViewer
  64774. * @param scene defines the hosting scene
  64775. */
  64776. function PhysicsViewer(scene) {
  64777. /** @hidden */
  64778. this._impostors = [];
  64779. /** @hidden */
  64780. this._meshes = [];
  64781. /** @hidden */
  64782. this._numMeshes = 0;
  64783. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64784. var physicEngine = this._scene.getPhysicsEngine();
  64785. if (physicEngine) {
  64786. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  64787. }
  64788. }
  64789. /** @hidden */
  64790. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64791. var plugin = this._physicsEnginePlugin;
  64792. for (var i = 0; i < this._numMeshes; i++) {
  64793. var impostor = this._impostors[i];
  64794. if (!impostor) {
  64795. continue;
  64796. }
  64797. if (impostor.isDisposed) {
  64798. this.hideImpostor(this._impostors[i--]);
  64799. }
  64800. else {
  64801. var mesh = this._meshes[i];
  64802. if (mesh && plugin) {
  64803. plugin.syncMeshWithImpostor(mesh, impostor);
  64804. }
  64805. }
  64806. }
  64807. };
  64808. /**
  64809. * Renders a specified physic impostor
  64810. * @param impostor defines the impostor to render
  64811. */
  64812. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64813. if (!this._scene) {
  64814. return;
  64815. }
  64816. for (var i = 0; i < this._numMeshes; i++) {
  64817. if (this._impostors[i] == impostor) {
  64818. return;
  64819. }
  64820. }
  64821. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64822. if (debugMesh) {
  64823. this._impostors[this._numMeshes] = impostor;
  64824. this._meshes[this._numMeshes] = debugMesh;
  64825. if (this._numMeshes === 0) {
  64826. this._renderFunction = this._updateDebugMeshes.bind(this);
  64827. this._scene.registerBeforeRender(this._renderFunction);
  64828. }
  64829. this._numMeshes++;
  64830. }
  64831. };
  64832. /**
  64833. * Hides a specified physic impostor
  64834. * @param impostor defines the impostor to hide
  64835. */
  64836. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64837. if (!impostor || !this._scene) {
  64838. return;
  64839. }
  64840. var removed = false;
  64841. for (var i = 0; i < this._numMeshes; i++) {
  64842. if (this._impostors[i] == impostor) {
  64843. var mesh = this._meshes[i];
  64844. if (!mesh) {
  64845. continue;
  64846. }
  64847. this._scene.removeMesh(mesh);
  64848. mesh.dispose();
  64849. this._numMeshes--;
  64850. if (this._numMeshes > 0) {
  64851. this._meshes[i] = this._meshes[this._numMeshes];
  64852. this._impostors[i] = this._impostors[this._numMeshes];
  64853. this._meshes[this._numMeshes] = null;
  64854. this._impostors[this._numMeshes] = null;
  64855. }
  64856. else {
  64857. this._meshes[0] = null;
  64858. this._impostors[0] = null;
  64859. }
  64860. removed = true;
  64861. break;
  64862. }
  64863. }
  64864. if (removed && this._numMeshes === 0) {
  64865. this._scene.unregisterBeforeRender(this._renderFunction);
  64866. }
  64867. };
  64868. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64869. if (!this._debugMaterial) {
  64870. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64871. this._debugMaterial.wireframe = true;
  64872. }
  64873. return this._debugMaterial;
  64874. };
  64875. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64876. if (!this._debugBoxMesh) {
  64877. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64878. this._debugBoxMesh.renderingGroupId = 1;
  64879. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64880. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64881. scene.removeMesh(this._debugBoxMesh);
  64882. }
  64883. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64884. };
  64885. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64886. if (!this._debugSphereMesh) {
  64887. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64888. this._debugSphereMesh.renderingGroupId = 1;
  64889. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64890. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64891. scene.removeMesh(this._debugSphereMesh);
  64892. }
  64893. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64894. };
  64895. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64896. var mesh = null;
  64897. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64898. mesh = this._getDebugBoxMesh(scene);
  64899. impostor.getBoxSizeToRef(mesh.scaling);
  64900. }
  64901. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64902. mesh = this._getDebugSphereMesh(scene);
  64903. var radius = impostor.getRadius();
  64904. mesh.scaling.x = radius * 2;
  64905. mesh.scaling.y = radius * 2;
  64906. mesh.scaling.z = radius * 2;
  64907. }
  64908. return mesh;
  64909. };
  64910. /** Releases all resources */
  64911. PhysicsViewer.prototype.dispose = function () {
  64912. for (var i = 0; i < this._numMeshes; i++) {
  64913. this.hideImpostor(this._impostors[i]);
  64914. }
  64915. if (this._debugBoxMesh) {
  64916. this._debugBoxMesh.dispose();
  64917. }
  64918. if (this._debugSphereMesh) {
  64919. this._debugSphereMesh.dispose();
  64920. }
  64921. if (this._debugMaterial) {
  64922. this._debugMaterial.dispose();
  64923. }
  64924. this._impostors.length = 0;
  64925. this._scene = null;
  64926. this._physicsEnginePlugin = null;
  64927. };
  64928. return PhysicsViewer;
  64929. }());
  64930. Debug.PhysicsViewer = PhysicsViewer;
  64931. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64932. })(BABYLON || (BABYLON = {}));
  64933. //# sourceMappingURL=babylon.physicsViewer.js.map
  64934. var BABYLON;
  64935. (function (BABYLON) {
  64936. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  64937. get: function () {
  64938. return this._forceShowBoundingBoxes || false;
  64939. },
  64940. set: function (value) {
  64941. this._forceShowBoundingBoxes = value;
  64942. // Lazyly creates a BB renderer if needed.
  64943. if (value) {
  64944. this.getBoundingBoxRenderer();
  64945. }
  64946. },
  64947. enumerable: true,
  64948. configurable: true
  64949. });
  64950. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  64951. if (!this._boundingBoxRenderer) {
  64952. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  64953. }
  64954. return this._boundingBoxRenderer;
  64955. };
  64956. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  64957. get: function () {
  64958. return this._showBoundingBox || false;
  64959. },
  64960. set: function (value) {
  64961. this._showBoundingBox = value;
  64962. // Lazyly creates a BB renderer if needed.
  64963. if (value) {
  64964. this.getScene().getBoundingBoxRenderer();
  64965. }
  64966. },
  64967. enumerable: true,
  64968. configurable: true
  64969. });
  64970. /**
  64971. * Component responsible of rendering the bounding box of the meshes in a scene.
  64972. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  64973. */
  64974. var BoundingBoxRenderer = /** @class */ (function () {
  64975. /**
  64976. * Instantiates a new bounding box renderer in a scene.
  64977. * @param scene the scene the renderer renders in
  64978. */
  64979. function BoundingBoxRenderer(scene) {
  64980. /**
  64981. * The component name helpfull to identify the component in the list of scene components.
  64982. */
  64983. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  64984. /**
  64985. * Color of the bounding box lines placed in front of an object
  64986. */
  64987. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64988. /**
  64989. * Color of the bounding box lines placed behind an object
  64990. */
  64991. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64992. /**
  64993. * Defines if the renderer should show the back lines or not
  64994. */
  64995. this.showBackLines = true;
  64996. /**
  64997. * @hidden
  64998. */
  64999. this.renderList = new BABYLON.SmartArray(32);
  65000. this._vertexBuffers = {};
  65001. this.scene = scene;
  65002. scene._addComponent(this);
  65003. }
  65004. /**
  65005. * Registers the component in a given scene
  65006. */
  65007. BoundingBoxRenderer.prototype.register = function () {
  65008. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  65009. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  65010. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  65011. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  65012. };
  65013. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  65014. if (mesh.showSubMeshesBoundingBox) {
  65015. var boundingInfo = subMesh.getBoundingInfo();
  65016. if (boundingInfo !== null && boundingInfo !== undefined) {
  65017. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  65018. this.renderList.push(boundingInfo.boundingBox);
  65019. }
  65020. }
  65021. };
  65022. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  65023. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  65024. var boundingInfo = sourceMesh.getBoundingInfo();
  65025. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  65026. this.renderList.push(boundingInfo.boundingBox);
  65027. }
  65028. };
  65029. BoundingBoxRenderer.prototype._prepareRessources = function () {
  65030. if (this._colorShader) {
  65031. return;
  65032. }
  65033. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  65034. attributes: [BABYLON.VertexBuffer.PositionKind],
  65035. uniforms: ["world", "viewProjection", "color"]
  65036. });
  65037. var engine = this.scene.getEngine();
  65038. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  65039. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  65040. this._createIndexBuffer();
  65041. };
  65042. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  65043. var engine = this.scene.getEngine();
  65044. 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]);
  65045. };
  65046. /**
  65047. * Rebuilds the elements related to this component in case of
  65048. * context lost for instance.
  65049. */
  65050. BoundingBoxRenderer.prototype.rebuild = function () {
  65051. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65052. if (vb) {
  65053. vb._rebuild();
  65054. }
  65055. this._createIndexBuffer();
  65056. };
  65057. /**
  65058. * @hidden
  65059. */
  65060. BoundingBoxRenderer.prototype.reset = function () {
  65061. this.renderList.reset();
  65062. };
  65063. /**
  65064. * Render the bounding boxes of a specific rendering group
  65065. * @param renderingGroupId defines the rendering group to render
  65066. */
  65067. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  65068. if (this.renderList.length === 0) {
  65069. return;
  65070. }
  65071. this._prepareRessources();
  65072. if (!this._colorShader.isReady()) {
  65073. return;
  65074. }
  65075. var engine = this.scene.getEngine();
  65076. engine.setDepthWrite(false);
  65077. this._colorShader._preBind();
  65078. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  65079. var boundingBox = this.renderList.data[boundingBoxIndex];
  65080. if (boundingBox._tag !== renderingGroupId) {
  65081. continue;
  65082. }
  65083. var min = boundingBox.minimum;
  65084. var max = boundingBox.maximum;
  65085. var diff = max.subtract(min);
  65086. var median = min.add(diff.scale(0.5));
  65087. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  65088. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  65089. .multiply(boundingBox.getWorldMatrix());
  65090. // VBOs
  65091. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  65092. if (this.showBackLines) {
  65093. // Back
  65094. engine.setDepthFunctionToGreaterOrEqual();
  65095. this.scene.resetCachedMaterial();
  65096. this._colorShader.setColor4("color", this.backColor.toColor4());
  65097. this._colorShader.bind(worldMatrix);
  65098. // Draw order
  65099. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65100. }
  65101. // Front
  65102. engine.setDepthFunctionToLess();
  65103. this.scene.resetCachedMaterial();
  65104. this._colorShader.setColor4("color", this.frontColor.toColor4());
  65105. this._colorShader.bind(worldMatrix);
  65106. // Draw order
  65107. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65108. }
  65109. this._colorShader.unbind();
  65110. engine.setDepthFunctionToLessOrEqual();
  65111. engine.setDepthWrite(true);
  65112. };
  65113. /**
  65114. * In case of occlusion queries, we can render the occlusion bounding box through this method
  65115. * @param mesh Define the mesh to render the occlusion bounding box for
  65116. */
  65117. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  65118. this._prepareRessources();
  65119. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  65120. return;
  65121. }
  65122. var engine = this.scene.getEngine();
  65123. engine.setDepthWrite(false);
  65124. engine.setColorWrite(false);
  65125. this._colorShader._preBind();
  65126. var boundingBox = mesh._boundingInfo.boundingBox;
  65127. var min = boundingBox.minimum;
  65128. var max = boundingBox.maximum;
  65129. var diff = max.subtract(min);
  65130. var median = min.add(diff.scale(0.5));
  65131. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  65132. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  65133. .multiply(boundingBox.getWorldMatrix());
  65134. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  65135. engine.setDepthFunctionToLess();
  65136. this.scene.resetCachedMaterial();
  65137. this._colorShader.bind(worldMatrix);
  65138. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65139. this._colorShader.unbind();
  65140. engine.setDepthFunctionToLessOrEqual();
  65141. engine.setDepthWrite(true);
  65142. engine.setColorWrite(true);
  65143. };
  65144. /**
  65145. * Dispose and release the resources attached to this renderer.
  65146. */
  65147. BoundingBoxRenderer.prototype.dispose = function () {
  65148. if (!this._colorShader) {
  65149. return;
  65150. }
  65151. this.renderList.dispose();
  65152. this._colorShader.dispose();
  65153. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65154. if (buffer) {
  65155. buffer.dispose();
  65156. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65157. }
  65158. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  65159. };
  65160. return BoundingBoxRenderer;
  65161. }());
  65162. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  65163. })(BABYLON || (BABYLON = {}));
  65164. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  65165. var BABYLON;
  65166. (function (BABYLON) {
  65167. BABYLON.Engine.prototype.createTransformFeedback = function () {
  65168. return this._gl.createTransformFeedback();
  65169. };
  65170. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  65171. this._gl.deleteTransformFeedback(value);
  65172. };
  65173. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  65174. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  65175. };
  65176. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  65177. if (usePoints === void 0) { usePoints = true; }
  65178. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  65179. };
  65180. BABYLON.Engine.prototype.endTransformFeedback = function () {
  65181. this._gl.endTransformFeedback();
  65182. };
  65183. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  65184. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  65185. };
  65186. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  65187. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  65188. };
  65189. })(BABYLON || (BABYLON = {}));
  65190. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  65191. var BABYLON;
  65192. (function (BABYLON) {
  65193. /**
  65194. * This represents a GPU particle system in Babylon
  65195. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  65196. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  65197. */
  65198. var GPUParticleSystem = /** @class */ (function (_super) {
  65199. __extends(GPUParticleSystem, _super);
  65200. /**
  65201. * Instantiates a GPU particle system.
  65202. * 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.
  65203. * @param name The name of the particle system
  65204. * @param options The options used to create the system
  65205. * @param scene The scene the particle system belongs to
  65206. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  65207. */
  65208. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  65209. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  65210. var _this = _super.call(this, name) || this;
  65211. /**
  65212. * The layer mask we are rendering the particles through.
  65213. */
  65214. _this.layerMask = 0x0FFFFFFF;
  65215. _this._accumulatedCount = 0;
  65216. _this._targetIndex = 0;
  65217. _this._currentRenderId = -1;
  65218. _this._started = false;
  65219. _this._stopped = false;
  65220. _this._timeDelta = 0;
  65221. _this._attributesStrideSize = 21;
  65222. _this._actualFrame = 0;
  65223. _this._rawTextureWidth = 256;
  65224. /**
  65225. * An event triggered when the system is disposed.
  65226. */
  65227. _this.onDisposeObservable = new BABYLON.Observable();
  65228. /**
  65229. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  65230. * to override the particles.
  65231. */
  65232. _this.forceDepthWrite = false;
  65233. _this._preWarmDone = false;
  65234. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65235. // Setup the default processing configuration to the scene.
  65236. _this._attachImageProcessingConfiguration(null);
  65237. _this._engine = _this._scene.getEngine();
  65238. if (!options.randomTextureSize) {
  65239. delete options.randomTextureSize;
  65240. }
  65241. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  65242. var optionsAsNumber = options;
  65243. if (isFinite(optionsAsNumber)) {
  65244. fullOptions.capacity = optionsAsNumber;
  65245. }
  65246. _this._capacity = fullOptions.capacity;
  65247. _this._activeCount = fullOptions.capacity;
  65248. _this._currentActiveCount = 0;
  65249. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  65250. _this._scene.particleSystems.push(_this);
  65251. _this._updateEffectOptions = {
  65252. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  65253. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  65254. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  65255. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  65256. uniformBuffersNames: [],
  65257. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  65258. defines: "",
  65259. fallbacks: null,
  65260. onCompiled: null,
  65261. onError: null,
  65262. indexParameters: null,
  65263. maxSimultaneousLights: 0,
  65264. transformFeedbackVaryings: []
  65265. };
  65266. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  65267. // Random data
  65268. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  65269. var d = [];
  65270. for (var i = 0; i < maxTextureSize; ++i) {
  65271. d.push(Math.random());
  65272. d.push(Math.random());
  65273. d.push(Math.random());
  65274. d.push(Math.random());
  65275. }
  65276. _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);
  65277. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65278. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65279. d = [];
  65280. for (var i = 0; i < maxTextureSize; ++i) {
  65281. d.push(Math.random());
  65282. d.push(Math.random());
  65283. d.push(Math.random());
  65284. d.push(Math.random());
  65285. }
  65286. _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);
  65287. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65288. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65289. _this._randomTextureSize = maxTextureSize;
  65290. return _this;
  65291. }
  65292. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  65293. /**
  65294. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  65295. */
  65296. get: function () {
  65297. if (!BABYLON.Engine.LastCreatedEngine) {
  65298. return false;
  65299. }
  65300. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  65301. },
  65302. enumerable: true,
  65303. configurable: true
  65304. });
  65305. /**
  65306. * Gets the maximum number of particles active at the same time.
  65307. * @returns The max number of active particles.
  65308. */
  65309. GPUParticleSystem.prototype.getCapacity = function () {
  65310. return this._capacity;
  65311. };
  65312. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  65313. /**
  65314. * Gets or set the number of active particles
  65315. */
  65316. get: function () {
  65317. return this._activeCount;
  65318. },
  65319. set: function (value) {
  65320. this._activeCount = Math.min(value, this._capacity);
  65321. },
  65322. enumerable: true,
  65323. configurable: true
  65324. });
  65325. /**
  65326. * Is this system ready to be used/rendered
  65327. * @return true if the system is ready
  65328. */
  65329. GPUParticleSystem.prototype.isReady = function () {
  65330. if (!this._updateEffect) {
  65331. this._recreateUpdateEffect();
  65332. this._recreateRenderEffect();
  65333. return false;
  65334. }
  65335. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  65336. return false;
  65337. }
  65338. return true;
  65339. };
  65340. /**
  65341. * Gets if the system has been started. (Note: this will still be true after stop is called)
  65342. * @returns True if it has been started, otherwise false.
  65343. */
  65344. GPUParticleSystem.prototype.isStarted = function () {
  65345. return this._started;
  65346. };
  65347. /**
  65348. * Starts the particle system and begins to emit
  65349. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  65350. */
  65351. GPUParticleSystem.prototype.start = function (delay) {
  65352. var _this = this;
  65353. if (delay === void 0) { delay = this.startDelay; }
  65354. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  65355. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  65356. }
  65357. if (delay) {
  65358. setTimeout(function () {
  65359. _this.start(0);
  65360. }, delay);
  65361. return;
  65362. }
  65363. this._started = true;
  65364. this._stopped = false;
  65365. this._preWarmDone = false;
  65366. // Animations
  65367. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  65368. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  65369. }
  65370. };
  65371. /**
  65372. * Stops the particle system.
  65373. */
  65374. GPUParticleSystem.prototype.stop = function () {
  65375. this._stopped = true;
  65376. };
  65377. /**
  65378. * Remove all active particles
  65379. */
  65380. GPUParticleSystem.prototype.reset = function () {
  65381. this._releaseBuffers();
  65382. this._releaseVAOs();
  65383. this._currentActiveCount = 0;
  65384. this._targetIndex = 0;
  65385. };
  65386. /**
  65387. * Returns the string "GPUParticleSystem"
  65388. * @returns a string containing the class name
  65389. */
  65390. GPUParticleSystem.prototype.getClassName = function () {
  65391. return "GPUParticleSystem";
  65392. };
  65393. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  65394. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  65395. this._releaseBuffers();
  65396. return this;
  65397. };
  65398. /**
  65399. * Adds a new color gradient
  65400. * @param gradient defines the gradient to use (between 0 and 1)
  65401. * @param color1 defines the color to affect to the specified gradient
  65402. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  65403. * @returns the current particle system
  65404. */
  65405. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  65406. if (!this._colorGradients) {
  65407. this._colorGradients = [];
  65408. }
  65409. var colorGradient = new BABYLON.ColorGradient();
  65410. colorGradient.gradient = gradient;
  65411. colorGradient.color1 = color1;
  65412. this._colorGradients.push(colorGradient);
  65413. this._colorGradients.sort(function (a, b) {
  65414. if (a.gradient < b.gradient) {
  65415. return -1;
  65416. }
  65417. else if (a.gradient > b.gradient) {
  65418. return 1;
  65419. }
  65420. return 0;
  65421. });
  65422. if (this._colorGradientsTexture) {
  65423. this._colorGradientsTexture.dispose();
  65424. this._colorGradientsTexture = null;
  65425. }
  65426. this._releaseBuffers();
  65427. return this;
  65428. };
  65429. /**
  65430. * Remove a specific color gradient
  65431. * @param gradient defines the gradient to remove
  65432. * @returns the current particle system
  65433. */
  65434. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  65435. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  65436. this._colorGradientsTexture = null;
  65437. return this;
  65438. };
  65439. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  65440. var valueGradient = new BABYLON.FactorGradient();
  65441. valueGradient.gradient = gradient;
  65442. valueGradient.factor1 = factor;
  65443. factorGradients.push(valueGradient);
  65444. factorGradients.sort(function (a, b) {
  65445. if (a.gradient < b.gradient) {
  65446. return -1;
  65447. }
  65448. else if (a.gradient > b.gradient) {
  65449. return 1;
  65450. }
  65451. return 0;
  65452. });
  65453. this._releaseBuffers();
  65454. };
  65455. /**
  65456. * Adds a new size gradient
  65457. * @param gradient defines the gradient to use (between 0 and 1)
  65458. * @param factor defines the size factor to affect to the specified gradient
  65459. * @returns the current particle system
  65460. */
  65461. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  65462. if (!this._sizeGradients) {
  65463. this._sizeGradients = [];
  65464. }
  65465. this._addFactorGradient(this._sizeGradients, gradient, factor);
  65466. if (this._sizeGradientsTexture) {
  65467. this._sizeGradientsTexture.dispose();
  65468. this._sizeGradientsTexture = null;
  65469. }
  65470. this._releaseBuffers();
  65471. return this;
  65472. };
  65473. /**
  65474. * Remove a specific size gradient
  65475. * @param gradient defines the gradient to remove
  65476. * @returns the current particle system
  65477. */
  65478. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  65479. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  65480. this._sizeGradientsTexture = null;
  65481. return this;
  65482. };
  65483. /**
  65484. * Adds a new angular speed gradient
  65485. * @param gradient defines the gradient to use (between 0 and 1)
  65486. * @param factor defines the angular speed to affect to the specified gradient
  65487. * @returns the current particle system
  65488. */
  65489. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  65490. if (!this._angularSpeedGradients) {
  65491. this._angularSpeedGradients = [];
  65492. }
  65493. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  65494. if (this._angularSpeedGradientsTexture) {
  65495. this._angularSpeedGradientsTexture.dispose();
  65496. this._angularSpeedGradientsTexture = null;
  65497. }
  65498. this._releaseBuffers();
  65499. return this;
  65500. };
  65501. /**
  65502. * Remove a specific angular speed gradient
  65503. * @param gradient defines the gradient to remove
  65504. * @returns the current particle system
  65505. */
  65506. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  65507. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  65508. this._angularSpeedGradientsTexture = null;
  65509. return this;
  65510. };
  65511. /**
  65512. * Adds a new velocity gradient
  65513. * @param gradient defines the gradient to use (between 0 and 1)
  65514. * @param factor defines the velocity to affect to the specified gradient
  65515. * @returns the current particle system
  65516. */
  65517. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  65518. if (!this._velocityGradients) {
  65519. this._velocityGradients = [];
  65520. }
  65521. this._addFactorGradient(this._velocityGradients, gradient, factor);
  65522. if (this._velocityGradientsTexture) {
  65523. this._velocityGradientsTexture.dispose();
  65524. this._velocityGradientsTexture = null;
  65525. }
  65526. this._releaseBuffers();
  65527. return this;
  65528. };
  65529. /**
  65530. * Remove a specific velocity gradient
  65531. * @param gradient defines the gradient to remove
  65532. * @returns the current particle system
  65533. */
  65534. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  65535. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  65536. this._velocityGradientsTexture = null;
  65537. return this;
  65538. };
  65539. /**
  65540. * Adds a new limit velocity gradient
  65541. * @param gradient defines the gradient to use (between 0 and 1)
  65542. * @param factor defines the limit velocity value to affect to the specified gradient
  65543. * @returns the current particle system
  65544. */
  65545. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  65546. if (!this._limitVelocityGradients) {
  65547. this._limitVelocityGradients = [];
  65548. }
  65549. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  65550. if (this._limitVelocityGradientsTexture) {
  65551. this._limitVelocityGradientsTexture.dispose();
  65552. this._limitVelocityGradientsTexture = null;
  65553. }
  65554. this._releaseBuffers();
  65555. return this;
  65556. };
  65557. /**
  65558. * Remove a specific limit velocity gradient
  65559. * @param gradient defines the gradient to remove
  65560. * @returns the current particle system
  65561. */
  65562. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  65563. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  65564. this._limitVelocityGradientsTexture = null;
  65565. return this;
  65566. };
  65567. /**
  65568. * Adds a new drag gradient
  65569. * @param gradient defines the gradient to use (between 0 and 1)
  65570. * @param factor defines the drag value to affect to the specified gradient
  65571. * @returns the current particle system
  65572. */
  65573. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  65574. if (!this._dragGradients) {
  65575. this._dragGradients = [];
  65576. }
  65577. this._addFactorGradient(this._dragGradients, gradient, factor);
  65578. if (this._dragGradientsTexture) {
  65579. this._dragGradientsTexture.dispose();
  65580. this._dragGradientsTexture = null;
  65581. }
  65582. this._releaseBuffers();
  65583. return this;
  65584. };
  65585. /**
  65586. * Remove a specific drag gradient
  65587. * @param gradient defines the gradient to remove
  65588. * @returns the current particle system
  65589. */
  65590. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  65591. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  65592. this._dragGradientsTexture = null;
  65593. return this;
  65594. };
  65595. /**
  65596. * Not supported by GPUParticleSystem
  65597. * @param gradient defines the gradient to use (between 0 and 1)
  65598. * @param factor defines the emit rate value to affect to the specified gradient
  65599. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65600. * @returns the current particle system
  65601. */
  65602. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  65603. // Do nothing as emit rate is not supported by GPUParticleSystem
  65604. return this;
  65605. };
  65606. /**
  65607. * Not supported by GPUParticleSystem
  65608. * @param gradient defines the gradient to remove
  65609. * @returns the current particle system
  65610. */
  65611. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  65612. // Do nothing as emit rate is not supported by GPUParticleSystem
  65613. return this;
  65614. };
  65615. /**
  65616. * Not supported by GPUParticleSystem
  65617. * @param gradient defines the gradient to use (between 0 and 1)
  65618. * @param factor defines the start size value to affect to the specified gradient
  65619. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65620. * @returns the current particle system
  65621. */
  65622. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  65623. // Do nothing as start size is not supported by GPUParticleSystem
  65624. return this;
  65625. };
  65626. /**
  65627. * Not supported by GPUParticleSystem
  65628. * @param gradient defines the gradient to remove
  65629. * @returns the current particle system
  65630. */
  65631. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  65632. // Do nothing as start size is not supported by GPUParticleSystem
  65633. return this;
  65634. };
  65635. /**
  65636. * Not supported by GPUParticleSystem
  65637. * @param gradient defines the gradient to use (between 0 and 1)
  65638. * @param min defines the color remap minimal range
  65639. * @param max defines the color remap maximal range
  65640. * @returns the current particle system
  65641. */
  65642. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  65643. // Do nothing as start size is not supported by GPUParticleSystem
  65644. return this;
  65645. };
  65646. /**
  65647. * Not supported by GPUParticleSystem
  65648. * @param gradient defines the gradient to remove
  65649. * @returns the current particle system
  65650. */
  65651. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  65652. // Do nothing as start size is not supported by GPUParticleSystem
  65653. return this;
  65654. };
  65655. /**
  65656. * Not supported by GPUParticleSystem
  65657. * @param gradient defines the gradient to use (between 0 and 1)
  65658. * @param min defines the alpha remap minimal range
  65659. * @param max defines the alpha remap maximal range
  65660. * @returns the current particle system
  65661. */
  65662. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  65663. // Do nothing as start size is not supported by GPUParticleSystem
  65664. return this;
  65665. };
  65666. /**
  65667. * Not supported by GPUParticleSystem
  65668. * @param gradient defines the gradient to remove
  65669. * @returns the current particle system
  65670. */
  65671. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  65672. // Do nothing as start size is not supported by GPUParticleSystem
  65673. return this;
  65674. };
  65675. /**
  65676. * Not supported by GPUParticleSystem
  65677. * @param gradient defines the gradient to use (between 0 and 1)
  65678. * @param color defines the color to affect to the specified gradient
  65679. * @returns the current particle system
  65680. */
  65681. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  65682. //Not supported by GPUParticleSystem
  65683. return this;
  65684. };
  65685. /**
  65686. * Not supported by GPUParticleSystem
  65687. * @param gradient defines the gradient to remove
  65688. * @returns the current particle system
  65689. */
  65690. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  65691. //Not supported by GPUParticleSystem
  65692. return this;
  65693. };
  65694. /**
  65695. * Not supported by GPUParticleSystem
  65696. * @returns the list of ramp gradients
  65697. */
  65698. GPUParticleSystem.prototype.getRampGradients = function () {
  65699. return null;
  65700. };
  65701. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  65702. /**
  65703. * Not supported by GPUParticleSystem
  65704. * Gets or sets a boolean indicating that ramp gradients must be used
  65705. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  65706. */
  65707. get: function () {
  65708. //Not supported by GPUParticleSystem
  65709. return false;
  65710. },
  65711. set: function (value) {
  65712. //Not supported by GPUParticleSystem
  65713. },
  65714. enumerable: true,
  65715. configurable: true
  65716. });
  65717. /**
  65718. * Not supported by GPUParticleSystem
  65719. * @param gradient defines the gradient to use (between 0 and 1)
  65720. * @param factor defines the life time factor to affect to the specified gradient
  65721. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65722. * @returns the current particle system
  65723. */
  65724. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  65725. //Not supported by GPUParticleSystem
  65726. return this;
  65727. };
  65728. /**
  65729. * Not supported by GPUParticleSystem
  65730. * @param gradient defines the gradient to remove
  65731. * @returns the current particle system
  65732. */
  65733. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  65734. //Not supported by GPUParticleSystem
  65735. return this;
  65736. };
  65737. GPUParticleSystem.prototype._reset = function () {
  65738. this._releaseBuffers();
  65739. };
  65740. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  65741. var updateVertexBuffers = {};
  65742. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  65743. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  65744. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  65745. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  65746. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  65747. var offset = 12;
  65748. if (!this._colorGradientsTexture) {
  65749. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  65750. offset += 4;
  65751. }
  65752. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  65753. offset += 3;
  65754. if (!this._isBillboardBased) {
  65755. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  65756. offset += 3;
  65757. }
  65758. if (this._angularSpeedGradientsTexture) {
  65759. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  65760. offset += 1;
  65761. }
  65762. else {
  65763. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  65764. offset += 2;
  65765. }
  65766. if (this._isAnimationSheetEnabled) {
  65767. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  65768. offset += 1;
  65769. if (this.spriteRandomStartCell) {
  65770. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  65771. offset += 1;
  65772. }
  65773. }
  65774. if (this.noiseTexture) {
  65775. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  65776. offset += 3;
  65777. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  65778. offset += 3;
  65779. }
  65780. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  65781. this._engine.bindArrayBuffer(null);
  65782. return vao;
  65783. };
  65784. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  65785. var renderVertexBuffers = {};
  65786. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  65787. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  65788. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  65789. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  65790. var offset = 12;
  65791. if (!this._colorGradientsTexture) {
  65792. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  65793. offset += 4;
  65794. }
  65795. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  65796. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  65797. }
  65798. offset += 3; // Direction
  65799. if (!this._isBillboardBased) {
  65800. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  65801. offset += 3;
  65802. }
  65803. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  65804. if (this._angularSpeedGradientsTexture) {
  65805. offset++;
  65806. }
  65807. else {
  65808. offset += 2;
  65809. }
  65810. if (this._isAnimationSheetEnabled) {
  65811. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  65812. offset += 1;
  65813. if (this.spriteRandomStartCell) {
  65814. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  65815. offset += 1;
  65816. }
  65817. }
  65818. if (this.noiseTexture) {
  65819. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  65820. offset += 3;
  65821. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  65822. offset += 3;
  65823. }
  65824. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  65825. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  65826. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  65827. this._engine.bindArrayBuffer(null);
  65828. return vao;
  65829. };
  65830. GPUParticleSystem.prototype._initialize = function (force) {
  65831. if (force === void 0) { force = false; }
  65832. if (this._buffer0 && !force) {
  65833. return;
  65834. }
  65835. var engine = this._scene.getEngine();
  65836. var data = new Array();
  65837. if (!this.isBillboardBased) {
  65838. this._attributesStrideSize += 3;
  65839. }
  65840. if (this._colorGradientsTexture) {
  65841. this._attributesStrideSize -= 4;
  65842. }
  65843. if (this._angularSpeedGradientsTexture) {
  65844. this._attributesStrideSize -= 1;
  65845. }
  65846. if (this._isAnimationSheetEnabled) {
  65847. this._attributesStrideSize += 1;
  65848. if (this.spriteRandomStartCell) {
  65849. this._attributesStrideSize += 1;
  65850. }
  65851. }
  65852. if (this.noiseTexture) {
  65853. this._attributesStrideSize += 6;
  65854. }
  65855. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  65856. // position
  65857. data.push(0.0);
  65858. data.push(0.0);
  65859. data.push(0.0);
  65860. // Age and life
  65861. data.push(0.0); // create the particle as a dead one to create a new one at start
  65862. data.push(0.0);
  65863. // Seed
  65864. data.push(Math.random());
  65865. data.push(Math.random());
  65866. data.push(Math.random());
  65867. data.push(Math.random());
  65868. // Size
  65869. data.push(0.0);
  65870. data.push(0.0);
  65871. data.push(0.0);
  65872. if (!this._colorGradientsTexture) {
  65873. // color
  65874. data.push(0.0);
  65875. data.push(0.0);
  65876. data.push(0.0);
  65877. data.push(0.0);
  65878. }
  65879. // direction
  65880. data.push(0.0);
  65881. data.push(0.0);
  65882. data.push(0.0);
  65883. if (!this.isBillboardBased) {
  65884. // initialDirection
  65885. data.push(0.0);
  65886. data.push(0.0);
  65887. data.push(0.0);
  65888. }
  65889. // angle
  65890. data.push(0.0);
  65891. if (!this._angularSpeedGradientsTexture) {
  65892. data.push(0.0);
  65893. }
  65894. if (this._isAnimationSheetEnabled) {
  65895. data.push(0.0);
  65896. if (this.spriteRandomStartCell) {
  65897. data.push(0.0);
  65898. }
  65899. }
  65900. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  65901. data.push(Math.random());
  65902. data.push(Math.random());
  65903. data.push(Math.random());
  65904. data.push(Math.random());
  65905. data.push(Math.random());
  65906. data.push(Math.random());
  65907. }
  65908. }
  65909. // Sprite data
  65910. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  65911. -0.5, 0.5, 0, 1,
  65912. -0.5, -0.5, 0, 0,
  65913. 0.5, -0.5, 1, 0]);
  65914. // Buffers
  65915. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65916. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65917. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  65918. // Update VAO
  65919. this._updateVAO = [];
  65920. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  65921. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  65922. // Render VAO
  65923. this._renderVAO = [];
  65924. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  65925. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  65926. // Links
  65927. this._sourceBuffer = this._buffer0;
  65928. this._targetBuffer = this._buffer1;
  65929. };
  65930. /** @hidden */
  65931. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  65932. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  65933. if (this._isBillboardBased) {
  65934. defines += "\n#define BILLBOARD";
  65935. }
  65936. if (this._colorGradientsTexture) {
  65937. defines += "\n#define COLORGRADIENTS";
  65938. }
  65939. if (this._sizeGradientsTexture) {
  65940. defines += "\n#define SIZEGRADIENTS";
  65941. }
  65942. if (this._angularSpeedGradientsTexture) {
  65943. defines += "\n#define ANGULARSPEEDGRADIENTS";
  65944. }
  65945. if (this._velocityGradientsTexture) {
  65946. defines += "\n#define VELOCITYGRADIENTS";
  65947. }
  65948. if (this._limitVelocityGradientsTexture) {
  65949. defines += "\n#define LIMITVELOCITYGRADIENTS";
  65950. }
  65951. if (this._dragGradientsTexture) {
  65952. defines += "\n#define DRAGGRADIENTS";
  65953. }
  65954. if (this.isAnimationSheetEnabled) {
  65955. defines += "\n#define ANIMATESHEET";
  65956. if (this.spriteRandomStartCell) {
  65957. defines += "\n#define ANIMATESHEETRANDOMSTART";
  65958. }
  65959. }
  65960. if (this.noiseTexture) {
  65961. defines += "\n#define NOISE";
  65962. }
  65963. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  65964. return;
  65965. }
  65966. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  65967. if (!this._colorGradientsTexture) {
  65968. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  65969. }
  65970. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  65971. if (!this._isBillboardBased) {
  65972. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  65973. }
  65974. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  65975. if (this.isAnimationSheetEnabled) {
  65976. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  65977. if (this.spriteRandomStartCell) {
  65978. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  65979. }
  65980. }
  65981. if (this.noiseTexture) {
  65982. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  65983. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  65984. }
  65985. this._updateEffectOptions.defines = defines;
  65986. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  65987. };
  65988. /** @hidden */
  65989. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  65990. var defines = "";
  65991. if (this._scene.clipPlane) {
  65992. defines = "\n#define CLIPPLANE";
  65993. }
  65994. if (this._scene.clipPlane2) {
  65995. defines = "\n#define CLIPPLANE2";
  65996. }
  65997. if (this._scene.clipPlane3) {
  65998. defines = "\n#define CLIPPLANE3";
  65999. }
  66000. if (this._scene.clipPlane4) {
  66001. defines = "\n#define CLIPPLANE4";
  66002. }
  66003. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  66004. defines = "\n#define BLENDMULTIPLYMODE";
  66005. }
  66006. if (this._isBillboardBased) {
  66007. defines += "\n#define BILLBOARD";
  66008. switch (this.billboardMode) {
  66009. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  66010. defines += "\n#define BILLBOARDY";
  66011. break;
  66012. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  66013. defines += "\n#define BILLBOARDSTRETCHED";
  66014. break;
  66015. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  66016. default:
  66017. break;
  66018. }
  66019. }
  66020. if (this._colorGradientsTexture) {
  66021. defines += "\n#define COLORGRADIENTS";
  66022. }
  66023. if (this.isAnimationSheetEnabled) {
  66024. defines += "\n#define ANIMATESHEET";
  66025. }
  66026. if (this._imageProcessingConfiguration) {
  66027. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  66028. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  66029. }
  66030. if (this._renderEffect && this._renderEffect.defines === defines) {
  66031. return;
  66032. }
  66033. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  66034. var samplers = ["textureSampler", "colorGradientSampler"];
  66035. if (BABYLON.ImageProcessingConfiguration) {
  66036. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  66037. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  66038. }
  66039. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  66040. };
  66041. /**
  66042. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  66043. * @param preWarm defines if we are in the pre-warmimg phase
  66044. */
  66045. GPUParticleSystem.prototype.animate = function (preWarm) {
  66046. if (preWarm === void 0) { preWarm = false; }
  66047. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  66048. this._actualFrame += this._timeDelta;
  66049. if (!this._stopped) {
  66050. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  66051. this.stop();
  66052. }
  66053. }
  66054. };
  66055. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  66056. var texture = this[textureName];
  66057. if (!factorGradients || !factorGradients.length || texture) {
  66058. return;
  66059. }
  66060. var data = new Float32Array(this._rawTextureWidth);
  66061. for (var x = 0; x < this._rawTextureWidth; x++) {
  66062. var ratio = x / this._rawTextureWidth;
  66063. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  66064. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  66065. });
  66066. }
  66067. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66068. };
  66069. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  66070. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  66071. };
  66072. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  66073. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  66074. };
  66075. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  66076. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  66077. };
  66078. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  66079. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  66080. };
  66081. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  66082. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  66083. };
  66084. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  66085. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  66086. return;
  66087. }
  66088. var data = new Uint8Array(this._rawTextureWidth * 4);
  66089. var tmpColor = BABYLON.Tmp.Color4[0];
  66090. for (var x = 0; x < this._rawTextureWidth; x++) {
  66091. var ratio = x / this._rawTextureWidth;
  66092. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  66093. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  66094. data[x * 4] = tmpColor.r * 255;
  66095. data[x * 4 + 1] = tmpColor.g * 255;
  66096. data[x * 4 + 2] = tmpColor.b * 255;
  66097. data[x * 4 + 3] = tmpColor.a * 255;
  66098. });
  66099. }
  66100. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66101. };
  66102. /**
  66103. * Renders the particle system in its current state
  66104. * @param preWarm defines if the system should only update the particles but not render them
  66105. * @returns the current number of particles
  66106. */
  66107. GPUParticleSystem.prototype.render = function (preWarm) {
  66108. if (preWarm === void 0) { preWarm = false; }
  66109. if (!this._started) {
  66110. return 0;
  66111. }
  66112. this._createColorGradientTexture();
  66113. this._createSizeGradientTexture();
  66114. this._createAngularSpeedGradientTexture();
  66115. this._createVelocityGradientTexture();
  66116. this._createLimitVelocityGradientTexture();
  66117. this._createDragGradientTexture();
  66118. this._recreateUpdateEffect();
  66119. this._recreateRenderEffect();
  66120. if (!this.isReady()) {
  66121. return 0;
  66122. }
  66123. if (!preWarm) {
  66124. if (!this._preWarmDone && this.preWarmCycles) {
  66125. for (var index = 0; index < this.preWarmCycles; index++) {
  66126. this.animate(true);
  66127. this.render(true);
  66128. }
  66129. this._preWarmDone = true;
  66130. }
  66131. if (this._currentRenderId === this._scene.getRenderId()) {
  66132. return 0;
  66133. }
  66134. this._currentRenderId = this._scene.getRenderId();
  66135. }
  66136. // Get everything ready to render
  66137. this._initialize();
  66138. this._accumulatedCount += this.emitRate * this._timeDelta;
  66139. if (this._accumulatedCount > 1) {
  66140. var intPart = this._accumulatedCount | 0;
  66141. this._accumulatedCount -= intPart;
  66142. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  66143. }
  66144. if (!this._currentActiveCount) {
  66145. return 0;
  66146. }
  66147. // Enable update effect
  66148. this._engine.enableEffect(this._updateEffect);
  66149. this._engine.setState(false);
  66150. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  66151. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  66152. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  66153. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  66154. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  66155. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  66156. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  66157. if (!this._colorGradientsTexture) {
  66158. this._updateEffect.setDirectColor4("color1", this.color1);
  66159. this._updateEffect.setDirectColor4("color2", this.color2);
  66160. }
  66161. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  66162. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  66163. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  66164. this._updateEffect.setVector3("gravity", this.gravity);
  66165. if (this._sizeGradientsTexture) {
  66166. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  66167. }
  66168. if (this._angularSpeedGradientsTexture) {
  66169. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  66170. }
  66171. if (this._velocityGradientsTexture) {
  66172. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  66173. }
  66174. if (this._limitVelocityGradientsTexture) {
  66175. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  66176. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  66177. }
  66178. if (this._dragGradientsTexture) {
  66179. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  66180. }
  66181. if (this.particleEmitterType) {
  66182. this.particleEmitterType.applyToShader(this._updateEffect);
  66183. }
  66184. if (this._isAnimationSheetEnabled) {
  66185. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  66186. }
  66187. if (this.noiseTexture) {
  66188. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  66189. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  66190. }
  66191. var emitterWM;
  66192. if (this.emitter.position) {
  66193. var emitterMesh = this.emitter;
  66194. emitterWM = emitterMesh.getWorldMatrix();
  66195. }
  66196. else {
  66197. var emitterPosition = this.emitter;
  66198. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  66199. }
  66200. this._updateEffect.setMatrix("emitterWM", emitterWM);
  66201. // Bind source VAO
  66202. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  66203. // Update
  66204. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  66205. this._engine.setRasterizerState(false);
  66206. this._engine.beginTransformFeedback(true);
  66207. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  66208. this._engine.endTransformFeedback();
  66209. this._engine.setRasterizerState(true);
  66210. this._engine.bindTransformFeedbackBuffer(null);
  66211. if (!preWarm) {
  66212. // Enable render effect
  66213. this._engine.enableEffect(this._renderEffect);
  66214. var viewMatrix = this._scene.getViewMatrix();
  66215. this._renderEffect.setMatrix("view", viewMatrix);
  66216. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  66217. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  66218. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  66219. if (this._colorGradientsTexture) {
  66220. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  66221. }
  66222. else {
  66223. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  66224. }
  66225. if (this._isAnimationSheetEnabled && this.particleTexture) {
  66226. var baseSize = this.particleTexture.getBaseSize();
  66227. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  66228. }
  66229. if (this._isBillboardBased) {
  66230. var camera = this._scene.activeCamera;
  66231. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  66232. }
  66233. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  66234. var invView = viewMatrix.clone();
  66235. invView.invert();
  66236. this._renderEffect.setMatrix("invView", invView);
  66237. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  66238. }
  66239. // image processing
  66240. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  66241. this._imageProcessingConfiguration.bind(this._renderEffect);
  66242. }
  66243. // Draw order
  66244. switch (this.blendMode) {
  66245. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  66246. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  66247. break;
  66248. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  66249. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  66250. break;
  66251. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  66252. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  66253. break;
  66254. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  66255. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  66256. break;
  66257. }
  66258. if (this.forceDepthWrite) {
  66259. this._engine.setDepthWrite(true);
  66260. }
  66261. // Bind source VAO
  66262. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  66263. // Render
  66264. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  66265. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66266. }
  66267. // Switch VAOs
  66268. this._targetIndex++;
  66269. if (this._targetIndex === 2) {
  66270. this._targetIndex = 0;
  66271. }
  66272. // Switch buffers
  66273. var tmpBuffer = this._sourceBuffer;
  66274. this._sourceBuffer = this._targetBuffer;
  66275. this._targetBuffer = tmpBuffer;
  66276. return this._currentActiveCount;
  66277. };
  66278. /**
  66279. * Rebuilds the particle system
  66280. */
  66281. GPUParticleSystem.prototype.rebuild = function () {
  66282. this._initialize(true);
  66283. };
  66284. GPUParticleSystem.prototype._releaseBuffers = function () {
  66285. if (this._buffer0) {
  66286. this._buffer0.dispose();
  66287. this._buffer0 = null;
  66288. }
  66289. if (this._buffer1) {
  66290. this._buffer1.dispose();
  66291. this._buffer1 = null;
  66292. }
  66293. if (this._spriteBuffer) {
  66294. this._spriteBuffer.dispose();
  66295. this._spriteBuffer = null;
  66296. }
  66297. };
  66298. GPUParticleSystem.prototype._releaseVAOs = function () {
  66299. if (!this._updateVAO) {
  66300. return;
  66301. }
  66302. for (var index = 0; index < this._updateVAO.length; index++) {
  66303. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  66304. }
  66305. this._updateVAO = [];
  66306. for (var index = 0; index < this._renderVAO.length; index++) {
  66307. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  66308. }
  66309. this._renderVAO = [];
  66310. };
  66311. /**
  66312. * Disposes the particle system and free the associated resources
  66313. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  66314. */
  66315. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  66316. if (disposeTexture === void 0) { disposeTexture = true; }
  66317. var index = this._scene.particleSystems.indexOf(this);
  66318. if (index > -1) {
  66319. this._scene.particleSystems.splice(index, 1);
  66320. }
  66321. this._releaseBuffers();
  66322. this._releaseVAOs();
  66323. if (this._colorGradientsTexture) {
  66324. this._colorGradientsTexture.dispose();
  66325. this._colorGradientsTexture = null;
  66326. }
  66327. if (this._sizeGradientsTexture) {
  66328. this._sizeGradientsTexture.dispose();
  66329. this._sizeGradientsTexture = null;
  66330. }
  66331. if (this._angularSpeedGradientsTexture) {
  66332. this._angularSpeedGradientsTexture.dispose();
  66333. this._angularSpeedGradientsTexture = null;
  66334. }
  66335. if (this._velocityGradientsTexture) {
  66336. this._velocityGradientsTexture.dispose();
  66337. this._velocityGradientsTexture = null;
  66338. }
  66339. if (this._limitVelocityGradientsTexture) {
  66340. this._limitVelocityGradientsTexture.dispose();
  66341. this._limitVelocityGradientsTexture = null;
  66342. }
  66343. if (this._dragGradientsTexture) {
  66344. this._dragGradientsTexture.dispose();
  66345. this._dragGradientsTexture = null;
  66346. }
  66347. if (this._randomTexture) {
  66348. this._randomTexture.dispose();
  66349. this._randomTexture = null;
  66350. }
  66351. if (this._randomTexture2) {
  66352. this._randomTexture2.dispose();
  66353. this._randomTexture2 = null;
  66354. }
  66355. if (disposeTexture && this.particleTexture) {
  66356. this.particleTexture.dispose();
  66357. this.particleTexture = null;
  66358. }
  66359. if (disposeTexture && this.noiseTexture) {
  66360. this.noiseTexture.dispose();
  66361. this.noiseTexture = null;
  66362. }
  66363. // Callback
  66364. this.onDisposeObservable.notifyObservers(this);
  66365. this.onDisposeObservable.clear();
  66366. };
  66367. /**
  66368. * Clones the particle system.
  66369. * @param name The name of the cloned object
  66370. * @param newEmitter The new emitter to use
  66371. * @returns the cloned particle system
  66372. */
  66373. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  66374. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  66375. BABYLON.Tools.DeepCopy(this, result);
  66376. if (newEmitter === undefined) {
  66377. newEmitter = this.emitter;
  66378. }
  66379. result.emitter = newEmitter;
  66380. if (this.particleTexture) {
  66381. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  66382. }
  66383. return result;
  66384. };
  66385. /**
  66386. * Serializes the particle system to a JSON object.
  66387. * @returns the JSON object
  66388. */
  66389. GPUParticleSystem.prototype.serialize = function () {
  66390. var serializationObject = {};
  66391. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  66392. serializationObject.activeParticleCount = this.activeParticleCount;
  66393. return serializationObject;
  66394. };
  66395. /**
  66396. * Parses a JSON object to create a GPU particle system.
  66397. * @param parsedParticleSystem The JSON object to parse
  66398. * @param scene The scene to create the particle system in
  66399. * @param rootUrl The root url to use to load external dependencies like texture
  66400. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  66401. * @returns the parsed GPU particle system
  66402. */
  66403. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  66404. if (doNotStart === void 0) { doNotStart = false; }
  66405. var name = parsedParticleSystem.name;
  66406. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  66407. if (parsedParticleSystem.activeParticleCount) {
  66408. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  66409. }
  66410. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  66411. // Auto start
  66412. if (parsedParticleSystem.preventAutoStart) {
  66413. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  66414. }
  66415. if (!doNotStart && !particleSystem.preventAutoStart) {
  66416. particleSystem.start();
  66417. }
  66418. return particleSystem;
  66419. };
  66420. return GPUParticleSystem;
  66421. }(BABYLON.BaseParticleSystem));
  66422. BABYLON.GPUParticleSystem = GPUParticleSystem;
  66423. })(BABYLON || (BABYLON = {}));
  66424. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  66425. var BABYLON;
  66426. (function (BABYLON) {
  66427. /**
  66428. * Represents one particle of a solid particle system.
  66429. */
  66430. var SolidParticle = /** @class */ (function () {
  66431. /**
  66432. * Creates a Solid Particle object.
  66433. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  66434. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  66435. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  66436. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  66437. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  66438. * @param shapeId (integer) is the model shape identifier in the SPS.
  66439. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  66440. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  66441. */
  66442. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  66443. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  66444. /**
  66445. * particle global index
  66446. */
  66447. this.idx = 0;
  66448. /**
  66449. * The color of the particle
  66450. */
  66451. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66452. /**
  66453. * The world space position of the particle.
  66454. */
  66455. this.position = BABYLON.Vector3.Zero();
  66456. /**
  66457. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  66458. */
  66459. this.rotation = BABYLON.Vector3.Zero();
  66460. /**
  66461. * The scaling of the particle.
  66462. */
  66463. this.scaling = BABYLON.Vector3.One();
  66464. /**
  66465. * The uvs of the particle.
  66466. */
  66467. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  66468. /**
  66469. * The current speed of the particle.
  66470. */
  66471. this.velocity = BABYLON.Vector3.Zero();
  66472. /**
  66473. * The pivot point in the particle local space.
  66474. */
  66475. this.pivot = BABYLON.Vector3.Zero();
  66476. /**
  66477. * Must the particle be translated from its pivot point in its local space ?
  66478. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  66479. * Default : false
  66480. */
  66481. this.translateFromPivot = false;
  66482. /**
  66483. * Is the particle active or not ?
  66484. */
  66485. this.alive = true;
  66486. /**
  66487. * Is the particle visible or not ?
  66488. */
  66489. this.isVisible = true;
  66490. /**
  66491. * Index of this particle in the global "positions" array (Internal use)
  66492. * @hidden
  66493. */
  66494. this._pos = 0;
  66495. /**
  66496. * @hidden Index of this particle in the global "indices" array (Internal use)
  66497. */
  66498. this._ind = 0;
  66499. /**
  66500. * ModelShape id of this particle
  66501. */
  66502. this.shapeId = 0;
  66503. /**
  66504. * Index of the particle in its shape id (Internal use)
  66505. */
  66506. this.idxInShape = 0;
  66507. /**
  66508. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  66509. */
  66510. this._stillInvisible = false;
  66511. /**
  66512. * @hidden Last computed particle rotation matrix
  66513. */
  66514. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  66515. /**
  66516. * Parent particle Id, if any.
  66517. * Default null.
  66518. */
  66519. this.parentId = null;
  66520. /**
  66521. * @hidden Internal global position in the SPS.
  66522. */
  66523. this._globalPosition = BABYLON.Vector3.Zero();
  66524. this.idx = particleIndex;
  66525. this._pos = positionIndex;
  66526. this._ind = indiceIndex;
  66527. this._model = model;
  66528. this.shapeId = shapeId;
  66529. this.idxInShape = idxInShape;
  66530. this._sps = sps;
  66531. if (modelBoundingInfo) {
  66532. this._modelBoundingInfo = modelBoundingInfo;
  66533. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  66534. }
  66535. }
  66536. Object.defineProperty(SolidParticle.prototype, "scale", {
  66537. /**
  66538. * Legacy support, changed scale to scaling
  66539. */
  66540. get: function () {
  66541. return this.scaling;
  66542. },
  66543. /**
  66544. * Legacy support, changed scale to scaling
  66545. */
  66546. set: function (scale) {
  66547. this.scaling = scale;
  66548. },
  66549. enumerable: true,
  66550. configurable: true
  66551. });
  66552. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  66553. /**
  66554. * Legacy support, changed quaternion to rotationQuaternion
  66555. */
  66556. get: function () {
  66557. return this.rotationQuaternion;
  66558. },
  66559. /**
  66560. * Legacy support, changed quaternion to rotationQuaternion
  66561. */
  66562. set: function (q) {
  66563. this.rotationQuaternion = q;
  66564. },
  66565. enumerable: true,
  66566. configurable: true
  66567. });
  66568. /**
  66569. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  66570. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  66571. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  66572. * @returns true if it intersects
  66573. */
  66574. SolidParticle.prototype.intersectsMesh = function (target) {
  66575. if (!this._boundingInfo || !target._boundingInfo) {
  66576. return false;
  66577. }
  66578. if (this._sps._bSphereOnly) {
  66579. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  66580. }
  66581. return this._boundingInfo.intersects(target._boundingInfo, false);
  66582. };
  66583. return SolidParticle;
  66584. }());
  66585. BABYLON.SolidParticle = SolidParticle;
  66586. /**
  66587. * Represents the shape of the model used by one particle of a solid particle system.
  66588. * SPS internal tool, don't use it manually.
  66589. */
  66590. var ModelShape = /** @class */ (function () {
  66591. /**
  66592. * 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.
  66593. * SPS internal tool, don't use it manually.
  66594. * @hidden
  66595. */
  66596. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  66597. /**
  66598. * length of the shape in the model indices array (internal use)
  66599. * @hidden
  66600. */
  66601. this._indicesLength = 0;
  66602. this.shapeID = id;
  66603. this._shape = shape;
  66604. this._indicesLength = indicesLength;
  66605. this._shapeUV = shapeUV;
  66606. this._positionFunction = posFunction;
  66607. this._vertexFunction = vtxFunction;
  66608. }
  66609. return ModelShape;
  66610. }());
  66611. BABYLON.ModelShape = ModelShape;
  66612. /**
  66613. * Represents a Depth Sorted Particle in the solid particle system.
  66614. */
  66615. var DepthSortedParticle = /** @class */ (function () {
  66616. function DepthSortedParticle() {
  66617. /**
  66618. * Index of the particle in the "indices" array
  66619. */
  66620. this.ind = 0;
  66621. /**
  66622. * Length of the particle shape in the "indices" array
  66623. */
  66624. this.indicesLength = 0;
  66625. /**
  66626. * Squared distance from the particle to the camera
  66627. */
  66628. this.sqDistance = 0.0;
  66629. }
  66630. return DepthSortedParticle;
  66631. }());
  66632. BABYLON.DepthSortedParticle = DepthSortedParticle;
  66633. })(BABYLON || (BABYLON = {}));
  66634. //# sourceMappingURL=babylon.solidParticle.js.map
  66635. var BABYLON;
  66636. (function (BABYLON) {
  66637. /**
  66638. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  66639. *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.
  66640. * The SPS is also a particle system. It provides some methods to manage the particles.
  66641. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  66642. *
  66643. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  66644. */
  66645. var SolidParticleSystem = /** @class */ (function () {
  66646. /**
  66647. * Creates a SPS (Solid Particle System) object.
  66648. * @param name (String) is the SPS name, this will be the underlying mesh name.
  66649. * @param scene (Scene) is the scene in which the SPS is added.
  66650. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  66651. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  66652. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  66653. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  66654. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  66655. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  66656. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  66657. */
  66658. function SolidParticleSystem(name, scene, options) {
  66659. /**
  66660. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  66661. * Example : var p = SPS.particles[i];
  66662. */
  66663. this.particles = new Array();
  66664. /**
  66665. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  66666. */
  66667. this.nbParticles = 0;
  66668. /**
  66669. * If the particles must ever face the camera (default false). Useful for planar particles.
  66670. */
  66671. this.billboard = false;
  66672. /**
  66673. * Recompute normals when adding a shape
  66674. */
  66675. this.recomputeNormals = true;
  66676. /**
  66677. * This a counter ofr your own usage. It's not set by any SPS functions.
  66678. */
  66679. this.counter = 0;
  66680. /**
  66681. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  66682. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  66683. */
  66684. this.vars = {};
  66685. /**
  66686. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  66687. * @hidden
  66688. */
  66689. this._bSphereOnly = false;
  66690. /**
  66691. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  66692. * @hidden
  66693. */
  66694. this._bSphereRadiusFactor = 1.0;
  66695. this._positions = new Array();
  66696. this._indices = new Array();
  66697. this._normals = new Array();
  66698. this._colors = new Array();
  66699. this._uvs = new Array();
  66700. this._index = 0; // indices index
  66701. this._updatable = true;
  66702. this._pickable = false;
  66703. this._isVisibilityBoxLocked = false;
  66704. this._alwaysVisible = false;
  66705. this._depthSort = false;
  66706. this._shapeCounter = 0;
  66707. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  66708. this._color = new BABYLON.Color4(0, 0, 0, 0);
  66709. this._computeParticleColor = true;
  66710. this._computeParticleTexture = true;
  66711. this._computeParticleRotation = true;
  66712. this._computeParticleVertex = false;
  66713. this._computeBoundingBox = false;
  66714. this._depthSortParticles = true;
  66715. this._cam_axisZ = BABYLON.Vector3.Zero();
  66716. this._cam_axisY = BABYLON.Vector3.Zero();
  66717. this._cam_axisX = BABYLON.Vector3.Zero();
  66718. this._axisZ = BABYLON.Axis.Z;
  66719. this._camDir = BABYLON.Vector3.Zero();
  66720. this._camInvertedPosition = BABYLON.Vector3.Zero();
  66721. this._rotMatrix = new BABYLON.Matrix();
  66722. this._invertMatrix = new BABYLON.Matrix();
  66723. this._rotated = BABYLON.Vector3.Zero();
  66724. this._quaternion = new BABYLON.Quaternion();
  66725. this._vertex = BABYLON.Vector3.Zero();
  66726. this._normal = BABYLON.Vector3.Zero();
  66727. this._yaw = 0.0;
  66728. this._pitch = 0.0;
  66729. this._roll = 0.0;
  66730. this._halfroll = 0.0;
  66731. this._halfpitch = 0.0;
  66732. this._halfyaw = 0.0;
  66733. this._sinRoll = 0.0;
  66734. this._cosRoll = 0.0;
  66735. this._sinPitch = 0.0;
  66736. this._cosPitch = 0.0;
  66737. this._sinYaw = 0.0;
  66738. this._cosYaw = 0.0;
  66739. this._mustUnrotateFixedNormals = false;
  66740. this._minimum = BABYLON.Vector3.Zero();
  66741. this._maximum = BABYLON.Vector3.Zero();
  66742. this._minBbox = BABYLON.Vector3.Zero();
  66743. this._maxBbox = BABYLON.Vector3.Zero();
  66744. this._particlesIntersect = false;
  66745. this._depthSortFunction = function (p1, p2) {
  66746. return (p2.sqDistance - p1.sqDistance);
  66747. };
  66748. this._needs32Bits = false;
  66749. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  66750. this._scaledPivot = BABYLON.Vector3.Zero();
  66751. this._particleHasParent = false;
  66752. this.name = name;
  66753. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66754. this._camera = scene.activeCamera;
  66755. this._pickable = options ? options.isPickable : false;
  66756. this._depthSort = options ? options.enableDepthSort : false;
  66757. this._particlesIntersect = options ? options.particleIntersection : false;
  66758. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  66759. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  66760. if (options && options.updatable !== undefined) {
  66761. this._updatable = options.updatable;
  66762. }
  66763. else {
  66764. this._updatable = true;
  66765. }
  66766. if (this._pickable) {
  66767. this.pickedParticles = [];
  66768. }
  66769. if (this._depthSort) {
  66770. this.depthSortedParticles = [];
  66771. }
  66772. }
  66773. /**
  66774. * Builds the SPS underlying mesh. Returns a standard Mesh.
  66775. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  66776. * @returns the created mesh
  66777. */
  66778. SolidParticleSystem.prototype.buildMesh = function () {
  66779. if (this.nbParticles === 0) {
  66780. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  66781. this.addShape(triangle, 1);
  66782. triangle.dispose();
  66783. }
  66784. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  66785. this._positions32 = new Float32Array(this._positions);
  66786. this._uvs32 = new Float32Array(this._uvs);
  66787. this._colors32 = new Float32Array(this._colors);
  66788. if (this.recomputeNormals) {
  66789. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  66790. }
  66791. this._normals32 = new Float32Array(this._normals);
  66792. this._fixedNormal32 = new Float32Array(this._normals);
  66793. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  66794. this._unrotateFixedNormals();
  66795. }
  66796. var vertexData = new BABYLON.VertexData();
  66797. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  66798. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  66799. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  66800. if (this._uvs32.length > 0) {
  66801. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  66802. }
  66803. if (this._colors32.length > 0) {
  66804. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  66805. }
  66806. var mesh = new BABYLON.Mesh(this.name, this._scene);
  66807. vertexData.applyToMesh(mesh, this._updatable);
  66808. this.mesh = mesh;
  66809. this.mesh.isPickable = this._pickable;
  66810. // free memory
  66811. if (!this._depthSort) {
  66812. this._indices = null;
  66813. }
  66814. this._positions = null;
  66815. this._normals = null;
  66816. this._uvs = null;
  66817. this._colors = null;
  66818. if (!this._updatable) {
  66819. this.particles.length = 0;
  66820. }
  66821. return mesh;
  66822. };
  66823. /**
  66824. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  66825. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  66826. * Thus the particles generated from `digest()` have their property `position` set yet.
  66827. * @param mesh ( Mesh ) is the mesh to be digested
  66828. * @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
  66829. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  66830. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  66831. * @returns the current SPS
  66832. */
  66833. SolidParticleSystem.prototype.digest = function (mesh, options) {
  66834. var size = (options && options.facetNb) || 1;
  66835. var number = (options && options.number) || 0;
  66836. var delta = (options && options.delta) || 0;
  66837. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66838. var meshInd = mesh.getIndices();
  66839. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66840. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66841. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66842. var f = 0; // facet counter
  66843. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  66844. // compute size from number
  66845. if (number) {
  66846. number = (number > totalFacets) ? totalFacets : number;
  66847. size = Math.round(totalFacets / number);
  66848. delta = 0;
  66849. }
  66850. else {
  66851. size = (size > totalFacets) ? totalFacets : size;
  66852. }
  66853. var facetPos = []; // submesh positions
  66854. var facetInd = []; // submesh indices
  66855. var facetUV = []; // submesh UV
  66856. var facetCol = []; // submesh colors
  66857. var barycenter = BABYLON.Vector3.Zero();
  66858. var sizeO = size;
  66859. while (f < totalFacets) {
  66860. size = sizeO + Math.floor((1 + delta) * Math.random());
  66861. if (f > totalFacets - size) {
  66862. size = totalFacets - f;
  66863. }
  66864. // reset temp arrays
  66865. facetPos.length = 0;
  66866. facetInd.length = 0;
  66867. facetUV.length = 0;
  66868. facetCol.length = 0;
  66869. // iterate over "size" facets
  66870. var fi = 0;
  66871. for (var j = f * 3; j < (f + size) * 3; j++) {
  66872. facetInd.push(fi);
  66873. var i = meshInd[j];
  66874. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  66875. if (meshUV) {
  66876. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  66877. }
  66878. if (meshCol) {
  66879. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  66880. }
  66881. fi++;
  66882. }
  66883. // create a model shape for each single particle
  66884. var idx = this.nbParticles;
  66885. var shape = this._posToShape(facetPos);
  66886. var shapeUV = this._uvsToShapeUV(facetUV);
  66887. // compute the barycenter of the shape
  66888. var v;
  66889. for (v = 0; v < shape.length; v++) {
  66890. barycenter.addInPlace(shape[v]);
  66891. }
  66892. barycenter.scaleInPlace(1 / shape.length);
  66893. // shift the shape from its barycenter to the origin
  66894. for (v = 0; v < shape.length; v++) {
  66895. shape[v].subtractInPlace(barycenter);
  66896. }
  66897. var bInfo;
  66898. if (this._particlesIntersect) {
  66899. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  66900. }
  66901. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  66902. // add the particle in the SPS
  66903. var currentPos = this._positions.length;
  66904. var currentInd = this._indices.length;
  66905. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  66906. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  66907. // initialize the particle position
  66908. this.particles[this.nbParticles].position.addInPlace(barycenter);
  66909. this._index += shape.length;
  66910. idx++;
  66911. this.nbParticles++;
  66912. this._shapeCounter++;
  66913. f += size;
  66914. }
  66915. return this;
  66916. };
  66917. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  66918. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  66919. var index = 0;
  66920. var idx = 0;
  66921. for (var p = 0; p < this.particles.length; p++) {
  66922. this._particle = this.particles[p];
  66923. this._shape = this._particle._model._shape;
  66924. if (this._particle.rotationQuaternion) {
  66925. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66926. }
  66927. else {
  66928. this._yaw = this._particle.rotation.y;
  66929. this._pitch = this._particle.rotation.x;
  66930. this._roll = this._particle.rotation.z;
  66931. this._quaternionRotationYPR();
  66932. }
  66933. this._quaternionToRotationMatrix();
  66934. this._rotMatrix.invertToRef(this._invertMatrix);
  66935. for (var pt = 0; pt < this._shape.length; pt++) {
  66936. idx = index + pt * 3;
  66937. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  66938. this._fixedNormal32[idx] = this._normal.x;
  66939. this._fixedNormal32[idx + 1] = this._normal.y;
  66940. this._fixedNormal32[idx + 2] = this._normal.z;
  66941. }
  66942. index = idx + 3;
  66943. }
  66944. };
  66945. //reset copy
  66946. SolidParticleSystem.prototype._resetCopy = function () {
  66947. this._copy.position.x = 0;
  66948. this._copy.position.y = 0;
  66949. this._copy.position.z = 0;
  66950. this._copy.rotation.x = 0;
  66951. this._copy.rotation.y = 0;
  66952. this._copy.rotation.z = 0;
  66953. this._copy.rotationQuaternion = null;
  66954. this._copy.scaling.x = 1.0;
  66955. this._copy.scaling.y = 1.0;
  66956. this._copy.scaling.z = 1.0;
  66957. this._copy.uvs.x = 0;
  66958. this._copy.uvs.y = 0;
  66959. this._copy.uvs.z = 1.0;
  66960. this._copy.uvs.w = 1.0;
  66961. this._copy.color = null;
  66962. this._copy.translateFromPivot = false;
  66963. };
  66964. // _meshBuilder : inserts the shape model in the global SPS mesh
  66965. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  66966. var i;
  66967. var u = 0;
  66968. var c = 0;
  66969. var n = 0;
  66970. this._resetCopy();
  66971. if (options && options.positionFunction) { // call to custom positionFunction
  66972. options.positionFunction(this._copy, idx, idxInShape);
  66973. this._mustUnrotateFixedNormals = true;
  66974. }
  66975. if (this._copy.rotationQuaternion) {
  66976. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66977. }
  66978. else {
  66979. this._yaw = this._copy.rotation.y;
  66980. this._pitch = this._copy.rotation.x;
  66981. this._roll = this._copy.rotation.z;
  66982. this._quaternionRotationYPR();
  66983. }
  66984. this._quaternionToRotationMatrix();
  66985. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  66986. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  66987. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  66988. if (this._copy.translateFromPivot) {
  66989. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66990. }
  66991. else {
  66992. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66993. }
  66994. for (i = 0; i < shape.length; i++) {
  66995. this._vertex.x = shape[i].x;
  66996. this._vertex.y = shape[i].y;
  66997. this._vertex.z = shape[i].z;
  66998. if (options && options.vertexFunction) {
  66999. options.vertexFunction(this._copy, this._vertex, i);
  67000. }
  67001. this._vertex.x *= this._copy.scaling.x;
  67002. this._vertex.y *= this._copy.scaling.y;
  67003. this._vertex.z *= this._copy.scaling.z;
  67004. this._vertex.x -= this._scaledPivot.x;
  67005. this._vertex.y -= this._scaledPivot.y;
  67006. this._vertex.z -= this._scaledPivot.z;
  67007. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  67008. this._rotated.addInPlace(this._pivotBackTranslation);
  67009. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  67010. if (meshUV) {
  67011. 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);
  67012. u += 2;
  67013. }
  67014. if (this._copy.color) {
  67015. this._color = this._copy.color;
  67016. }
  67017. else if (meshCol && meshCol[c] !== undefined) {
  67018. this._color.r = meshCol[c];
  67019. this._color.g = meshCol[c + 1];
  67020. this._color.b = meshCol[c + 2];
  67021. this._color.a = meshCol[c + 3];
  67022. }
  67023. else {
  67024. this._color.r = 1.0;
  67025. this._color.g = 1.0;
  67026. this._color.b = 1.0;
  67027. this._color.a = 1.0;
  67028. }
  67029. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  67030. c += 4;
  67031. if (!this.recomputeNormals && meshNor) {
  67032. this._normal.x = meshNor[n];
  67033. this._normal.y = meshNor[n + 1];
  67034. this._normal.z = meshNor[n + 2];
  67035. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  67036. normals.push(this._normal.x, this._normal.y, this._normal.z);
  67037. n += 3;
  67038. }
  67039. }
  67040. for (i = 0; i < meshInd.length; i++) {
  67041. var current_ind = p + meshInd[i];
  67042. indices.push(current_ind);
  67043. if (current_ind > 65535) {
  67044. this._needs32Bits = true;
  67045. }
  67046. }
  67047. if (this._pickable) {
  67048. var nbfaces = meshInd.length / 3;
  67049. for (i = 0; i < nbfaces; i++) {
  67050. this.pickedParticles.push({ idx: idx, faceId: i });
  67051. }
  67052. }
  67053. if (this._depthSort) {
  67054. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  67055. }
  67056. return this._copy;
  67057. };
  67058. // returns a shape array from positions array
  67059. SolidParticleSystem.prototype._posToShape = function (positions) {
  67060. var shape = [];
  67061. for (var i = 0; i < positions.length; i += 3) {
  67062. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  67063. }
  67064. return shape;
  67065. };
  67066. // returns a shapeUV array from a Vector4 uvs
  67067. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  67068. var shapeUV = [];
  67069. if (uvs) {
  67070. for (var i = 0; i < uvs.length; i++) {
  67071. shapeUV.push(uvs[i]);
  67072. }
  67073. }
  67074. return shapeUV;
  67075. };
  67076. // adds a new particle object in the particles array
  67077. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  67078. if (bInfo === void 0) { bInfo = null; }
  67079. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  67080. this.particles.push(sp);
  67081. return sp;
  67082. };
  67083. /**
  67084. * Adds some particles to the SPS from the model shape. Returns the shape id.
  67085. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  67086. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  67087. * @param nb (positive integer) the number of particles to be created from this model
  67088. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  67089. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  67090. * @returns the number of shapes in the system
  67091. */
  67092. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  67093. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67094. var meshInd = mesh.getIndices();
  67095. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67096. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67097. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67098. var bbInfo;
  67099. if (this._particlesIntersect) {
  67100. bbInfo = mesh.getBoundingInfo();
  67101. }
  67102. var shape = this._posToShape(meshPos);
  67103. var shapeUV = this._uvsToShapeUV(meshUV);
  67104. var posfunc = options ? options.positionFunction : null;
  67105. var vtxfunc = options ? options.vertexFunction : null;
  67106. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  67107. // particles
  67108. var sp;
  67109. var currentCopy;
  67110. var idx = this.nbParticles;
  67111. for (var i = 0; i < nb; i++) {
  67112. var currentPos = this._positions.length;
  67113. var currentInd = this._indices.length;
  67114. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  67115. if (this._updatable) {
  67116. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  67117. sp.position.copyFrom(currentCopy.position);
  67118. sp.rotation.copyFrom(currentCopy.rotation);
  67119. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  67120. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  67121. }
  67122. if (currentCopy.color && sp.color) {
  67123. sp.color.copyFrom(currentCopy.color);
  67124. }
  67125. sp.scaling.copyFrom(currentCopy.scaling);
  67126. sp.uvs.copyFrom(currentCopy.uvs);
  67127. }
  67128. this._index += shape.length;
  67129. idx++;
  67130. }
  67131. this.nbParticles += nb;
  67132. this._shapeCounter++;
  67133. return this._shapeCounter - 1;
  67134. };
  67135. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  67136. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  67137. this._resetCopy();
  67138. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  67139. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  67140. }
  67141. if (this._copy.rotationQuaternion) {
  67142. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  67143. }
  67144. else {
  67145. this._yaw = this._copy.rotation.y;
  67146. this._pitch = this._copy.rotation.x;
  67147. this._roll = this._copy.rotation.z;
  67148. this._quaternionRotationYPR();
  67149. }
  67150. this._quaternionToRotationMatrix();
  67151. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67152. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67153. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67154. if (this._copy.translateFromPivot) {
  67155. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  67156. }
  67157. else {
  67158. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  67159. }
  67160. this._shape = particle._model._shape;
  67161. for (var pt = 0; pt < this._shape.length; pt++) {
  67162. this._vertex.x = this._shape[pt].x;
  67163. this._vertex.y = this._shape[pt].y;
  67164. this._vertex.z = this._shape[pt].z;
  67165. if (particle._model._vertexFunction) {
  67166. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  67167. }
  67168. this._vertex.x *= this._copy.scaling.x;
  67169. this._vertex.y *= this._copy.scaling.y;
  67170. this._vertex.z *= this._copy.scaling.z;
  67171. this._vertex.x -= this._scaledPivot.x;
  67172. this._vertex.y -= this._scaledPivot.y;
  67173. this._vertex.z -= this._scaledPivot.z;
  67174. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  67175. this._rotated.addInPlace(this._pivotBackTranslation);
  67176. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  67177. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  67178. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  67179. }
  67180. particle.position.x = 0.0;
  67181. particle.position.y = 0.0;
  67182. particle.position.z = 0.0;
  67183. particle.rotation.x = 0.0;
  67184. particle.rotation.y = 0.0;
  67185. particle.rotation.z = 0.0;
  67186. particle.rotationQuaternion = null;
  67187. particle.scaling.x = 1.0;
  67188. particle.scaling.y = 1.0;
  67189. particle.scaling.z = 1.0;
  67190. particle.uvs.x = 0.0;
  67191. particle.uvs.y = 0.0;
  67192. particle.uvs.z = 1.0;
  67193. particle.uvs.w = 1.0;
  67194. particle.pivot.x = 0.0;
  67195. particle.pivot.y = 0.0;
  67196. particle.pivot.z = 0.0;
  67197. particle.translateFromPivot = false;
  67198. particle.parentId = null;
  67199. };
  67200. /**
  67201. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  67202. * @returns the SPS.
  67203. */
  67204. SolidParticleSystem.prototype.rebuildMesh = function () {
  67205. for (var p = 0; p < this.particles.length; p++) {
  67206. this._rebuildParticle(this.particles[p]);
  67207. }
  67208. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67209. return this;
  67210. };
  67211. /**
  67212. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  67213. * This method calls `updateParticle()` for each particle of the SPS.
  67214. * For an animated SPS, it is usually called within the render loop.
  67215. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  67216. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  67217. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  67218. * @returns the SPS.
  67219. */
  67220. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  67221. if (start === void 0) { start = 0; }
  67222. if (end === void 0) { end = this.nbParticles - 1; }
  67223. if (update === void 0) { update = true; }
  67224. if (!this._updatable) {
  67225. return this;
  67226. }
  67227. // custom beforeUpdate
  67228. this.beforeUpdateParticles(start, end, update);
  67229. this._cam_axisX.x = 1.0;
  67230. this._cam_axisX.y = 0.0;
  67231. this._cam_axisX.z = 0.0;
  67232. this._cam_axisY.x = 0.0;
  67233. this._cam_axisY.y = 1.0;
  67234. this._cam_axisY.z = 0.0;
  67235. this._cam_axisZ.x = 0.0;
  67236. this._cam_axisZ.y = 0.0;
  67237. this._cam_axisZ.z = 1.0;
  67238. // cases when the World Matrix is to be computed first
  67239. if (this.billboard || this._depthSort) {
  67240. this.mesh.computeWorldMatrix(true);
  67241. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  67242. }
  67243. // if the particles will always face the camera
  67244. if (this.billboard) {
  67245. // compute the camera position and un-rotate it by the current mesh rotation
  67246. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  67247. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  67248. this._cam_axisZ.normalize();
  67249. // same for camera up vector extracted from the cam view matrix
  67250. var view = this._camera.getViewMatrix(true);
  67251. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  67252. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  67253. this._cam_axisY.normalize();
  67254. this._cam_axisX.normalize();
  67255. }
  67256. // if depthSort, compute the camera global position in the mesh local system
  67257. if (this._depthSort) {
  67258. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  67259. }
  67260. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  67261. var idx = 0; // current position index in the global array positions32
  67262. var index = 0; // position start index in the global array positions32 of the current particle
  67263. var colidx = 0; // current color index in the global array colors32
  67264. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  67265. var uvidx = 0; // current uv index in the global array uvs32
  67266. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  67267. var pt = 0; // current index in the particle model shape
  67268. if (this.mesh.isFacetDataEnabled) {
  67269. this._computeBoundingBox = true;
  67270. }
  67271. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  67272. if (this._computeBoundingBox) {
  67273. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  67274. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  67275. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  67276. }
  67277. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  67278. if (this.mesh._boundingInfo) {
  67279. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  67280. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  67281. }
  67282. }
  67283. }
  67284. // particle loop
  67285. index = this.particles[start]._pos;
  67286. var vpos = (index / 3) | 0;
  67287. colorIndex = vpos * 4;
  67288. uvIndex = vpos * 2;
  67289. for (var p = start; p <= end; p++) {
  67290. this._particle = this.particles[p];
  67291. this._shape = this._particle._model._shape;
  67292. this._shapeUV = this._particle._model._shapeUV;
  67293. // call to custom user function to update the particle properties
  67294. this.updateParticle(this._particle);
  67295. // camera-particle distance for depth sorting
  67296. if (this._depthSort && this._depthSortParticles) {
  67297. var dsp = this.depthSortedParticles[p];
  67298. dsp.ind = this._particle._ind;
  67299. dsp.indicesLength = this._particle._model._indicesLength;
  67300. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  67301. }
  67302. // skip the computations for inactive or already invisible particles
  67303. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  67304. // increment indexes for the next particle
  67305. pt = this._shape.length;
  67306. index += pt * 3;
  67307. colorIndex += pt * 4;
  67308. uvIndex += pt * 2;
  67309. continue;
  67310. }
  67311. if (this._particle.isVisible) {
  67312. this._particle._stillInvisible = false; // un-mark permanent invisibility
  67313. this._particleHasParent = (this._particle.parentId !== null);
  67314. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67315. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67316. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67317. // particle rotation matrix
  67318. if (this.billboard) {
  67319. this._particle.rotation.x = 0.0;
  67320. this._particle.rotation.y = 0.0;
  67321. }
  67322. if (this._computeParticleRotation || this.billboard) {
  67323. if (this._particle.rotationQuaternion) {
  67324. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  67325. }
  67326. else {
  67327. this._yaw = this._particle.rotation.y;
  67328. this._pitch = this._particle.rotation.x;
  67329. this._roll = this._particle.rotation.z;
  67330. this._quaternionRotationYPR();
  67331. }
  67332. this._quaternionToRotationMatrix();
  67333. }
  67334. if (this._particleHasParent) {
  67335. this._parent = this.particles[this._particle.parentId];
  67336. 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];
  67337. 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];
  67338. 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];
  67339. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  67340. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  67341. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  67342. if (this._computeParticleRotation || this.billboard) {
  67343. 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];
  67344. 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];
  67345. 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];
  67346. 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];
  67347. 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];
  67348. 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];
  67349. 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];
  67350. 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];
  67351. 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];
  67352. }
  67353. }
  67354. else {
  67355. this._particle._globalPosition.x = this._particle.position.x;
  67356. this._particle._globalPosition.y = this._particle.position.y;
  67357. this._particle._globalPosition.z = this._particle.position.z;
  67358. if (this._computeParticleRotation || this.billboard) {
  67359. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  67360. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  67361. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  67362. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  67363. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  67364. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  67365. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  67366. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  67367. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  67368. }
  67369. }
  67370. if (this._particle.translateFromPivot) {
  67371. this._pivotBackTranslation.x = 0.0;
  67372. this._pivotBackTranslation.y = 0.0;
  67373. this._pivotBackTranslation.z = 0.0;
  67374. }
  67375. else {
  67376. this._pivotBackTranslation.x = this._scaledPivot.x;
  67377. this._pivotBackTranslation.y = this._scaledPivot.y;
  67378. this._pivotBackTranslation.z = this._scaledPivot.z;
  67379. }
  67380. // particle vertex loop
  67381. for (pt = 0; pt < this._shape.length; pt++) {
  67382. idx = index + pt * 3;
  67383. colidx = colorIndex + pt * 4;
  67384. uvidx = uvIndex + pt * 2;
  67385. this._vertex.x = this._shape[pt].x;
  67386. this._vertex.y = this._shape[pt].y;
  67387. this._vertex.z = this._shape[pt].z;
  67388. if (this._computeParticleVertex) {
  67389. this.updateParticleVertex(this._particle, this._vertex, pt);
  67390. }
  67391. // positions
  67392. this._vertex.x *= this._particle.scaling.x;
  67393. this._vertex.y *= this._particle.scaling.y;
  67394. this._vertex.z *= this._particle.scaling.z;
  67395. this._vertex.x -= this._scaledPivot.x;
  67396. this._vertex.y -= this._scaledPivot.y;
  67397. this._vertex.z -= this._scaledPivot.z;
  67398. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67399. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67400. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67401. this._rotated.x += this._pivotBackTranslation.x;
  67402. this._rotated.y += this._pivotBackTranslation.y;
  67403. this._rotated.z += this._pivotBackTranslation.z;
  67404. 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;
  67405. 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;
  67406. 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;
  67407. if (this._computeBoundingBox) {
  67408. if (this._positions32[idx] < this._minimum.x) {
  67409. this._minimum.x = this._positions32[idx];
  67410. }
  67411. if (this._positions32[idx] > this._maximum.x) {
  67412. this._maximum.x = this._positions32[idx];
  67413. }
  67414. if (this._positions32[idx + 1] < this._minimum.y) {
  67415. this._minimum.y = this._positions32[idx + 1];
  67416. }
  67417. if (this._positions32[idx + 1] > this._maximum.y) {
  67418. this._maximum.y = this._positions32[idx + 1];
  67419. }
  67420. if (this._positions32[idx + 2] < this._minimum.z) {
  67421. this._minimum.z = this._positions32[idx + 2];
  67422. }
  67423. if (this._positions32[idx + 2] > this._maximum.z) {
  67424. this._maximum.z = this._positions32[idx + 2];
  67425. }
  67426. }
  67427. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  67428. if (!this._computeParticleVertex) {
  67429. this._normal.x = this._fixedNormal32[idx];
  67430. this._normal.y = this._fixedNormal32[idx + 1];
  67431. this._normal.z = this._fixedNormal32[idx + 2];
  67432. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  67433. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  67434. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  67435. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67436. 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;
  67437. 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;
  67438. }
  67439. if (this._computeParticleColor && this._particle.color) {
  67440. this._colors32[colidx] = this._particle.color.r;
  67441. this._colors32[colidx + 1] = this._particle.color.g;
  67442. this._colors32[colidx + 2] = this._particle.color.b;
  67443. this._colors32[colidx + 3] = this._particle.color.a;
  67444. }
  67445. if (this._computeParticleTexture) {
  67446. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67447. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67448. }
  67449. }
  67450. }
  67451. // particle just set invisible : scaled to zero and positioned at the origin
  67452. else {
  67453. this._particle._stillInvisible = true; // mark the particle as invisible
  67454. for (pt = 0; pt < this._shape.length; pt++) {
  67455. idx = index + pt * 3;
  67456. colidx = colorIndex + pt * 4;
  67457. uvidx = uvIndex + pt * 2;
  67458. this._positions32[idx] = 0.0;
  67459. this._positions32[idx + 1] = 0.0;
  67460. this._positions32[idx + 2] = 0.0;
  67461. this._normals32[idx] = 0.0;
  67462. this._normals32[idx + 1] = 0.0;
  67463. this._normals32[idx + 2] = 0.0;
  67464. if (this._computeParticleColor && this._particle.color) {
  67465. this._colors32[colidx] = this._particle.color.r;
  67466. this._colors32[colidx + 1] = this._particle.color.g;
  67467. this._colors32[colidx + 2] = this._particle.color.b;
  67468. this._colors32[colidx + 3] = this._particle.color.a;
  67469. }
  67470. if (this._computeParticleTexture) {
  67471. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67472. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67473. }
  67474. }
  67475. }
  67476. // if the particle intersections must be computed : update the bbInfo
  67477. if (this._particlesIntersect) {
  67478. var bInfo = this._particle._boundingInfo;
  67479. var bBox = bInfo.boundingBox;
  67480. var bSphere = bInfo.boundingSphere;
  67481. if (!this._bSphereOnly) {
  67482. // place, scale and rotate the particle bbox within the SPS local system, then update it
  67483. for (var b = 0; b < bBox.vectors.length; b++) {
  67484. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  67485. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  67486. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  67487. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67488. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67489. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67490. 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;
  67491. 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;
  67492. 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;
  67493. }
  67494. bBox._update(this.mesh._worldMatrix);
  67495. }
  67496. // place and scale the particle bouding sphere in the SPS local system, then update it
  67497. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  67498. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  67499. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  67500. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  67501. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  67502. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  67503. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  67504. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  67505. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  67506. 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));
  67507. bSphere._update(this.mesh._worldMatrix);
  67508. }
  67509. // increment indexes for the next particle
  67510. index = idx + 3;
  67511. colorIndex = colidx + 4;
  67512. uvIndex = uvidx + 2;
  67513. }
  67514. // if the VBO must be updated
  67515. if (update) {
  67516. if (this._computeParticleColor) {
  67517. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  67518. }
  67519. if (this._computeParticleTexture) {
  67520. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  67521. }
  67522. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67523. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  67524. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  67525. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  67526. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  67527. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  67528. for (var i = 0; i < this._normals32.length; i++) {
  67529. this._fixedNormal32[i] = this._normals32[i];
  67530. }
  67531. }
  67532. if (!this.mesh.areNormalsFrozen) {
  67533. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  67534. }
  67535. }
  67536. if (this._depthSort && this._depthSortParticles) {
  67537. this.depthSortedParticles.sort(this._depthSortFunction);
  67538. var dspl = this.depthSortedParticles.length;
  67539. var sorted = 0;
  67540. var lind = 0;
  67541. var sind = 0;
  67542. var sid = 0;
  67543. for (sorted = 0; sorted < dspl; sorted++) {
  67544. lind = this.depthSortedParticles[sorted].indicesLength;
  67545. sind = this.depthSortedParticles[sorted].ind;
  67546. for (var i = 0; i < lind; i++) {
  67547. this._indices32[sid] = this._indices[sind + i];
  67548. sid++;
  67549. }
  67550. }
  67551. this.mesh.updateIndices(this._indices32);
  67552. }
  67553. }
  67554. if (this._computeBoundingBox) {
  67555. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  67556. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  67557. }
  67558. this.afterUpdateParticles(start, end, update);
  67559. return this;
  67560. };
  67561. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  67562. this._halfroll = this._roll * 0.5;
  67563. this._halfpitch = this._pitch * 0.5;
  67564. this._halfyaw = this._yaw * 0.5;
  67565. this._sinRoll = Math.sin(this._halfroll);
  67566. this._cosRoll = Math.cos(this._halfroll);
  67567. this._sinPitch = Math.sin(this._halfpitch);
  67568. this._cosPitch = Math.cos(this._halfpitch);
  67569. this._sinYaw = Math.sin(this._halfyaw);
  67570. this._cosYaw = Math.cos(this._halfyaw);
  67571. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  67572. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  67573. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  67574. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  67575. };
  67576. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  67577. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  67578. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  67579. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  67580. this._rotMatrix.m[3] = 0;
  67581. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  67582. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  67583. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  67584. this._rotMatrix.m[7] = 0;
  67585. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  67586. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  67587. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  67588. this._rotMatrix.m[11] = 0;
  67589. this._rotMatrix.m[12] = 0;
  67590. this._rotMatrix.m[13] = 0;
  67591. this._rotMatrix.m[14] = 0;
  67592. this._rotMatrix.m[15] = 1.0;
  67593. };
  67594. /**
  67595. * Disposes the SPS.
  67596. */
  67597. SolidParticleSystem.prototype.dispose = function () {
  67598. this.mesh.dispose();
  67599. this.vars = null;
  67600. // drop references to internal big arrays for the GC
  67601. this._positions = null;
  67602. this._indices = null;
  67603. this._normals = null;
  67604. this._uvs = null;
  67605. this._colors = null;
  67606. this._indices32 = null;
  67607. this._positions32 = null;
  67608. this._normals32 = null;
  67609. this._fixedNormal32 = null;
  67610. this._uvs32 = null;
  67611. this._colors32 = null;
  67612. this.pickedParticles = null;
  67613. };
  67614. /**
  67615. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  67616. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67617. * @returns the SPS.
  67618. */
  67619. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  67620. if (!this._isVisibilityBoxLocked) {
  67621. this.mesh.refreshBoundingInfo();
  67622. }
  67623. return this;
  67624. };
  67625. /**
  67626. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  67627. * @param size the size (float) of the visibility box
  67628. * note : this doesn't lock the SPS mesh bounding box.
  67629. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67630. */
  67631. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  67632. var vis = size / 2;
  67633. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  67634. };
  67635. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  67636. /**
  67637. * Gets whether the SPS as always visible or not
  67638. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67639. */
  67640. get: function () {
  67641. return this._alwaysVisible;
  67642. },
  67643. /**
  67644. * Sets the SPS as always visible or not
  67645. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67646. */
  67647. set: function (val) {
  67648. this._alwaysVisible = val;
  67649. this.mesh.alwaysSelectAsActiveMesh = val;
  67650. },
  67651. enumerable: true,
  67652. configurable: true
  67653. });
  67654. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  67655. /**
  67656. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67657. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67658. */
  67659. get: function () {
  67660. return this._isVisibilityBoxLocked;
  67661. },
  67662. /**
  67663. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67664. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67665. */
  67666. set: function (val) {
  67667. this._isVisibilityBoxLocked = val;
  67668. var boundingInfo = this.mesh.getBoundingInfo();
  67669. boundingInfo.isLocked = val;
  67670. },
  67671. enumerable: true,
  67672. configurable: true
  67673. });
  67674. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  67675. /**
  67676. * Gets if `setParticles()` computes the particle rotations or not.
  67677. * Default value : true. The SPS is faster when it's set to false.
  67678. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67679. */
  67680. get: function () {
  67681. return this._computeParticleRotation;
  67682. },
  67683. /**
  67684. * Tells to `setParticles()` to compute the particle rotations or not.
  67685. * Default value : true. The SPS is faster when it's set to false.
  67686. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67687. */
  67688. set: function (val) {
  67689. this._computeParticleRotation = val;
  67690. },
  67691. enumerable: true,
  67692. configurable: true
  67693. });
  67694. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  67695. /**
  67696. * Gets if `setParticles()` computes the particle colors or not.
  67697. * Default value : true. The SPS is faster when it's set to false.
  67698. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67699. */
  67700. get: function () {
  67701. return this._computeParticleColor;
  67702. },
  67703. /**
  67704. * Tells to `setParticles()` to compute the particle colors or not.
  67705. * Default value : true. The SPS is faster when it's set to false.
  67706. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67707. */
  67708. set: function (val) {
  67709. this._computeParticleColor = val;
  67710. },
  67711. enumerable: true,
  67712. configurable: true
  67713. });
  67714. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  67715. /**
  67716. * Gets if `setParticles()` computes the particle textures or not.
  67717. * Default value : true. The SPS is faster when it's set to false.
  67718. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  67719. */
  67720. get: function () {
  67721. return this._computeParticleTexture;
  67722. },
  67723. set: function (val) {
  67724. this._computeParticleTexture = val;
  67725. },
  67726. enumerable: true,
  67727. configurable: true
  67728. });
  67729. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  67730. /**
  67731. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  67732. * Default value : false. The SPS is faster when it's set to false.
  67733. * Note : the particle custom vertex positions aren't stored values.
  67734. */
  67735. get: function () {
  67736. return this._computeParticleVertex;
  67737. },
  67738. /**
  67739. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  67740. * Default value : false. The SPS is faster when it's set to false.
  67741. * Note : the particle custom vertex positions aren't stored values.
  67742. */
  67743. set: function (val) {
  67744. this._computeParticleVertex = val;
  67745. },
  67746. enumerable: true,
  67747. configurable: true
  67748. });
  67749. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  67750. /**
  67751. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  67752. */
  67753. get: function () {
  67754. return this._computeBoundingBox;
  67755. },
  67756. /**
  67757. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  67758. */
  67759. set: function (val) {
  67760. this._computeBoundingBox = val;
  67761. },
  67762. enumerable: true,
  67763. configurable: true
  67764. });
  67765. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  67766. /**
  67767. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  67768. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67769. * Default : `true`
  67770. */
  67771. get: function () {
  67772. return this._depthSortParticles;
  67773. },
  67774. /**
  67775. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  67776. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67777. * Default : `true`
  67778. */
  67779. set: function (val) {
  67780. this._depthSortParticles = val;
  67781. },
  67782. enumerable: true,
  67783. configurable: true
  67784. });
  67785. // =======================================================================
  67786. // Particle behavior logic
  67787. // these following methods may be overwritten by the user to fit his needs
  67788. /**
  67789. * This function does nothing. It may be overwritten to set all the particle first values.
  67790. * The SPS doesn't call this function, you may have to call it by your own.
  67791. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67792. */
  67793. SolidParticleSystem.prototype.initParticles = function () {
  67794. };
  67795. /**
  67796. * This function does nothing. It may be overwritten to recycle a particle.
  67797. * The SPS doesn't call this function, you may have to call it by your own.
  67798. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67799. * @param particle The particle to recycle
  67800. * @returns the recycled particle
  67801. */
  67802. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  67803. return particle;
  67804. };
  67805. /**
  67806. * Updates a particle : this function should be overwritten by the user.
  67807. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  67808. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67809. * @example : just set a particle position or velocity and recycle conditions
  67810. * @param particle The particle to update
  67811. * @returns the updated particle
  67812. */
  67813. SolidParticleSystem.prototype.updateParticle = function (particle) {
  67814. return particle;
  67815. };
  67816. /**
  67817. * Updates a vertex of a particle : it can be overwritten by the user.
  67818. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  67819. * @param particle the current particle
  67820. * @param vertex the current index of the current particle
  67821. * @param pt the index of the current vertex in the particle shape
  67822. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  67823. * @example : just set a vertex particle position
  67824. * @returns the updated vertex
  67825. */
  67826. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  67827. return vertex;
  67828. };
  67829. /**
  67830. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  67831. * This does nothing and may be overwritten by the user.
  67832. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67833. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67834. * @param update the boolean update value actually passed to setParticles()
  67835. */
  67836. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  67837. };
  67838. /**
  67839. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  67840. * This will be passed three parameters.
  67841. * This does nothing and may be overwritten by the user.
  67842. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67843. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67844. * @param update the boolean update value actually passed to setParticles()
  67845. */
  67846. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  67847. };
  67848. return SolidParticleSystem;
  67849. }());
  67850. BABYLON.SolidParticleSystem = SolidParticleSystem;
  67851. })(BABYLON || (BABYLON = {}));
  67852. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  67853. var BABYLON;
  67854. (function (BABYLON) {
  67855. /**
  67856. * Class containing static functions to help procedurally build meshes
  67857. */
  67858. var MeshBuilder = /** @class */ (function () {
  67859. function MeshBuilder() {
  67860. }
  67861. MeshBuilder.updateSideOrientation = function (orientation) {
  67862. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  67863. return BABYLON.Mesh.DOUBLESIDE;
  67864. }
  67865. if (orientation === undefined || orientation === null) {
  67866. return BABYLON.Mesh.FRONTSIDE;
  67867. }
  67868. return orientation;
  67869. };
  67870. /**
  67871. * Creates a box mesh
  67872. * * The parameter `size` sets the size (float) of each box side (default 1)
  67873. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  67874. * * 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)
  67875. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67876. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67877. * * 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
  67878. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67879. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  67880. * @param name defines the name of the mesh
  67881. * @param options defines the options used to create the mesh
  67882. * @param scene defines the hosting scene
  67883. * @returns the box mesh
  67884. */
  67885. MeshBuilder.CreateBox = function (name, options, scene) {
  67886. if (scene === void 0) { scene = null; }
  67887. var box = new BABYLON.Mesh(name, scene);
  67888. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67889. box._originalBuilderSideOrientation = options.sideOrientation;
  67890. var vertexData = BABYLON.VertexData.CreateBox(options);
  67891. vertexData.applyToMesh(box, options.updatable);
  67892. return box;
  67893. };
  67894. /**
  67895. * Creates a sphere mesh
  67896. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  67897. * * 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`)
  67898. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  67899. * * 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
  67900. * * 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)
  67901. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67902. * * 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
  67903. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67904. * @param name defines the name of the mesh
  67905. * @param options defines the options used to create the mesh
  67906. * @param scene defines the hosting scene
  67907. * @returns the sphere mesh
  67908. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  67909. */
  67910. MeshBuilder.CreateSphere = function (name, options, scene) {
  67911. var sphere = new BABYLON.Mesh(name, scene);
  67912. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67913. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67914. var vertexData = BABYLON.VertexData.CreateSphere(options);
  67915. vertexData.applyToMesh(sphere, options.updatable);
  67916. return sphere;
  67917. };
  67918. /**
  67919. * Creates a plane polygonal mesh. By default, this is a disc
  67920. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  67921. * * 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
  67922. * * 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
  67923. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67924. * * 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
  67925. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67926. * @param name defines the name of the mesh
  67927. * @param options defines the options used to create the mesh
  67928. * @param scene defines the hosting scene
  67929. * @returns the plane polygonal mesh
  67930. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  67931. */
  67932. MeshBuilder.CreateDisc = function (name, options, scene) {
  67933. if (scene === void 0) { scene = null; }
  67934. var disc = new BABYLON.Mesh(name, scene);
  67935. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67936. disc._originalBuilderSideOrientation = options.sideOrientation;
  67937. var vertexData = BABYLON.VertexData.CreateDisc(options);
  67938. vertexData.applyToMesh(disc, options.updatable);
  67939. return disc;
  67940. };
  67941. /**
  67942. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  67943. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  67944. * * 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`)
  67945. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  67946. * * 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
  67947. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67948. * * 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
  67949. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67950. * @param name defines the name of the mesh
  67951. * @param options defines the options used to create the mesh
  67952. * @param scene defines the hosting scene
  67953. * @returns the icosahedron mesh
  67954. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  67955. */
  67956. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  67957. var sphere = new BABYLON.Mesh(name, scene);
  67958. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67959. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67960. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  67961. vertexData.applyToMesh(sphere, options.updatable);
  67962. return sphere;
  67963. };
  67964. /**
  67965. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67966. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  67967. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  67968. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  67969. * * 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
  67970. * * 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
  67971. * * 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
  67972. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67973. * * 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
  67974. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67975. * * 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
  67976. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  67977. * * 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
  67978. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  67979. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67980. * @param name defines the name of the mesh
  67981. * @param options defines the options used to create the mesh
  67982. * @param scene defines the hosting scene
  67983. * @returns the ribbon mesh
  67984. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  67985. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67986. */
  67987. MeshBuilder.CreateRibbon = function (name, options, scene) {
  67988. if (scene === void 0) { scene = null; }
  67989. var pathArray = options.pathArray;
  67990. var closeArray = options.closeArray;
  67991. var closePath = options.closePath;
  67992. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67993. var instance = options.instance;
  67994. var updatable = options.updatable;
  67995. if (instance) { // existing ribbon instance update
  67996. // positionFunction : ribbon case
  67997. // only pathArray and sideOrientation parameters are taken into account for positions update
  67998. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  67999. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  68000. var positionFunction = function (positions) {
  68001. var minlg = pathArray[0].length;
  68002. var mesh = instance;
  68003. var i = 0;
  68004. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  68005. for (var si = 1; si <= ns; si++) {
  68006. for (var p = 0; p < pathArray.length; p++) {
  68007. var path = pathArray[p];
  68008. var l = path.length;
  68009. minlg = (minlg < l) ? minlg : l;
  68010. var j = 0;
  68011. while (j < minlg) {
  68012. positions[i] = path[j].x;
  68013. positions[i + 1] = path[j].y;
  68014. positions[i + 2] = path[j].z;
  68015. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  68016. BABYLON.Tmp.Vector3[0].x = path[j].x;
  68017. }
  68018. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  68019. BABYLON.Tmp.Vector3[1].x = path[j].x;
  68020. }
  68021. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  68022. BABYLON.Tmp.Vector3[0].y = path[j].y;
  68023. }
  68024. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  68025. BABYLON.Tmp.Vector3[1].y = path[j].y;
  68026. }
  68027. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  68028. BABYLON.Tmp.Vector3[0].z = path[j].z;
  68029. }
  68030. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  68031. BABYLON.Tmp.Vector3[1].z = path[j].z;
  68032. }
  68033. j++;
  68034. i += 3;
  68035. }
  68036. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  68037. positions[i] = path[0].x;
  68038. positions[i + 1] = path[0].y;
  68039. positions[i + 2] = path[0].z;
  68040. i += 3;
  68041. }
  68042. }
  68043. }
  68044. };
  68045. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68046. positionFunction(positions);
  68047. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[2], BABYLON.Tmp.Vector3[3]);
  68048. instance._boundingInfo.update(instance._worldMatrix);
  68049. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  68050. if (options.colors) {
  68051. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68052. for (var c = 0; c < options.colors.length; c++) {
  68053. colors[c * 4] = options.colors[c].r;
  68054. colors[c * 4 + 1] = options.colors[c].g;
  68055. colors[c * 4 + 2] = options.colors[c].b;
  68056. colors[c * 4 + 3] = options.colors[c].a;
  68057. }
  68058. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  68059. }
  68060. if (options.uvs) {
  68061. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68062. for (var i = 0; i < options.uvs.length; i++) {
  68063. uvs[i * 2] = options.uvs[i].x;
  68064. uvs[i * 2 + 1] = options.uvs[i].y;
  68065. }
  68066. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  68067. }
  68068. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  68069. var indices = instance.getIndices();
  68070. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68071. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  68072. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  68073. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  68074. var indexFirst = 0;
  68075. var indexLast = 0;
  68076. for (var p = 0; p < pathArray.length; p++) {
  68077. indexFirst = instance._creationDataStorage.idx[p] * 3;
  68078. if (p + 1 < pathArray.length) {
  68079. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  68080. }
  68081. else {
  68082. indexLast = normals.length - 3;
  68083. }
  68084. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  68085. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  68086. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  68087. normals[indexLast] = normals[indexFirst];
  68088. normals[indexLast + 1] = normals[indexFirst + 1];
  68089. normals[indexLast + 2] = normals[indexFirst + 2];
  68090. }
  68091. }
  68092. if (!(instance.areNormalsFrozen)) {
  68093. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  68094. }
  68095. }
  68096. return instance;
  68097. }
  68098. else { // new ribbon creation
  68099. var ribbon = new BABYLON.Mesh(name, scene);
  68100. ribbon._originalBuilderSideOrientation = sideOrientation;
  68101. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  68102. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  68103. if (closePath) {
  68104. ribbon._creationDataStorage.idx = vertexData._idx;
  68105. }
  68106. ribbon._creationDataStorage.closePath = closePath;
  68107. ribbon._creationDataStorage.closeArray = closeArray;
  68108. vertexData.applyToMesh(ribbon, updatable);
  68109. return ribbon;
  68110. }
  68111. };
  68112. /**
  68113. * Creates a cylinder or a cone mesh
  68114. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  68115. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  68116. * * 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.
  68117. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  68118. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  68119. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  68120. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  68121. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  68122. * * 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).
  68123. * * 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
  68124. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  68125. * * 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
  68126. * * 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.
  68127. * * If `enclose` is false, a ring surface is one element.
  68128. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  68129. * * 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
  68130. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68131. * * 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
  68132. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68133. * @param name defines the name of the mesh
  68134. * @param options defines the options used to create the mesh
  68135. * @param scene defines the hosting scene
  68136. * @returns the cylinder mesh
  68137. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  68138. */
  68139. MeshBuilder.CreateCylinder = function (name, options, scene) {
  68140. var cylinder = new BABYLON.Mesh(name, scene);
  68141. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68142. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  68143. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  68144. vertexData.applyToMesh(cylinder, options.updatable);
  68145. return cylinder;
  68146. };
  68147. /**
  68148. * Creates a torus mesh
  68149. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  68150. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  68151. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  68152. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68153. * * 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
  68154. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68155. * @param name defines the name of the mesh
  68156. * @param options defines the options used to create the mesh
  68157. * @param scene defines the hosting scene
  68158. * @returns the torus mesh
  68159. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  68160. */
  68161. MeshBuilder.CreateTorus = function (name, options, scene) {
  68162. var torus = new BABYLON.Mesh(name, scene);
  68163. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68164. torus._originalBuilderSideOrientation = options.sideOrientation;
  68165. var vertexData = BABYLON.VertexData.CreateTorus(options);
  68166. vertexData.applyToMesh(torus, options.updatable);
  68167. return torus;
  68168. };
  68169. /**
  68170. * Creates a torus knot mesh
  68171. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  68172. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  68173. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  68174. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  68175. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68176. * * 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
  68177. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68178. * @param name defines the name of the mesh
  68179. * @param options defines the options used to create the mesh
  68180. * @param scene defines the hosting scene
  68181. * @returns the torus knot mesh
  68182. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  68183. */
  68184. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  68185. var torusKnot = new BABYLON.Mesh(name, scene);
  68186. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68187. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  68188. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  68189. vertexData.applyToMesh(torusKnot, options.updatable);
  68190. return torusKnot;
  68191. };
  68192. /**
  68193. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  68194. * * 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
  68195. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  68196. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  68197. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  68198. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  68199. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  68200. * * 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
  68201. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  68202. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68203. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  68204. * @param name defines the name of the new line system
  68205. * @param options defines the options used to create the line system
  68206. * @param scene defines the hosting scene
  68207. * @returns a new line system mesh
  68208. */
  68209. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  68210. var instance = options.instance;
  68211. var lines = options.lines;
  68212. var colors = options.colors;
  68213. if (instance) { // lines update
  68214. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68215. var vertexColor;
  68216. var lineColors;
  68217. if (colors) {
  68218. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68219. }
  68220. var i = 0;
  68221. var c = 0;
  68222. for (var l = 0; l < lines.length; l++) {
  68223. var points = lines[l];
  68224. for (var p = 0; p < points.length; p++) {
  68225. positions[i] = points[p].x;
  68226. positions[i + 1] = points[p].y;
  68227. positions[i + 2] = points[p].z;
  68228. if (colors && vertexColor) {
  68229. lineColors = colors[l];
  68230. vertexColor[c] = lineColors[p].r;
  68231. vertexColor[c + 1] = lineColors[p].g;
  68232. vertexColor[c + 2] = lineColors[p].b;
  68233. vertexColor[c + 3] = lineColors[p].a;
  68234. c += 4;
  68235. }
  68236. i += 3;
  68237. }
  68238. }
  68239. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  68240. if (colors && vertexColor) {
  68241. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  68242. }
  68243. return instance;
  68244. }
  68245. // line system creation
  68246. var useVertexColor = (colors) ? true : false;
  68247. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  68248. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  68249. vertexData.applyToMesh(lineSystem, options.updatable);
  68250. return lineSystem;
  68251. };
  68252. /**
  68253. * Creates a line mesh
  68254. * 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
  68255. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68256. * * The parameter `points` is an array successive Vector3
  68257. * * 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
  68258. * * The optional parameter `colors` is an array of successive Color4, one per line point
  68259. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  68260. * * When updating an instance, remember that only point positions can change, not the number of points
  68261. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68262. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  68263. * @param name defines the name of the new line system
  68264. * @param options defines the options used to create the line system
  68265. * @param scene defines the hosting scene
  68266. * @returns a new line mesh
  68267. */
  68268. MeshBuilder.CreateLines = function (name, options, scene) {
  68269. if (scene === void 0) { scene = null; }
  68270. var colors = (options.colors) ? [options.colors] : null;
  68271. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  68272. return lines;
  68273. };
  68274. /**
  68275. * Creates a dashed line mesh
  68276. * * 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
  68277. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68278. * * The parameter `points` is an array successive Vector3
  68279. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  68280. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  68281. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  68282. * * 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
  68283. * * When updating an instance, remember that only point positions can change, not the number of points
  68284. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68285. * @param name defines the name of the mesh
  68286. * @param options defines the options used to create the mesh
  68287. * @param scene defines the hosting scene
  68288. * @returns the dashed line mesh
  68289. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  68290. */
  68291. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  68292. if (scene === void 0) { scene = null; }
  68293. var points = options.points;
  68294. var instance = options.instance;
  68295. var gapSize = options.gapSize || 1;
  68296. var dashSize = options.dashSize || 3;
  68297. if (instance) { // dashed lines update
  68298. var positionFunction = function (positions) {
  68299. var curvect = BABYLON.Vector3.Zero();
  68300. var nbSeg = positions.length / 6;
  68301. var lg = 0;
  68302. var nb = 0;
  68303. var shft = 0;
  68304. var dashshft = 0;
  68305. var curshft = 0;
  68306. var p = 0;
  68307. var i = 0;
  68308. var j = 0;
  68309. for (i = 0; i < points.length - 1; i++) {
  68310. points[i + 1].subtractToRef(points[i], curvect);
  68311. lg += curvect.length();
  68312. }
  68313. shft = lg / nbSeg;
  68314. var dashSize = instance._creationDataStorage.dashSize;
  68315. var gapSize = instance._creationDataStorage.gapSize;
  68316. dashshft = dashSize * shft / (dashSize + gapSize);
  68317. for (i = 0; i < points.length - 1; i++) {
  68318. points[i + 1].subtractToRef(points[i], curvect);
  68319. nb = Math.floor(curvect.length() / shft);
  68320. curvect.normalize();
  68321. j = 0;
  68322. while (j < nb && p < positions.length) {
  68323. curshft = shft * j;
  68324. positions[p] = points[i].x + curshft * curvect.x;
  68325. positions[p + 1] = points[i].y + curshft * curvect.y;
  68326. positions[p + 2] = points[i].z + curshft * curvect.z;
  68327. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  68328. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  68329. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  68330. p += 6;
  68331. j++;
  68332. }
  68333. }
  68334. while (p < positions.length) {
  68335. positions[p] = points[i].x;
  68336. positions[p + 1] = points[i].y;
  68337. positions[p + 2] = points[i].z;
  68338. p += 3;
  68339. }
  68340. };
  68341. instance.updateMeshPositions(positionFunction, false);
  68342. return instance;
  68343. }
  68344. // dashed lines creation
  68345. var dashedLines = new BABYLON.LinesMesh(name, scene);
  68346. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  68347. vertexData.applyToMesh(dashedLines, options.updatable);
  68348. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  68349. dashedLines._creationDataStorage.dashSize = dashSize;
  68350. dashedLines._creationDataStorage.gapSize = gapSize;
  68351. return dashedLines;
  68352. };
  68353. /**
  68354. * 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.
  68355. * * 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.
  68356. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68357. * * 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.
  68358. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  68359. * * 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
  68360. * * 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
  68361. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  68362. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68363. * * 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
  68364. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  68365. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68366. * @param name defines the name of the mesh
  68367. * @param options defines the options used to create the mesh
  68368. * @param scene defines the hosting scene
  68369. * @returns the extruded shape mesh
  68370. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68371. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68372. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68373. */
  68374. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  68375. if (scene === void 0) { scene = null; }
  68376. var path = options.path;
  68377. var shape = options.shape;
  68378. var scale = options.scale || 1;
  68379. var rotation = options.rotation || 0;
  68380. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68381. var updatable = options.updatable;
  68382. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68383. var instance = options.instance || null;
  68384. var invertUV = options.invertUV || false;
  68385. 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);
  68386. };
  68387. /**
  68388. * Creates an custom extruded shape mesh.
  68389. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  68390. * * 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.
  68391. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68392. * * 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
  68393. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  68394. * * 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
  68395. * * It must returns a float value that will be the scale value applied to the shape on each path point
  68396. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  68397. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  68398. * * 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
  68399. * * 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
  68400. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  68401. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68402. * * 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
  68403. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68404. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68405. * @param name defines the name of the mesh
  68406. * @param options defines the options used to create the mesh
  68407. * @param scene defines the hosting scene
  68408. * @returns the custom extruded shape mesh
  68409. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  68410. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68411. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68412. */
  68413. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  68414. var path = options.path;
  68415. var shape = options.shape;
  68416. var scaleFunction = options.scaleFunction || (function () { return 1; });
  68417. var rotationFunction = options.rotationFunction || (function () { return 0; });
  68418. var ribbonCloseArray = options.ribbonCloseArray || false;
  68419. var ribbonClosePath = options.ribbonClosePath || false;
  68420. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68421. var updatable = options.updatable;
  68422. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68423. var instance = options.instance;
  68424. var invertUV = options.invertUV || false;
  68425. 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);
  68426. };
  68427. /**
  68428. * Creates lathe mesh.
  68429. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  68430. * * 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
  68431. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  68432. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  68433. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  68434. * * 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
  68435. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  68436. * * 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
  68437. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68438. * * 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
  68439. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68440. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68441. * @param name defines the name of the mesh
  68442. * @param options defines the options used to create the mesh
  68443. * @param scene defines the hosting scene
  68444. * @returns the lathe mesh
  68445. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  68446. */
  68447. MeshBuilder.CreateLathe = function (name, options, scene) {
  68448. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  68449. var closed = (options.closed === undefined) ? true : options.closed;
  68450. var shape = options.shape;
  68451. var radius = options.radius || 1;
  68452. var tessellation = options.tessellation || 64;
  68453. var clip = options.clip || 0;
  68454. var updatable = options.updatable;
  68455. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68456. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68457. var pi2 = Math.PI * 2;
  68458. var paths = new Array();
  68459. var invertUV = options.invertUV || false;
  68460. var i = 0;
  68461. var p = 0;
  68462. var step = pi2 / tessellation * arc;
  68463. var rotated;
  68464. var path = new Array();
  68465. for (i = 0; i <= tessellation - clip; i++) {
  68466. var path = [];
  68467. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  68468. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  68469. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  68470. }
  68471. for (p = 0; p < shape.length; p++) {
  68472. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  68473. path.push(rotated);
  68474. }
  68475. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  68476. 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));
  68477. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  68478. }
  68479. paths.push(path);
  68480. }
  68481. // lathe ribbon
  68482. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68483. return lathe;
  68484. };
  68485. /**
  68486. * Creates a plane mesh
  68487. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  68488. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  68489. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  68490. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68491. * * 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
  68492. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68493. * @param name defines the name of the mesh
  68494. * @param options defines the options used to create the mesh
  68495. * @param scene defines the hosting scene
  68496. * @returns the plane mesh
  68497. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68498. */
  68499. MeshBuilder.CreatePlane = function (name, options, scene) {
  68500. var plane = new BABYLON.Mesh(name, scene);
  68501. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68502. plane._originalBuilderSideOrientation = options.sideOrientation;
  68503. var vertexData = BABYLON.VertexData.CreatePlane(options);
  68504. vertexData.applyToMesh(plane, options.updatable);
  68505. if (options.sourcePlane) {
  68506. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  68507. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  68508. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  68509. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  68510. plane.rotate(vectorProduct, product);
  68511. }
  68512. }
  68513. return plane;
  68514. };
  68515. /**
  68516. * Creates a ground mesh
  68517. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  68518. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  68519. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68520. * @param name defines the name of the mesh
  68521. * @param options defines the options used to create the mesh
  68522. * @param scene defines the hosting scene
  68523. * @returns the ground mesh
  68524. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68525. */
  68526. MeshBuilder.CreateGround = function (name, options, scene) {
  68527. var ground = new BABYLON.GroundMesh(name, scene);
  68528. ground._setReady(false);
  68529. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  68530. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  68531. ground._width = options.width || 1;
  68532. ground._height = options.height || 1;
  68533. ground._maxX = ground._width / 2;
  68534. ground._maxZ = ground._height / 2;
  68535. ground._minX = -ground._maxX;
  68536. ground._minZ = -ground._maxZ;
  68537. var vertexData = BABYLON.VertexData.CreateGround(options);
  68538. vertexData.applyToMesh(ground, options.updatable);
  68539. ground._setReady(true);
  68540. return ground;
  68541. };
  68542. /**
  68543. * Creates a tiled ground mesh
  68544. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  68545. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  68546. * * 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
  68547. * * 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
  68548. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68549. * @param name defines the name of the mesh
  68550. * @param options defines the options used to create the mesh
  68551. * @param scene defines the hosting scene
  68552. * @returns the tiled ground mesh
  68553. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  68554. */
  68555. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  68556. var tiledGround = new BABYLON.Mesh(name, scene);
  68557. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  68558. vertexData.applyToMesh(tiledGround, options.updatable);
  68559. return tiledGround;
  68560. };
  68561. /**
  68562. * Creates a ground mesh from a height map
  68563. * * The parameter `url` sets the URL of the height map image resource.
  68564. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  68565. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  68566. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  68567. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  68568. * * 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.
  68569. * * 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).
  68570. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  68571. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68572. * @param name defines the name of the mesh
  68573. * @param url defines the url to the height map
  68574. * @param options defines the options used to create the mesh
  68575. * @param scene defines the hosting scene
  68576. * @returns the ground mesh
  68577. * @see http://doc.babylonjs.com/babylon101/height_map
  68578. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  68579. */
  68580. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  68581. var width = options.width || 10.0;
  68582. var height = options.height || 10.0;
  68583. var subdivisions = options.subdivisions || 1 | 0;
  68584. var minHeight = options.minHeight || 0.0;
  68585. var maxHeight = options.maxHeight || 1.0;
  68586. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  68587. var alphaFilter = options.alphaFilter || 0.0;
  68588. var updatable = options.updatable;
  68589. var onReady = options.onReady;
  68590. var ground = new BABYLON.GroundMesh(name, scene);
  68591. ground._subdivisionsX = subdivisions;
  68592. ground._subdivisionsY = subdivisions;
  68593. ground._width = width;
  68594. ground._height = height;
  68595. ground._maxX = ground._width / 2.0;
  68596. ground._maxZ = ground._height / 2.0;
  68597. ground._minX = -ground._maxX;
  68598. ground._minZ = -ground._maxZ;
  68599. ground._setReady(false);
  68600. var onload = function (img) {
  68601. // Getting height map data
  68602. var canvas = document.createElement("canvas");
  68603. var context = canvas.getContext("2d");
  68604. if (!context) {
  68605. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  68606. }
  68607. if (scene.isDisposed) {
  68608. return;
  68609. }
  68610. var bufferWidth = img.width;
  68611. var bufferHeight = img.height;
  68612. canvas.width = bufferWidth;
  68613. canvas.height = bufferHeight;
  68614. context.drawImage(img, 0, 0);
  68615. // Create VertexData from map data
  68616. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  68617. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  68618. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  68619. width: width, height: height,
  68620. subdivisions: subdivisions,
  68621. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  68622. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  68623. alphaFilter: alphaFilter
  68624. });
  68625. vertexData.applyToMesh(ground, updatable);
  68626. //execute ready callback, if set
  68627. if (onReady) {
  68628. onReady(ground);
  68629. }
  68630. ground._setReady(true);
  68631. };
  68632. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  68633. return ground;
  68634. };
  68635. /**
  68636. * Creates a polygon mesh
  68637. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  68638. * * 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
  68639. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68640. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68641. * * 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)
  68642. * * Remember you can only change the shape positions, not their number when updating a polygon
  68643. * @param name defines the name of the mesh
  68644. * @param options defines the options used to create the mesh
  68645. * @param scene defines the hosting scene
  68646. * @returns the polygon mesh
  68647. */
  68648. MeshBuilder.CreatePolygon = function (name, options, scene) {
  68649. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68650. var shape = options.shape;
  68651. var holes = options.holes || [];
  68652. var depth = options.depth || 0;
  68653. var contours = [];
  68654. var hole = [];
  68655. for (var i = 0; i < shape.length; i++) {
  68656. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  68657. }
  68658. var epsilon = 0.00000001;
  68659. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  68660. contours.pop();
  68661. }
  68662. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  68663. for (var hNb = 0; hNb < holes.length; hNb++) {
  68664. hole = [];
  68665. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  68666. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  68667. }
  68668. polygonTriangulation.addHole(hole);
  68669. }
  68670. var polygon = polygonTriangulation.build(options.updatable, depth);
  68671. polygon._originalBuilderSideOrientation = options.sideOrientation;
  68672. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  68673. vertexData.applyToMesh(polygon, options.updatable);
  68674. return polygon;
  68675. };
  68676. /**
  68677. * Creates an extruded polygon mesh, with depth in the Y direction.
  68678. * * 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)
  68679. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  68680. * @param name defines the name of the mesh
  68681. * @param options defines the options used to create the mesh
  68682. * @param scene defines the hosting scene
  68683. * @returns the polygon mesh
  68684. */
  68685. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  68686. return MeshBuilder.CreatePolygon(name, options, scene);
  68687. };
  68688. /**
  68689. * Creates a tube mesh.
  68690. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  68691. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  68692. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  68693. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  68694. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  68695. * * 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)
  68696. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  68697. * * 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
  68698. * * 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
  68699. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68700. * * 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
  68701. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68702. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68703. * @param name defines the name of the mesh
  68704. * @param options defines the options used to create the mesh
  68705. * @param scene defines the hosting scene
  68706. * @returns the tube mesh
  68707. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68708. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  68709. */
  68710. MeshBuilder.CreateTube = function (name, options, scene) {
  68711. var path = options.path;
  68712. var instance = options.instance;
  68713. var radius = 1.0;
  68714. if (options.radius !== undefined) {
  68715. radius = options.radius;
  68716. }
  68717. else if (instance) {
  68718. radius = instance._creationDataStorage.radius;
  68719. }
  68720. var tessellation = options.tessellation || 64 | 0;
  68721. var radiusFunction = options.radiusFunction || null;
  68722. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68723. var invertUV = options.invertUV || false;
  68724. var updatable = options.updatable;
  68725. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68726. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  68727. // tube geometry
  68728. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  68729. var tangents = path3D.getTangents();
  68730. var normals = path3D.getNormals();
  68731. var distances = path3D.getDistances();
  68732. var pi2 = Math.PI * 2;
  68733. var step = pi2 / tessellation * arc;
  68734. var returnRadius = function () { return radius; };
  68735. var radiusFunctionFinal = radiusFunction || returnRadius;
  68736. var circlePath;
  68737. var rad;
  68738. var normal;
  68739. var rotated;
  68740. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68741. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68742. for (var i = 0; i < path.length; i++) {
  68743. rad = radiusFunctionFinal(i, distances[i]); // current radius
  68744. circlePath = Array(); // current circle array
  68745. normal = normals[i]; // current normal
  68746. for (var t = 0; t < tessellation; t++) {
  68747. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  68748. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  68749. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  68750. rotated.scaleInPlace(rad).addInPlace(path[i]);
  68751. circlePath[t] = rotated;
  68752. }
  68753. circlePaths[index] = circlePath;
  68754. index++;
  68755. }
  68756. // cap
  68757. var capPath = function (nbPoints, pathIndex) {
  68758. var pointCap = Array();
  68759. for (var i = 0; i < nbPoints; i++) {
  68760. pointCap.push(path[pathIndex]);
  68761. }
  68762. return pointCap;
  68763. };
  68764. switch (cap) {
  68765. case BABYLON.Mesh.NO_CAP:
  68766. break;
  68767. case BABYLON.Mesh.CAP_START:
  68768. circlePaths[0] = capPath(tessellation, 0);
  68769. circlePaths[1] = circlePaths[2].slice(0);
  68770. break;
  68771. case BABYLON.Mesh.CAP_END:
  68772. circlePaths[index] = circlePaths[index - 1].slice(0);
  68773. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68774. break;
  68775. case BABYLON.Mesh.CAP_ALL:
  68776. circlePaths[0] = capPath(tessellation, 0);
  68777. circlePaths[1] = circlePaths[2].slice(0);
  68778. circlePaths[index] = circlePaths[index - 1].slice(0);
  68779. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68780. break;
  68781. default:
  68782. break;
  68783. }
  68784. return circlePaths;
  68785. };
  68786. var path3D;
  68787. var pathArray;
  68788. if (instance) { // tube update
  68789. var storage = instance._creationDataStorage;
  68790. var arc = options.arc || storage.arc;
  68791. path3D = storage.path3D.update(path);
  68792. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  68793. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  68794. // Update mode, no need to recreate the storage.
  68795. storage.path3D = path3D;
  68796. storage.pathArray = pathArray;
  68797. storage.arc = arc;
  68798. storage.radius = radius;
  68799. return instance;
  68800. }
  68801. // tube creation
  68802. path3D = new BABYLON.Path3D(path);
  68803. var newPathArray = new Array();
  68804. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68805. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  68806. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68807. tube._creationDataStorage.pathArray = pathArray;
  68808. tube._creationDataStorage.path3D = path3D;
  68809. tube._creationDataStorage.tessellation = tessellation;
  68810. tube._creationDataStorage.cap = cap;
  68811. tube._creationDataStorage.arc = options.arc;
  68812. tube._creationDataStorage.radius = radius;
  68813. return tube;
  68814. };
  68815. /**
  68816. * Creates a polyhedron mesh
  68817. * * 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
  68818. * * The parameter `size` (positive float, default 1) sets the polygon size
  68819. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  68820. * * 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`
  68821. * * 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
  68822. * * 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)`)
  68823. * * 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
  68824. * * 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
  68825. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68826. * * 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
  68827. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68828. * @param name defines the name of the mesh
  68829. * @param options defines the options used to create the mesh
  68830. * @param scene defines the hosting scene
  68831. * @returns the polyhedron mesh
  68832. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  68833. */
  68834. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  68835. var polyhedron = new BABYLON.Mesh(name, scene);
  68836. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68837. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  68838. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  68839. vertexData.applyToMesh(polyhedron, options.updatable);
  68840. return polyhedron;
  68841. };
  68842. /**
  68843. * Creates a decal mesh.
  68844. * 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
  68845. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  68846. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  68847. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  68848. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  68849. * @param name defines the name of the mesh
  68850. * @param sourceMesh defines the mesh where the decal must be applied
  68851. * @param options defines the options used to create the mesh
  68852. * @param scene defines the hosting scene
  68853. * @returns the decal mesh
  68854. * @see http://doc.babylonjs.com/how_to/decals
  68855. */
  68856. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  68857. var indices = sourceMesh.getIndices();
  68858. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68859. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68860. var position = options.position || BABYLON.Vector3.Zero();
  68861. var normal = options.normal || BABYLON.Vector3.Up();
  68862. var size = options.size || BABYLON.Vector3.One();
  68863. var angle = options.angle || 0;
  68864. // Getting correct rotation
  68865. if (!normal) {
  68866. var target = new BABYLON.Vector3(0, 0, 1);
  68867. var camera = sourceMesh.getScene().activeCamera;
  68868. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  68869. normal = camera.globalPosition.subtract(cameraWorldTarget);
  68870. }
  68871. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  68872. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  68873. var pitch = Math.atan2(normal.y, len);
  68874. // Matrix
  68875. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  68876. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  68877. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  68878. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  68879. var vertexData = new BABYLON.VertexData();
  68880. vertexData.indices = [];
  68881. vertexData.positions = [];
  68882. vertexData.normals = [];
  68883. vertexData.uvs = [];
  68884. var currentVertexDataIndex = 0;
  68885. var extractDecalVector3 = function (indexId) {
  68886. var result = new BABYLON.PositionNormalVertex();
  68887. if (!indices || !positions || !normals) {
  68888. return result;
  68889. }
  68890. var vertexId = indices[indexId];
  68891. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  68892. // Send vector to decal local world
  68893. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  68894. // Get normal
  68895. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  68896. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  68897. return result;
  68898. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  68899. var clip = function (vertices, axis) {
  68900. if (vertices.length === 0) {
  68901. return vertices;
  68902. }
  68903. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  68904. var clipVertices = function (v0, v1) {
  68905. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  68906. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  68907. };
  68908. var result = new Array();
  68909. for (var index = 0; index < vertices.length; index += 3) {
  68910. var v1Out;
  68911. var v2Out;
  68912. var v3Out;
  68913. var total = 0;
  68914. var nV1 = null;
  68915. var nV2 = null;
  68916. var nV3 = null;
  68917. var nV4 = null;
  68918. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  68919. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  68920. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  68921. v1Out = d1 > 0;
  68922. v2Out = d2 > 0;
  68923. v3Out = d3 > 0;
  68924. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  68925. switch (total) {
  68926. case 0:
  68927. result.push(vertices[index]);
  68928. result.push(vertices[index + 1]);
  68929. result.push(vertices[index + 2]);
  68930. break;
  68931. case 1:
  68932. if (v1Out) {
  68933. nV1 = vertices[index + 1];
  68934. nV2 = vertices[index + 2];
  68935. nV3 = clipVertices(vertices[index], nV1);
  68936. nV4 = clipVertices(vertices[index], nV2);
  68937. }
  68938. if (v2Out) {
  68939. nV1 = vertices[index];
  68940. nV2 = vertices[index + 2];
  68941. nV3 = clipVertices(vertices[index + 1], nV1);
  68942. nV4 = clipVertices(vertices[index + 1], nV2);
  68943. result.push(nV3);
  68944. result.push(nV2.clone());
  68945. result.push(nV1.clone());
  68946. result.push(nV2.clone());
  68947. result.push(nV3.clone());
  68948. result.push(nV4);
  68949. break;
  68950. }
  68951. if (v3Out) {
  68952. nV1 = vertices[index];
  68953. nV2 = vertices[index + 1];
  68954. nV3 = clipVertices(vertices[index + 2], nV1);
  68955. nV4 = clipVertices(vertices[index + 2], nV2);
  68956. }
  68957. if (nV1 && nV2 && nV3 && nV4) {
  68958. result.push(nV1.clone());
  68959. result.push(nV2.clone());
  68960. result.push(nV3);
  68961. result.push(nV4);
  68962. result.push(nV3.clone());
  68963. result.push(nV2.clone());
  68964. }
  68965. break;
  68966. case 2:
  68967. if (!v1Out) {
  68968. nV1 = vertices[index].clone();
  68969. nV2 = clipVertices(nV1, vertices[index + 1]);
  68970. nV3 = clipVertices(nV1, vertices[index + 2]);
  68971. result.push(nV1);
  68972. result.push(nV2);
  68973. result.push(nV3);
  68974. }
  68975. if (!v2Out) {
  68976. nV1 = vertices[index + 1].clone();
  68977. nV2 = clipVertices(nV1, vertices[index + 2]);
  68978. nV3 = clipVertices(nV1, vertices[index]);
  68979. result.push(nV1);
  68980. result.push(nV2);
  68981. result.push(nV3);
  68982. }
  68983. if (!v3Out) {
  68984. nV1 = vertices[index + 2].clone();
  68985. nV2 = clipVertices(nV1, vertices[index]);
  68986. nV3 = clipVertices(nV1, vertices[index + 1]);
  68987. result.push(nV1);
  68988. result.push(nV2);
  68989. result.push(nV3);
  68990. }
  68991. break;
  68992. case 3:
  68993. break;
  68994. }
  68995. }
  68996. return result;
  68997. };
  68998. for (var index = 0; index < indices.length; index += 3) {
  68999. var faceVertices = new Array();
  69000. faceVertices.push(extractDecalVector3(index));
  69001. faceVertices.push(extractDecalVector3(index + 1));
  69002. faceVertices.push(extractDecalVector3(index + 2));
  69003. // Clip
  69004. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  69005. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  69006. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  69007. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  69008. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  69009. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  69010. if (faceVertices.length === 0) {
  69011. continue;
  69012. }
  69013. // Add UVs and get back to world
  69014. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  69015. var vertex = faceVertices[vIndex];
  69016. //TODO check for Int32Array | Uint32Array | Uint16Array
  69017. vertexData.indices.push(currentVertexDataIndex);
  69018. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  69019. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  69020. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  69021. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  69022. currentVertexDataIndex++;
  69023. }
  69024. }
  69025. // Return mesh
  69026. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  69027. vertexData.applyToMesh(decal);
  69028. decal.position = position.clone();
  69029. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  69030. return decal;
  69031. };
  69032. // Privates
  69033. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  69034. // extrusion geometry
  69035. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  69036. var tangents = path3D.getTangents();
  69037. var normals = path3D.getNormals();
  69038. var binormals = path3D.getBinormals();
  69039. var distances = path3D.getDistances();
  69040. var angle = 0;
  69041. var returnScale = function () { return scale !== null ? scale : 1; };
  69042. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  69043. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  69044. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  69045. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  69046. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  69047. for (var i = 0; i < curve.length; i++) {
  69048. var shapePath = new Array();
  69049. var angleStep = rotate(i, distances[i]);
  69050. var scaleRatio = scl(i, distances[i]);
  69051. for (var p = 0; p < shape.length; p++) {
  69052. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  69053. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  69054. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  69055. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  69056. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  69057. shapePath[p] = rotated;
  69058. }
  69059. shapePaths[index] = shapePath;
  69060. angle += angleStep;
  69061. index++;
  69062. }
  69063. // cap
  69064. var capPath = function (shapePath) {
  69065. var pointCap = Array();
  69066. var barycenter = BABYLON.Vector3.Zero();
  69067. var i;
  69068. for (i = 0; i < shapePath.length; i++) {
  69069. barycenter.addInPlace(shapePath[i]);
  69070. }
  69071. barycenter.scaleInPlace(1.0 / shapePath.length);
  69072. for (i = 0; i < shapePath.length; i++) {
  69073. pointCap.push(barycenter);
  69074. }
  69075. return pointCap;
  69076. };
  69077. switch (cap) {
  69078. case BABYLON.Mesh.NO_CAP:
  69079. break;
  69080. case BABYLON.Mesh.CAP_START:
  69081. shapePaths[0] = capPath(shapePaths[2]);
  69082. shapePaths[1] = shapePaths[2];
  69083. break;
  69084. case BABYLON.Mesh.CAP_END:
  69085. shapePaths[index] = shapePaths[index - 1];
  69086. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  69087. break;
  69088. case BABYLON.Mesh.CAP_ALL:
  69089. shapePaths[0] = capPath(shapePaths[2]);
  69090. shapePaths[1] = shapePaths[2];
  69091. shapePaths[index] = shapePaths[index - 1];
  69092. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  69093. break;
  69094. default:
  69095. break;
  69096. }
  69097. return shapePaths;
  69098. };
  69099. var path3D;
  69100. var pathArray;
  69101. if (instance) { // instance update
  69102. var storage = instance._creationDataStorage;
  69103. path3D = storage.path3D.update(curve);
  69104. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  69105. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  69106. return instance;
  69107. }
  69108. // extruded shape creation
  69109. path3D = new BABYLON.Path3D(curve);
  69110. var newShapePaths = new Array();
  69111. cap = (cap < 0 || cap > 3) ? 0 : cap;
  69112. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  69113. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  69114. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  69115. extrudedGeneric._creationDataStorage.path3D = path3D;
  69116. extrudedGeneric._creationDataStorage.cap = cap;
  69117. return extrudedGeneric;
  69118. };
  69119. return MeshBuilder;
  69120. }());
  69121. BABYLON.MeshBuilder = MeshBuilder;
  69122. })(BABYLON || (BABYLON = {}));
  69123. //# sourceMappingURL=babylon.meshBuilder.js.map
  69124. var BABYLON;
  69125. (function (BABYLON) {
  69126. /**
  69127. * Draco compression (https://google.github.io/draco/)
  69128. *
  69129. * This class wraps the Draco module.
  69130. *
  69131. * **Encoder**
  69132. *
  69133. * The encoder is not currently implemented.
  69134. *
  69135. * **Decoder**
  69136. *
  69137. * 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.
  69138. *
  69139. * To update the configuration, use the following code:
  69140. * ```javascript
  69141. * BABYLON.DracoCompression.Configuration = {
  69142. * decoder: {
  69143. * wasmUrl: "<url to the WebAssembly library>",
  69144. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  69145. * fallbackUrl: "<url to the fallback JavaScript library>",
  69146. * }
  69147. * };
  69148. * ```
  69149. *
  69150. * 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.
  69151. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  69152. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  69153. *
  69154. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  69155. * ```javascript
  69156. * var dracoCompression = new BABYLON.DracoCompression();
  69157. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  69158. * [BABYLON.VertexBuffer.PositionKind]: 0
  69159. * });
  69160. * ```
  69161. *
  69162. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  69163. */
  69164. var DracoCompression = /** @class */ (function () {
  69165. /**
  69166. * Constructor
  69167. */
  69168. function DracoCompression() {
  69169. }
  69170. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  69171. /**
  69172. * Returns true if the decoder is available.
  69173. */
  69174. get: function () {
  69175. if (typeof DracoDecoderModule !== "undefined") {
  69176. return true;
  69177. }
  69178. var decoder = DracoCompression.Configuration.decoder;
  69179. if (decoder) {
  69180. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69181. return true;
  69182. }
  69183. if (decoder.fallbackUrl) {
  69184. return true;
  69185. }
  69186. }
  69187. return false;
  69188. },
  69189. enumerable: true,
  69190. configurable: true
  69191. });
  69192. /**
  69193. * Stop all async operations and release resources.
  69194. */
  69195. DracoCompression.prototype.dispose = function () {
  69196. };
  69197. /**
  69198. * Decode Draco compressed mesh data to vertex data.
  69199. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  69200. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  69201. * @returns A promise that resolves with the decoded vertex data
  69202. */
  69203. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  69204. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  69205. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  69206. var module = wrappedModule.module;
  69207. var vertexData = new BABYLON.VertexData();
  69208. var buffer = new module.DecoderBuffer();
  69209. buffer.Init(dataView, dataView.byteLength);
  69210. var decoder = new module.Decoder();
  69211. var geometry;
  69212. var status;
  69213. try {
  69214. var type = decoder.GetEncodedGeometryType(buffer);
  69215. switch (type) {
  69216. case module.TRIANGULAR_MESH:
  69217. geometry = new module.Mesh();
  69218. status = decoder.DecodeBufferToMesh(buffer, geometry);
  69219. break;
  69220. case module.POINT_CLOUD:
  69221. geometry = new module.PointCloud();
  69222. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  69223. break;
  69224. default:
  69225. throw new Error("Invalid geometry type " + type);
  69226. }
  69227. if (!status.ok() || !geometry.ptr) {
  69228. throw new Error(status.error_msg());
  69229. }
  69230. var numPoints = geometry.num_points();
  69231. if (type === module.TRIANGULAR_MESH) {
  69232. var numFaces = geometry.num_faces();
  69233. var faceIndices = new module.DracoInt32Array();
  69234. try {
  69235. var indices = new Uint32Array(numFaces * 3);
  69236. for (var i = 0; i < numFaces; i++) {
  69237. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  69238. var offset = i * 3;
  69239. indices[offset + 0] = faceIndices.GetValue(0);
  69240. indices[offset + 1] = faceIndices.GetValue(1);
  69241. indices[offset + 2] = faceIndices.GetValue(2);
  69242. }
  69243. vertexData.indices = indices;
  69244. }
  69245. finally {
  69246. module.destroy(faceIndices);
  69247. }
  69248. }
  69249. for (var kind in attributes) {
  69250. var uniqueId = attributes[kind];
  69251. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  69252. var dracoData = new module.DracoFloat32Array();
  69253. try {
  69254. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  69255. var babylonData = new Float32Array(numPoints * attribute.num_components());
  69256. for (var i = 0; i < babylonData.length; i++) {
  69257. babylonData[i] = dracoData.GetValue(i);
  69258. }
  69259. vertexData.set(babylonData, kind);
  69260. }
  69261. finally {
  69262. module.destroy(dracoData);
  69263. }
  69264. }
  69265. }
  69266. finally {
  69267. if (geometry) {
  69268. module.destroy(geometry);
  69269. }
  69270. module.destroy(decoder);
  69271. module.destroy(buffer);
  69272. }
  69273. return vertexData;
  69274. });
  69275. };
  69276. DracoCompression._GetDecoderModule = function () {
  69277. if (!DracoCompression._DecoderModulePromise) {
  69278. var promise = null;
  69279. var config_1 = {};
  69280. if (typeof DracoDecoderModule !== "undefined") {
  69281. promise = Promise.resolve();
  69282. }
  69283. else {
  69284. var decoder = DracoCompression.Configuration.decoder;
  69285. if (decoder) {
  69286. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69287. promise = Promise.all([
  69288. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  69289. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  69290. config_1.wasmBinary = data;
  69291. })
  69292. ]);
  69293. }
  69294. else if (decoder.fallbackUrl) {
  69295. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  69296. }
  69297. }
  69298. }
  69299. if (!promise) {
  69300. throw new Error("Draco decoder module is not available");
  69301. }
  69302. DracoCompression._DecoderModulePromise = promise.then(function () {
  69303. return new Promise(function (resolve) {
  69304. config_1.onModuleLoaded = function (decoderModule) {
  69305. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  69306. resolve({ module: decoderModule });
  69307. };
  69308. DracoDecoderModule(config_1);
  69309. });
  69310. });
  69311. }
  69312. return DracoCompression._DecoderModulePromise;
  69313. };
  69314. DracoCompression._LoadScriptAsync = function (url) {
  69315. return new Promise(function (resolve, reject) {
  69316. BABYLON.Tools.LoadScript(url, function () {
  69317. resolve();
  69318. }, function (message) {
  69319. reject(new Error(message));
  69320. });
  69321. });
  69322. };
  69323. DracoCompression._LoadFileAsync = function (url) {
  69324. return new Promise(function (resolve, reject) {
  69325. BABYLON.Tools.LoadFile(url, function (data) {
  69326. resolve(data);
  69327. }, undefined, undefined, true, function (request, exception) {
  69328. reject(exception);
  69329. });
  69330. });
  69331. };
  69332. /**
  69333. * The configuration. Defaults to the following urls:
  69334. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  69335. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  69336. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69337. */
  69338. DracoCompression.Configuration = {
  69339. decoder: {
  69340. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  69341. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  69342. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69343. }
  69344. };
  69345. return DracoCompression;
  69346. }());
  69347. BABYLON.DracoCompression = DracoCompression;
  69348. })(BABYLON || (BABYLON = {}));
  69349. //# sourceMappingURL=babylon.dracoCompression.js.map
  69350. var BABYLON;
  69351. (function (BABYLON) {
  69352. // Sets the default audio engine to Babylon JS.
  69353. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  69354. /**
  69355. * This represents the default audio engine used in babylon.
  69356. * It is responsible to play, synchronize and analyse sounds throughout the application.
  69357. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69358. */
  69359. var AudioEngine = /** @class */ (function () {
  69360. /**
  69361. * Instantiates a new audio engine.
  69362. *
  69363. * There should be only one per page as some browsers restrict the number
  69364. * of audio contexts you can create.
  69365. * @param hostElement defines the host element where to display the mute icon if necessary
  69366. */
  69367. function AudioEngine(hostElement) {
  69368. if (hostElement === void 0) { hostElement = null; }
  69369. var _this = this;
  69370. this._audioContext = null;
  69371. this._audioContextInitialized = false;
  69372. this._muteButton = null;
  69373. /**
  69374. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  69375. */
  69376. this.canUseWebAudio = false;
  69377. /**
  69378. * Defines if Babylon should emit a warning if WebAudio is not supported.
  69379. * @ignoreNaming
  69380. */
  69381. this.WarnedWebAudioUnsupported = false;
  69382. /**
  69383. * Gets whether or not mp3 are supported by your browser.
  69384. */
  69385. this.isMP3supported = false;
  69386. /**
  69387. * Gets whether or not ogg are supported by your browser.
  69388. */
  69389. this.isOGGsupported = false;
  69390. /**
  69391. * Gets whether audio has been unlocked on the device.
  69392. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  69393. * a user interaction has happened.
  69394. */
  69395. this.unlocked = true;
  69396. /**
  69397. * Defines if the audio engine relies on a custom unlocked button.
  69398. * In this case, the embedded button will not be displayed.
  69399. */
  69400. this.useCustomUnlockedButton = false;
  69401. /**
  69402. * Event raised when audio has been unlocked on the browser.
  69403. */
  69404. this.onAudioUnlockedObservable = new BABYLON.Observable();
  69405. /**
  69406. * Event raised when audio has been locked on the browser.
  69407. */
  69408. this.onAudioLockedObservable = new BABYLON.Observable();
  69409. this._tryToRun = false;
  69410. this._onResize = function () {
  69411. _this._moveButtonToTopLeft();
  69412. };
  69413. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  69414. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  69415. this.canUseWebAudio = true;
  69416. }
  69417. var audioElem = document.createElement('audio');
  69418. this._hostElement = hostElement;
  69419. try {
  69420. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  69421. this.isMP3supported = true;
  69422. }
  69423. }
  69424. catch (e) {
  69425. // protect error during capability check.
  69426. }
  69427. try {
  69428. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  69429. this.isOGGsupported = true;
  69430. }
  69431. }
  69432. catch (e) {
  69433. // protect error during capability check.
  69434. }
  69435. }
  69436. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  69437. /**
  69438. * Gets the current AudioContext if available.
  69439. */
  69440. get: function () {
  69441. if (!this._audioContextInitialized) {
  69442. this._initializeAudioContext();
  69443. }
  69444. else {
  69445. if (!this.unlocked && !this._muteButton) {
  69446. this._displayMuteButton();
  69447. }
  69448. }
  69449. return this._audioContext;
  69450. },
  69451. enumerable: true,
  69452. configurable: true
  69453. });
  69454. /**
  69455. * Flags the audio engine in Locked state.
  69456. * This happens due to new browser policies preventing audio to autoplay.
  69457. */
  69458. AudioEngine.prototype.lock = function () {
  69459. this._triggerSuspendedState();
  69460. };
  69461. /**
  69462. * Unlocks the audio engine once a user action has been done on the dom.
  69463. * This is helpful to resume play once browser policies have been satisfied.
  69464. */
  69465. AudioEngine.prototype.unlock = function () {
  69466. this._triggerRunningState();
  69467. };
  69468. AudioEngine.prototype._resumeAudioContext = function () {
  69469. var result;
  69470. if (this._audioContext.resume) {
  69471. result = this._audioContext.resume();
  69472. }
  69473. return result || Promise.resolve();
  69474. };
  69475. AudioEngine.prototype._initializeAudioContext = function () {
  69476. try {
  69477. if (this.canUseWebAudio) {
  69478. this._audioContext = new AudioContext();
  69479. // create a global volume gain node
  69480. this.masterGain = this._audioContext.createGain();
  69481. this.masterGain.gain.value = 1;
  69482. this.masterGain.connect(this._audioContext.destination);
  69483. this._audioContextInitialized = true;
  69484. if (this._audioContext.state === "running") {
  69485. // Do not wait for the promise to unlock.
  69486. this._triggerRunningState();
  69487. }
  69488. }
  69489. }
  69490. catch (e) {
  69491. this.canUseWebAudio = false;
  69492. BABYLON.Tools.Error("Web Audio: " + e.message);
  69493. }
  69494. };
  69495. AudioEngine.prototype._triggerRunningState = function () {
  69496. var _this = this;
  69497. if (this._tryToRun) {
  69498. return;
  69499. }
  69500. this._tryToRun = true;
  69501. this._resumeAudioContext()
  69502. .then(function () {
  69503. _this._tryToRun = false;
  69504. if (_this._muteButton) {
  69505. _this._hideMuteButton();
  69506. }
  69507. }).catch(function () {
  69508. _this._tryToRun = false;
  69509. _this.unlocked = false;
  69510. });
  69511. // Notify users that the audio stack is unlocked/unmuted
  69512. this.unlocked = true;
  69513. this.onAudioUnlockedObservable.notifyObservers(this);
  69514. };
  69515. AudioEngine.prototype._triggerSuspendedState = function () {
  69516. this.unlocked = false;
  69517. this.onAudioLockedObservable.notifyObservers(this);
  69518. this._displayMuteButton();
  69519. };
  69520. AudioEngine.prototype._displayMuteButton = function () {
  69521. var _this = this;
  69522. if (this.useCustomUnlockedButton) {
  69523. return;
  69524. }
  69525. this._muteButton = document.createElement("BUTTON");
  69526. this._muteButton.className = "babylonUnmuteIcon";
  69527. this._muteButton.id = "babylonUnmuteIconBtn";
  69528. this._muteButton.title = "Unmute";
  69529. 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) }";
  69530. var style = document.createElement('style');
  69531. style.appendChild(document.createTextNode(css));
  69532. document.getElementsByTagName('head')[0].appendChild(style);
  69533. document.body.appendChild(this._muteButton);
  69534. this._moveButtonToTopLeft();
  69535. this._muteButton.addEventListener('touchend', function () {
  69536. _this._triggerRunningState();
  69537. }, true);
  69538. this._muteButton.addEventListener('click', function () {
  69539. _this._triggerRunningState();
  69540. }, true);
  69541. window.addEventListener("resize", this._onResize);
  69542. };
  69543. AudioEngine.prototype._moveButtonToTopLeft = function () {
  69544. if (this._hostElement && this._muteButton) {
  69545. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  69546. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  69547. }
  69548. };
  69549. AudioEngine.prototype._hideMuteButton = function () {
  69550. if (this._muteButton) {
  69551. document.body.removeChild(this._muteButton);
  69552. this._muteButton = null;
  69553. }
  69554. };
  69555. /**
  69556. * Destroy and release the resources associated with the audio ccontext.
  69557. */
  69558. AudioEngine.prototype.dispose = function () {
  69559. if (this.canUseWebAudio && this._audioContextInitialized) {
  69560. if (this._connectedAnalyser && this._audioContext) {
  69561. this._connectedAnalyser.stopDebugCanvas();
  69562. this._connectedAnalyser.dispose();
  69563. this.masterGain.disconnect();
  69564. this.masterGain.connect(this._audioContext.destination);
  69565. this._connectedAnalyser = null;
  69566. }
  69567. this.masterGain.gain.value = 1;
  69568. }
  69569. this.WarnedWebAudioUnsupported = false;
  69570. this._hideMuteButton();
  69571. window.removeEventListener("resize", this._onResize);
  69572. this.onAudioUnlockedObservable.clear();
  69573. this.onAudioLockedObservable.clear();
  69574. };
  69575. /**
  69576. * Gets the global volume sets on the master gain.
  69577. * @returns the global volume if set or -1 otherwise
  69578. */
  69579. AudioEngine.prototype.getGlobalVolume = function () {
  69580. if (this.canUseWebAudio && this._audioContextInitialized) {
  69581. return this.masterGain.gain.value;
  69582. }
  69583. else {
  69584. return -1;
  69585. }
  69586. };
  69587. /**
  69588. * Sets the global volume of your experience (sets on the master gain).
  69589. * @param newVolume Defines the new global volume of the application
  69590. */
  69591. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  69592. if (this.canUseWebAudio && this._audioContextInitialized) {
  69593. this.masterGain.gain.value = newVolume;
  69594. }
  69595. };
  69596. /**
  69597. * Connect the audio engine to an audio analyser allowing some amazing
  69598. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69599. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69600. * @param analyser The analyser to connect to the engine
  69601. */
  69602. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  69603. if (this._connectedAnalyser) {
  69604. this._connectedAnalyser.stopDebugCanvas();
  69605. }
  69606. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  69607. this._connectedAnalyser = analyser;
  69608. this.masterGain.disconnect();
  69609. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  69610. }
  69611. };
  69612. return AudioEngine;
  69613. }());
  69614. BABYLON.AudioEngine = AudioEngine;
  69615. })(BABYLON || (BABYLON = {}));
  69616. //# sourceMappingURL=babylon.audioEngine.js.map
  69617. var BABYLON;
  69618. (function (BABYLON) {
  69619. /**
  69620. * Defines a sound that can be played in the application.
  69621. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  69622. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69623. */
  69624. var Sound = /** @class */ (function () {
  69625. /**
  69626. * Create a sound and attach it to a scene
  69627. * @param name Name of your sound
  69628. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  69629. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  69630. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  69631. */
  69632. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  69633. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  69634. var _this = this;
  69635. /**
  69636. * Does the sound autoplay once loaded.
  69637. */
  69638. this.autoplay = false;
  69639. /**
  69640. * Does the sound loop after it finishes playing once.
  69641. */
  69642. this.loop = false;
  69643. /**
  69644. * Does the sound use a custom attenuation curve to simulate the falloff
  69645. * happening when the source gets further away from the camera.
  69646. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69647. */
  69648. this.useCustomAttenuation = false;
  69649. /**
  69650. * Is this sound currently played.
  69651. */
  69652. this.isPlaying = false;
  69653. /**
  69654. * Is this sound currently paused.
  69655. */
  69656. this.isPaused = false;
  69657. /**
  69658. * Does this sound enables spatial sound.
  69659. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69660. */
  69661. this.spatialSound = false;
  69662. /**
  69663. * Define the reference distance the sound should be heard perfectly.
  69664. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69665. */
  69666. this.refDistance = 1;
  69667. /**
  69668. * Define the roll off factor of spatial sounds.
  69669. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69670. */
  69671. this.rolloffFactor = 1;
  69672. /**
  69673. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  69674. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69675. */
  69676. this.maxDistance = 100;
  69677. /**
  69678. * Define the distance attenuation model the sound will follow.
  69679. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69680. */
  69681. this.distanceModel = "linear";
  69682. /**
  69683. * Observable event when the current playing sound finishes.
  69684. */
  69685. this.onEndedObservable = new BABYLON.Observable();
  69686. this._panningModel = "equalpower";
  69687. this._playbackRate = 1;
  69688. this._streaming = false;
  69689. this._startTime = 0;
  69690. this._startOffset = 0;
  69691. this._position = BABYLON.Vector3.Zero();
  69692. /** @hidden */
  69693. this._positionInEmitterSpace = false;
  69694. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  69695. this._volume = 1;
  69696. this._isReadyToPlay = false;
  69697. this._isDirectional = false;
  69698. // Used if you'd like to create a directional sound.
  69699. // If not set, the sound will be omnidirectional
  69700. this._coneInnerAngle = 360;
  69701. this._coneOuterAngle = 360;
  69702. this._coneOuterGain = 0;
  69703. this._isOutputConnected = false;
  69704. this._urlType = "Unknown";
  69705. this.name = name;
  69706. this._scene = scene;
  69707. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69708. if (!compo) {
  69709. compo = new BABYLON.AudioSceneComponent(scene);
  69710. scene._addComponent(compo);
  69711. }
  69712. this._readyToPlayCallback = readyToPlayCallback;
  69713. // Default custom attenuation function is a linear attenuation
  69714. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  69715. if (currentDistance < maxDistance) {
  69716. return currentVolume * (1 - currentDistance / maxDistance);
  69717. }
  69718. else {
  69719. return 0;
  69720. }
  69721. };
  69722. if (options) {
  69723. this.autoplay = options.autoplay || false;
  69724. this.loop = options.loop || false;
  69725. // if volume === 0, we need another way to check this option
  69726. if (options.volume !== undefined) {
  69727. this._volume = options.volume;
  69728. }
  69729. this.spatialSound = options.spatialSound || false;
  69730. this.maxDistance = options.maxDistance || 100;
  69731. this.useCustomAttenuation = options.useCustomAttenuation || false;
  69732. this.rolloffFactor = options.rolloffFactor || 1;
  69733. this.refDistance = options.refDistance || 1;
  69734. this.distanceModel = options.distanceModel || "linear";
  69735. this._playbackRate = options.playbackRate || 1;
  69736. this._streaming = options.streaming || false;
  69737. }
  69738. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69739. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  69740. this._soundGain.gain.value = this._volume;
  69741. this._inputAudioNode = this._soundGain;
  69742. this._outputAudioNode = this._soundGain;
  69743. if (this.spatialSound) {
  69744. this._createSpatialParameters();
  69745. }
  69746. this._scene.mainSoundTrack.AddSound(this);
  69747. var validParameter = true;
  69748. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  69749. if (urlOrArrayBuffer) {
  69750. try {
  69751. if (typeof (urlOrArrayBuffer) === "string") {
  69752. this._urlType = "String";
  69753. }
  69754. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  69755. this._urlType = "ArrayBuffer";
  69756. }
  69757. else if (urlOrArrayBuffer instanceof MediaStream) {
  69758. this._urlType = "MediaStream";
  69759. }
  69760. else if (Array.isArray(urlOrArrayBuffer)) {
  69761. this._urlType = "Array";
  69762. }
  69763. var urls = [];
  69764. var codecSupportedFound = false;
  69765. switch (this._urlType) {
  69766. case "MediaStream":
  69767. this._streaming = true;
  69768. this._isReadyToPlay = true;
  69769. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  69770. if (this.autoplay) {
  69771. this.play();
  69772. }
  69773. if (this._readyToPlayCallback) {
  69774. this._readyToPlayCallback();
  69775. }
  69776. break;
  69777. case "ArrayBuffer":
  69778. if (urlOrArrayBuffer.byteLength > 0) {
  69779. codecSupportedFound = true;
  69780. this._soundLoaded(urlOrArrayBuffer);
  69781. }
  69782. break;
  69783. case "String":
  69784. urls.push(urlOrArrayBuffer);
  69785. case "Array":
  69786. if (urls.length === 0) {
  69787. urls = urlOrArrayBuffer;
  69788. }
  69789. // If we found a supported format, we load it immediately and stop the loop
  69790. for (var i = 0; i < urls.length; i++) {
  69791. var url = urls[i];
  69792. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  69793. codecSupportedFound = true;
  69794. }
  69795. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  69796. codecSupportedFound = true;
  69797. }
  69798. if (url.indexOf(".wav", url.length - 4) !== -1) {
  69799. codecSupportedFound = true;
  69800. }
  69801. if (url.indexOf("blob:") !== -1) {
  69802. codecSupportedFound = true;
  69803. }
  69804. if (codecSupportedFound) {
  69805. // Loading sound using XHR2
  69806. if (!this._streaming) {
  69807. this._scene._loadFile(url, function (data) {
  69808. _this._soundLoaded(data);
  69809. }, undefined, true, true, function (exception) {
  69810. if (exception) {
  69811. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  69812. }
  69813. BABYLON.Tools.Error("Sound creation aborted.");
  69814. _this._scene.mainSoundTrack.RemoveSound(_this);
  69815. });
  69816. }
  69817. // Streaming sound using HTML5 Audio tag
  69818. else {
  69819. this._htmlAudioElement = new Audio(url);
  69820. this._htmlAudioElement.controls = false;
  69821. this._htmlAudioElement.loop = this.loop;
  69822. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  69823. this._htmlAudioElement.preload = "auto";
  69824. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  69825. _this._isReadyToPlay = true;
  69826. if (_this.autoplay) {
  69827. _this.play();
  69828. }
  69829. if (_this._readyToPlayCallback) {
  69830. _this._readyToPlayCallback();
  69831. }
  69832. });
  69833. document.body.appendChild(this._htmlAudioElement);
  69834. this._htmlAudioElement.load();
  69835. }
  69836. break;
  69837. }
  69838. }
  69839. break;
  69840. default:
  69841. validParameter = false;
  69842. break;
  69843. }
  69844. if (!validParameter) {
  69845. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  69846. }
  69847. else {
  69848. if (!codecSupportedFound) {
  69849. this._isReadyToPlay = true;
  69850. // Simulating a ready to play event to avoid breaking code path
  69851. if (this._readyToPlayCallback) {
  69852. window.setTimeout(function () {
  69853. if (_this._readyToPlayCallback) {
  69854. _this._readyToPlayCallback();
  69855. }
  69856. }, 1000);
  69857. }
  69858. }
  69859. }
  69860. }
  69861. catch (ex) {
  69862. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  69863. this._scene.mainSoundTrack.RemoveSound(this);
  69864. }
  69865. }
  69866. }
  69867. else {
  69868. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  69869. this._scene.mainSoundTrack.AddSound(this);
  69870. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  69871. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  69872. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  69873. }
  69874. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  69875. if (this._readyToPlayCallback) {
  69876. window.setTimeout(function () {
  69877. if (_this._readyToPlayCallback) {
  69878. _this._readyToPlayCallback();
  69879. }
  69880. }, 1000);
  69881. }
  69882. }
  69883. }
  69884. /**
  69885. * Release the sound and its associated resources
  69886. */
  69887. Sound.prototype.dispose = function () {
  69888. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69889. if (this.isPlaying) {
  69890. this.stop();
  69891. }
  69892. this._isReadyToPlay = false;
  69893. if (this.soundTrackId === -1) {
  69894. this._scene.mainSoundTrack.RemoveSound(this);
  69895. }
  69896. else if (this._scene.soundTracks) {
  69897. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  69898. }
  69899. if (this._soundGain) {
  69900. this._soundGain.disconnect();
  69901. this._soundGain = null;
  69902. }
  69903. if (this._soundPanner) {
  69904. this._soundPanner.disconnect();
  69905. this._soundPanner = null;
  69906. }
  69907. if (this._soundSource) {
  69908. this._soundSource.disconnect();
  69909. this._soundSource = null;
  69910. }
  69911. this._audioBuffer = null;
  69912. if (this._htmlAudioElement) {
  69913. this._htmlAudioElement.pause();
  69914. this._htmlAudioElement.src = "";
  69915. document.body.removeChild(this._htmlAudioElement);
  69916. }
  69917. if (this._streamingSource) {
  69918. this._streamingSource.disconnect();
  69919. }
  69920. if (this._connectedMesh && this._registerFunc) {
  69921. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69922. this._connectedMesh = null;
  69923. }
  69924. }
  69925. };
  69926. /**
  69927. * Gets if the sounds is ready to be played or not.
  69928. * @returns true if ready, otherwise false
  69929. */
  69930. Sound.prototype.isReady = function () {
  69931. return this._isReadyToPlay;
  69932. };
  69933. Sound.prototype._soundLoaded = function (audioData) {
  69934. var _this = this;
  69935. if (!BABYLON.Engine.audioEngine.audioContext) {
  69936. return;
  69937. }
  69938. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  69939. _this._audioBuffer = buffer;
  69940. _this._isReadyToPlay = true;
  69941. if (_this.autoplay) {
  69942. _this.play();
  69943. }
  69944. if (_this._readyToPlayCallback) {
  69945. _this._readyToPlayCallback();
  69946. }
  69947. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  69948. };
  69949. /**
  69950. * Sets the data of the sound from an audiobuffer
  69951. * @param audioBuffer The audioBuffer containing the data
  69952. */
  69953. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  69954. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69955. this._audioBuffer = audioBuffer;
  69956. this._isReadyToPlay = true;
  69957. }
  69958. };
  69959. /**
  69960. * Updates the current sounds options such as maxdistance, loop...
  69961. * @param options A JSON object containing values named as the object properties
  69962. */
  69963. Sound.prototype.updateOptions = function (options) {
  69964. if (options) {
  69965. this.loop = options.loop || this.loop;
  69966. this.maxDistance = options.maxDistance || this.maxDistance;
  69967. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  69968. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  69969. this.refDistance = options.refDistance || this.refDistance;
  69970. this.distanceModel = options.distanceModel || this.distanceModel;
  69971. this._playbackRate = options.playbackRate || this._playbackRate;
  69972. this._updateSpatialParameters();
  69973. if (this.isPlaying) {
  69974. if (this._streaming && this._htmlAudioElement) {
  69975. this._htmlAudioElement.playbackRate = this._playbackRate;
  69976. }
  69977. else {
  69978. if (this._soundSource) {
  69979. this._soundSource.playbackRate.value = this._playbackRate;
  69980. }
  69981. }
  69982. }
  69983. }
  69984. };
  69985. Sound.prototype._createSpatialParameters = function () {
  69986. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69987. if (this._scene.headphone) {
  69988. this._panningModel = "HRTF";
  69989. }
  69990. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  69991. this._updateSpatialParameters();
  69992. this._soundPanner.connect(this._outputAudioNode);
  69993. this._inputAudioNode = this._soundPanner;
  69994. }
  69995. };
  69996. Sound.prototype._updateSpatialParameters = function () {
  69997. if (this.spatialSound && this._soundPanner) {
  69998. if (this.useCustomAttenuation) {
  69999. // Tricks to disable in a way embedded Web Audio attenuation
  70000. this._soundPanner.distanceModel = "linear";
  70001. this._soundPanner.maxDistance = Number.MAX_VALUE;
  70002. this._soundPanner.refDistance = 1;
  70003. this._soundPanner.rolloffFactor = 1;
  70004. this._soundPanner.panningModel = this._panningModel;
  70005. }
  70006. else {
  70007. this._soundPanner.distanceModel = this.distanceModel;
  70008. this._soundPanner.maxDistance = this.maxDistance;
  70009. this._soundPanner.refDistance = this.refDistance;
  70010. this._soundPanner.rolloffFactor = this.rolloffFactor;
  70011. this._soundPanner.panningModel = this._panningModel;
  70012. }
  70013. }
  70014. };
  70015. /**
  70016. * Switch the panning model to HRTF:
  70017. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70018. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70019. */
  70020. Sound.prototype.switchPanningModelToHRTF = function () {
  70021. this._panningModel = "HRTF";
  70022. this._switchPanningModel();
  70023. };
  70024. /**
  70025. * Switch the panning model to Equal Power:
  70026. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70027. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70028. */
  70029. Sound.prototype.switchPanningModelToEqualPower = function () {
  70030. this._panningModel = "equalpower";
  70031. this._switchPanningModel();
  70032. };
  70033. Sound.prototype._switchPanningModel = function () {
  70034. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70035. this._soundPanner.panningModel = this._panningModel;
  70036. }
  70037. };
  70038. /**
  70039. * Connect this sound to a sound track audio node like gain...
  70040. * @param soundTrackAudioNode the sound track audio node to connect to
  70041. */
  70042. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  70043. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70044. if (this._isOutputConnected) {
  70045. this._outputAudioNode.disconnect();
  70046. }
  70047. this._outputAudioNode.connect(soundTrackAudioNode);
  70048. this._isOutputConnected = true;
  70049. }
  70050. };
  70051. /**
  70052. * Transform this sound into a directional source
  70053. * @param coneInnerAngle Size of the inner cone in degree
  70054. * @param coneOuterAngle Size of the outer cone in degree
  70055. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  70056. */
  70057. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  70058. if (coneOuterAngle < coneInnerAngle) {
  70059. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  70060. return;
  70061. }
  70062. this._coneInnerAngle = coneInnerAngle;
  70063. this._coneOuterAngle = coneOuterAngle;
  70064. this._coneOuterGain = coneOuterGain;
  70065. this._isDirectional = true;
  70066. if (this.isPlaying && this.loop) {
  70067. this.stop();
  70068. this.play();
  70069. }
  70070. };
  70071. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  70072. /**
  70073. * Gets or sets the inner angle for the directional cone.
  70074. */
  70075. get: function () {
  70076. return this._coneInnerAngle;
  70077. },
  70078. /**
  70079. * Gets or sets the inner angle for the directional cone.
  70080. */
  70081. set: function (value) {
  70082. if (value != this._coneInnerAngle) {
  70083. if (this._coneOuterAngle < value) {
  70084. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70085. return;
  70086. }
  70087. this._coneInnerAngle = value;
  70088. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70089. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  70090. }
  70091. }
  70092. },
  70093. enumerable: true,
  70094. configurable: true
  70095. });
  70096. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  70097. /**
  70098. * Gets or sets the outer angle for the directional cone.
  70099. */
  70100. get: function () {
  70101. return this._coneOuterAngle;
  70102. },
  70103. /**
  70104. * Gets or sets the outer angle for the directional cone.
  70105. */
  70106. set: function (value) {
  70107. if (value != this._coneOuterAngle) {
  70108. if (value < this._coneInnerAngle) {
  70109. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70110. return;
  70111. }
  70112. this._coneOuterAngle = value;
  70113. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70114. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  70115. }
  70116. }
  70117. },
  70118. enumerable: true,
  70119. configurable: true
  70120. });
  70121. /**
  70122. * Sets the position of the emitter if spatial sound is enabled
  70123. * @param newPosition Defines the new posisiton
  70124. */
  70125. Sound.prototype.setPosition = function (newPosition) {
  70126. this._position = newPosition;
  70127. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  70128. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  70129. }
  70130. };
  70131. /**
  70132. * Sets the local direction of the emitter if spatial sound is enabled
  70133. * @param newLocalDirection Defines the new local direction
  70134. */
  70135. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  70136. this._localDirection = newLocalDirection;
  70137. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  70138. this._updateDirection();
  70139. }
  70140. };
  70141. Sound.prototype._updateDirection = function () {
  70142. if (!this._connectedMesh || !this._soundPanner) {
  70143. return;
  70144. }
  70145. var mat = this._connectedMesh.getWorldMatrix();
  70146. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  70147. direction.normalize();
  70148. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  70149. };
  70150. /** @hidden */
  70151. Sound.prototype.updateDistanceFromListener = function () {
  70152. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  70153. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  70154. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  70155. }
  70156. };
  70157. /**
  70158. * Sets a new custom attenuation function for the sound.
  70159. * @param callback Defines the function used for the attenuation
  70160. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  70161. */
  70162. Sound.prototype.setAttenuationFunction = function (callback) {
  70163. this._customAttenuationFunction = callback;
  70164. };
  70165. /**
  70166. * Play the sound
  70167. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  70168. * @param offset (optional) Start the sound setting it at a specific time
  70169. */
  70170. Sound.prototype.play = function (time, offset) {
  70171. var _this = this;
  70172. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  70173. try {
  70174. if (this._startOffset < 0) {
  70175. time = -this._startOffset;
  70176. this._startOffset = 0;
  70177. }
  70178. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70179. if (!this._soundSource || !this._streamingSource) {
  70180. if (this.spatialSound && this._soundPanner) {
  70181. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  70182. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  70183. }
  70184. if (this._isDirectional) {
  70185. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  70186. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  70187. this._soundPanner.coneOuterGain = this._coneOuterGain;
  70188. if (this._connectedMesh) {
  70189. this._updateDirection();
  70190. }
  70191. else {
  70192. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  70193. }
  70194. }
  70195. }
  70196. }
  70197. if (this._streaming) {
  70198. if (!this._streamingSource) {
  70199. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  70200. this._htmlAudioElement.onended = function () { _this._onended(); };
  70201. this._htmlAudioElement.playbackRate = this._playbackRate;
  70202. }
  70203. this._streamingSource.disconnect();
  70204. this._streamingSource.connect(this._inputAudioNode);
  70205. if (this._htmlAudioElement) {
  70206. // required to manage properly the new suspended default state of Chrome
  70207. // When the option 'streaming: true' is used, we need first to wait for
  70208. // the audio engine to be unlocked by a user gesture before trying to play
  70209. // an HTML Audio elememt
  70210. var tryToPlay = function () {
  70211. if (BABYLON.Engine.audioEngine.unlocked) {
  70212. var playPromise = _this._htmlAudioElement.play();
  70213. // In browsers that don’t yet support this functionality,
  70214. // playPromise won’t be defined.
  70215. if (playPromise !== undefined) {
  70216. playPromise.catch(function (error) {
  70217. // Automatic playback failed.
  70218. // Waiting for the audio engine to be unlocked by user click on unmute
  70219. BABYLON.Engine.audioEngine.lock();
  70220. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  70221. });
  70222. }
  70223. }
  70224. else {
  70225. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  70226. }
  70227. };
  70228. tryToPlay();
  70229. }
  70230. }
  70231. else {
  70232. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  70233. this._soundSource.buffer = this._audioBuffer;
  70234. this._soundSource.connect(this._inputAudioNode);
  70235. this._soundSource.loop = this.loop;
  70236. this._soundSource.playbackRate.value = this._playbackRate;
  70237. this._soundSource.onended = function () { _this._onended(); };
  70238. if (this._soundSource.buffer) {
  70239. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  70240. }
  70241. }
  70242. this._startTime = startTime;
  70243. this.isPlaying = true;
  70244. this.isPaused = false;
  70245. }
  70246. catch (ex) {
  70247. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  70248. }
  70249. }
  70250. };
  70251. Sound.prototype._onended = function () {
  70252. this.isPlaying = false;
  70253. if (this.onended) {
  70254. this.onended();
  70255. }
  70256. this.onEndedObservable.notifyObservers(this);
  70257. };
  70258. /**
  70259. * Stop the sound
  70260. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  70261. */
  70262. Sound.prototype.stop = function (time) {
  70263. if (this.isPlaying) {
  70264. if (this._streaming) {
  70265. if (this._htmlAudioElement) {
  70266. this._htmlAudioElement.pause();
  70267. // Test needed for Firefox or it will generate an Invalid State Error
  70268. if (this._htmlAudioElement.currentTime > 0) {
  70269. this._htmlAudioElement.currentTime = 0;
  70270. }
  70271. }
  70272. else {
  70273. this._streamingSource.disconnect();
  70274. }
  70275. }
  70276. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  70277. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70278. this._soundSource.stop(stopTime);
  70279. this._soundSource.onended = function () { };
  70280. if (!this.isPaused) {
  70281. this._startOffset = 0;
  70282. }
  70283. }
  70284. this.isPlaying = false;
  70285. }
  70286. };
  70287. /**
  70288. * Put the sound in pause
  70289. */
  70290. Sound.prototype.pause = function () {
  70291. if (this.isPlaying) {
  70292. this.isPaused = true;
  70293. if (this._streaming) {
  70294. if (this._htmlAudioElement) {
  70295. this._htmlAudioElement.pause();
  70296. }
  70297. else {
  70298. this._streamingSource.disconnect();
  70299. }
  70300. }
  70301. else if (BABYLON.Engine.audioEngine.audioContext) {
  70302. this.stop(0);
  70303. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  70304. }
  70305. }
  70306. };
  70307. /**
  70308. * Sets a dedicated volume for this sounds
  70309. * @param newVolume Define the new volume of the sound
  70310. * @param time Define in how long the sound should be at this value
  70311. */
  70312. Sound.prototype.setVolume = function (newVolume, time) {
  70313. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  70314. if (time && BABYLON.Engine.audioEngine.audioContext) {
  70315. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  70316. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  70317. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  70318. }
  70319. else {
  70320. this._soundGain.gain.value = newVolume;
  70321. }
  70322. }
  70323. this._volume = newVolume;
  70324. };
  70325. /**
  70326. * Set the sound play back rate
  70327. * @param newPlaybackRate Define the playback rate the sound should be played at
  70328. */
  70329. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  70330. this._playbackRate = newPlaybackRate;
  70331. if (this.isPlaying) {
  70332. if (this._streaming && this._htmlAudioElement) {
  70333. this._htmlAudioElement.playbackRate = this._playbackRate;
  70334. }
  70335. else if (this._soundSource) {
  70336. this._soundSource.playbackRate.value = this._playbackRate;
  70337. }
  70338. }
  70339. };
  70340. /**
  70341. * Gets the volume of the sound.
  70342. * @returns the volume of the sound
  70343. */
  70344. Sound.prototype.getVolume = function () {
  70345. return this._volume;
  70346. };
  70347. /**
  70348. * Attach the sound to a dedicated mesh
  70349. * @param meshToConnectTo The mesh to connect the sound with
  70350. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70351. */
  70352. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  70353. var _this = this;
  70354. if (this._connectedMesh && this._registerFunc) {
  70355. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70356. this._registerFunc = null;
  70357. }
  70358. this._connectedMesh = meshToConnectTo;
  70359. if (!this.spatialSound) {
  70360. this.spatialSound = true;
  70361. this._createSpatialParameters();
  70362. if (this.isPlaying && this.loop) {
  70363. this.stop();
  70364. this.play();
  70365. }
  70366. }
  70367. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  70368. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  70369. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  70370. };
  70371. /**
  70372. * Detach the sound from the previously attached mesh
  70373. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70374. */
  70375. Sound.prototype.detachFromMesh = function () {
  70376. if (this._connectedMesh && this._registerFunc) {
  70377. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70378. this._registerFunc = null;
  70379. this._connectedMesh = null;
  70380. }
  70381. };
  70382. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  70383. if (!node.getBoundingInfo) {
  70384. return;
  70385. }
  70386. var mesh = node;
  70387. if (this._positionInEmitterSpace) {
  70388. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  70389. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  70390. }
  70391. else {
  70392. var boundingInfo = mesh.getBoundingInfo();
  70393. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  70394. }
  70395. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  70396. this._updateDirection();
  70397. }
  70398. };
  70399. /**
  70400. * Clone the current sound in the scene.
  70401. * @returns the new sound clone
  70402. */
  70403. Sound.prototype.clone = function () {
  70404. var _this = this;
  70405. if (!this._streaming) {
  70406. var setBufferAndRun = function () {
  70407. if (_this._isReadyToPlay) {
  70408. clonedSound._audioBuffer = _this.getAudioBuffer();
  70409. clonedSound._isReadyToPlay = true;
  70410. if (clonedSound.autoplay) {
  70411. clonedSound.play();
  70412. }
  70413. }
  70414. else {
  70415. window.setTimeout(setBufferAndRun, 300);
  70416. }
  70417. };
  70418. var currentOptions = {
  70419. autoplay: this.autoplay, loop: this.loop,
  70420. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  70421. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  70422. refDistance: this.refDistance, distanceModel: this.distanceModel
  70423. };
  70424. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  70425. if (this.useCustomAttenuation) {
  70426. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  70427. }
  70428. clonedSound.setPosition(this._position);
  70429. clonedSound.setPlaybackRate(this._playbackRate);
  70430. setBufferAndRun();
  70431. return clonedSound;
  70432. }
  70433. // Can't clone a streaming sound
  70434. else {
  70435. return null;
  70436. }
  70437. };
  70438. /**
  70439. * Gets the current underlying audio buffer containing the data
  70440. * @returns the audio buffer
  70441. */
  70442. Sound.prototype.getAudioBuffer = function () {
  70443. return this._audioBuffer;
  70444. };
  70445. /**
  70446. * Serializes the Sound in a JSON representation
  70447. * @returns the JSON representation of the sound
  70448. */
  70449. Sound.prototype.serialize = function () {
  70450. var serializationObject = {
  70451. name: this.name,
  70452. url: this.name,
  70453. autoplay: this.autoplay,
  70454. loop: this.loop,
  70455. volume: this._volume,
  70456. spatialSound: this.spatialSound,
  70457. maxDistance: this.maxDistance,
  70458. rolloffFactor: this.rolloffFactor,
  70459. refDistance: this.refDistance,
  70460. distanceModel: this.distanceModel,
  70461. playbackRate: this._playbackRate,
  70462. panningModel: this._panningModel,
  70463. soundTrackId: this.soundTrackId
  70464. };
  70465. if (this.spatialSound) {
  70466. if (this._connectedMesh) {
  70467. serializationObject.connectedMeshId = this._connectedMesh.id;
  70468. }
  70469. serializationObject.position = this._position.asArray();
  70470. serializationObject.refDistance = this.refDistance;
  70471. serializationObject.distanceModel = this.distanceModel;
  70472. serializationObject.isDirectional = this._isDirectional;
  70473. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  70474. serializationObject.coneInnerAngle = this._coneInnerAngle;
  70475. serializationObject.coneOuterAngle = this._coneOuterAngle;
  70476. serializationObject.coneOuterGain = this._coneOuterGain;
  70477. }
  70478. return serializationObject;
  70479. };
  70480. /**
  70481. * Parse a JSON representation of a sound to innstantiate in a given scene
  70482. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  70483. * @param scene Define the scene the new parsed sound should be created in
  70484. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  70485. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  70486. * @returns the newly parsed sound
  70487. */
  70488. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  70489. var soundName = parsedSound.name;
  70490. var soundUrl;
  70491. if (parsedSound.url) {
  70492. soundUrl = rootUrl + parsedSound.url;
  70493. }
  70494. else {
  70495. soundUrl = rootUrl + soundName;
  70496. }
  70497. var options = {
  70498. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  70499. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  70500. rolloffFactor: parsedSound.rolloffFactor,
  70501. refDistance: parsedSound.refDistance,
  70502. distanceModel: parsedSound.distanceModel,
  70503. playbackRate: parsedSound.playbackRate
  70504. };
  70505. var newSound;
  70506. if (!sourceSound) {
  70507. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  70508. scene._addPendingData(newSound);
  70509. }
  70510. else {
  70511. var setBufferAndRun = function () {
  70512. if (sourceSound._isReadyToPlay) {
  70513. newSound._audioBuffer = sourceSound.getAudioBuffer();
  70514. newSound._isReadyToPlay = true;
  70515. if (newSound.autoplay) {
  70516. newSound.play();
  70517. }
  70518. }
  70519. else {
  70520. window.setTimeout(setBufferAndRun, 300);
  70521. }
  70522. };
  70523. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  70524. setBufferAndRun();
  70525. }
  70526. if (parsedSound.position) {
  70527. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  70528. newSound.setPosition(soundPosition);
  70529. }
  70530. if (parsedSound.isDirectional) {
  70531. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  70532. if (parsedSound.localDirectionToMesh) {
  70533. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  70534. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  70535. }
  70536. }
  70537. if (parsedSound.connectedMeshId) {
  70538. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  70539. if (connectedMesh) {
  70540. newSound.attachToMesh(connectedMesh);
  70541. }
  70542. }
  70543. return newSound;
  70544. };
  70545. return Sound;
  70546. }());
  70547. BABYLON.Sound = Sound;
  70548. })(BABYLON || (BABYLON = {}));
  70549. //# sourceMappingURL=babylon.sound.js.map
  70550. var BABYLON;
  70551. (function (BABYLON) {
  70552. /**
  70553. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  70554. * It will be also used in a future release to apply effects on a specific track.
  70555. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70556. */
  70557. var SoundTrack = /** @class */ (function () {
  70558. /**
  70559. * Creates a new sound track.
  70560. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70561. * @param scene Define the scene the sound track belongs to
  70562. * @param options
  70563. */
  70564. function SoundTrack(scene, options) {
  70565. if (options === void 0) { options = {}; }
  70566. /**
  70567. * The unique identifier of the sound track in the scene.
  70568. */
  70569. this.id = -1;
  70570. this._isMainTrack = false;
  70571. this._isInitialized = false;
  70572. this._scene = scene;
  70573. this.soundCollection = new Array();
  70574. this._options = options;
  70575. if (!this._isMainTrack && this._scene.soundTracks) {
  70576. this._scene.soundTracks.push(this);
  70577. this.id = this._scene.soundTracks.length - 1;
  70578. }
  70579. }
  70580. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  70581. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70582. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  70583. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  70584. if (this._options) {
  70585. if (this._options.volume) {
  70586. this._outputAudioNode.gain.value = this._options.volume;
  70587. }
  70588. if (this._options.mainTrack) {
  70589. this._isMainTrack = this._options.mainTrack;
  70590. }
  70591. }
  70592. this._isInitialized = true;
  70593. }
  70594. };
  70595. /**
  70596. * Release the sound track and its associated resources
  70597. */
  70598. SoundTrack.prototype.dispose = function () {
  70599. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  70600. if (this._connectedAnalyser) {
  70601. this._connectedAnalyser.stopDebugCanvas();
  70602. }
  70603. while (this.soundCollection.length) {
  70604. this.soundCollection[0].dispose();
  70605. }
  70606. if (this._outputAudioNode) {
  70607. this._outputAudioNode.disconnect();
  70608. }
  70609. this._outputAudioNode = null;
  70610. }
  70611. };
  70612. /**
  70613. * Adds a sound to this sound track
  70614. * @param sound define the cound to add
  70615. * @ignoreNaming
  70616. */
  70617. SoundTrack.prototype.AddSound = function (sound) {
  70618. if (!this._isInitialized) {
  70619. this._initializeSoundTrackAudioGraph();
  70620. }
  70621. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70622. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  70623. }
  70624. if (sound.soundTrackId) {
  70625. if (sound.soundTrackId === -1) {
  70626. this._scene.mainSoundTrack.RemoveSound(sound);
  70627. }
  70628. else if (this._scene.soundTracks) {
  70629. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  70630. }
  70631. }
  70632. this.soundCollection.push(sound);
  70633. sound.soundTrackId = this.id;
  70634. };
  70635. /**
  70636. * Removes a sound to this sound track
  70637. * @param sound define the cound to remove
  70638. * @ignoreNaming
  70639. */
  70640. SoundTrack.prototype.RemoveSound = function (sound) {
  70641. var index = this.soundCollection.indexOf(sound);
  70642. if (index !== -1) {
  70643. this.soundCollection.splice(index, 1);
  70644. }
  70645. };
  70646. /**
  70647. * Set a global volume for the full sound track.
  70648. * @param newVolume Define the new volume of the sound track
  70649. */
  70650. SoundTrack.prototype.setVolume = function (newVolume) {
  70651. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70652. this._outputAudioNode.gain.value = newVolume;
  70653. }
  70654. };
  70655. /**
  70656. * Switch the panning model to HRTF:
  70657. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70658. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70659. */
  70660. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  70661. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70662. for (var i = 0; i < this.soundCollection.length; i++) {
  70663. this.soundCollection[i].switchPanningModelToHRTF();
  70664. }
  70665. }
  70666. };
  70667. /**
  70668. * Switch the panning model to Equal Power:
  70669. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70670. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70671. */
  70672. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  70673. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70674. for (var i = 0; i < this.soundCollection.length; i++) {
  70675. this.soundCollection[i].switchPanningModelToEqualPower();
  70676. }
  70677. }
  70678. };
  70679. /**
  70680. * Connect the sound track to an audio analyser allowing some amazing
  70681. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70682. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70683. * @param analyser The analyser to connect to the engine
  70684. */
  70685. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  70686. if (this._connectedAnalyser) {
  70687. this._connectedAnalyser.stopDebugCanvas();
  70688. }
  70689. this._connectedAnalyser = analyser;
  70690. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70691. this._outputAudioNode.disconnect();
  70692. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  70693. }
  70694. };
  70695. return SoundTrack;
  70696. }());
  70697. BABYLON.SoundTrack = SoundTrack;
  70698. })(BABYLON || (BABYLON = {}));
  70699. //# sourceMappingURL=babylon.soundtrack.js.map
  70700. var BABYLON;
  70701. (function (BABYLON) {
  70702. /**
  70703. * Class used to work with sound analyzer using fast fourier transform (FFT)
  70704. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70705. */
  70706. var Analyser = /** @class */ (function () {
  70707. /**
  70708. * Creates a new analyser
  70709. * @param scene defines hosting scene
  70710. */
  70711. function Analyser(scene) {
  70712. /**
  70713. * Gets or sets the smoothing
  70714. * @ignorenaming
  70715. */
  70716. this.SMOOTHING = 0.75;
  70717. /**
  70718. * Gets or sets the FFT table size
  70719. * @ignorenaming
  70720. */
  70721. this.FFT_SIZE = 512;
  70722. /**
  70723. * Gets or sets the bar graph amplitude
  70724. * @ignorenaming
  70725. */
  70726. this.BARGRAPHAMPLITUDE = 256;
  70727. /**
  70728. * Gets or sets the position of the debug canvas
  70729. * @ignorenaming
  70730. */
  70731. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  70732. /**
  70733. * Gets or sets the debug canvas size
  70734. * @ignorenaming
  70735. */
  70736. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  70737. this._scene = scene;
  70738. this._audioEngine = BABYLON.Engine.audioEngine;
  70739. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  70740. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  70741. this._webAudioAnalyser.minDecibels = -140;
  70742. this._webAudioAnalyser.maxDecibels = 0;
  70743. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70744. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70745. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  70746. }
  70747. }
  70748. /**
  70749. * Get the number of data values you will have to play with for the visualization
  70750. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  70751. * @returns a number
  70752. */
  70753. Analyser.prototype.getFrequencyBinCount = function () {
  70754. if (this._audioEngine.canUseWebAudio) {
  70755. return this._webAudioAnalyser.frequencyBinCount;
  70756. }
  70757. else {
  70758. return 0;
  70759. }
  70760. };
  70761. /**
  70762. * Gets the current frequency data as a byte array
  70763. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70764. * @returns a Uint8Array
  70765. */
  70766. Analyser.prototype.getByteFrequencyData = function () {
  70767. if (this._audioEngine.canUseWebAudio) {
  70768. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70769. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70770. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  70771. }
  70772. return this._byteFreqs;
  70773. };
  70774. /**
  70775. * Gets the current waveform as a byte array
  70776. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  70777. * @returns a Uint8Array
  70778. */
  70779. Analyser.prototype.getByteTimeDomainData = function () {
  70780. if (this._audioEngine.canUseWebAudio) {
  70781. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70782. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70783. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  70784. }
  70785. return this._byteTime;
  70786. };
  70787. /**
  70788. * Gets the current frequency data as a float array
  70789. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70790. * @returns a Float32Array
  70791. */
  70792. Analyser.prototype.getFloatFrequencyData = function () {
  70793. if (this._audioEngine.canUseWebAudio) {
  70794. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70795. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70796. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  70797. }
  70798. return this._floatFreqs;
  70799. };
  70800. /**
  70801. * Renders the debug canvas
  70802. */
  70803. Analyser.prototype.drawDebugCanvas = function () {
  70804. var _this = this;
  70805. if (this._audioEngine.canUseWebAudio) {
  70806. if (!this._debugCanvas) {
  70807. this._debugCanvas = document.createElement("canvas");
  70808. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  70809. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  70810. this._debugCanvas.style.position = "absolute";
  70811. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  70812. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  70813. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  70814. document.body.appendChild(this._debugCanvas);
  70815. this._registerFunc = function () {
  70816. _this.drawDebugCanvas();
  70817. };
  70818. this._scene.registerBeforeRender(this._registerFunc);
  70819. }
  70820. if (this._registerFunc && this._debugCanvasContext) {
  70821. var workingArray = this.getByteFrequencyData();
  70822. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  70823. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  70824. // Draw the frequency domain chart.
  70825. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  70826. var value = workingArray[i];
  70827. var percent = value / this.BARGRAPHAMPLITUDE;
  70828. var height = this.DEBUGCANVASSIZE.height * percent;
  70829. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  70830. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  70831. var hue = i / this.getFrequencyBinCount() * 360;
  70832. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  70833. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  70834. }
  70835. }
  70836. }
  70837. };
  70838. /**
  70839. * Stops rendering the debug canvas and removes it
  70840. */
  70841. Analyser.prototype.stopDebugCanvas = function () {
  70842. if (this._debugCanvas) {
  70843. if (this._registerFunc) {
  70844. this._scene.unregisterBeforeRender(this._registerFunc);
  70845. this._registerFunc = null;
  70846. }
  70847. document.body.removeChild(this._debugCanvas);
  70848. this._debugCanvas = null;
  70849. this._debugCanvasContext = null;
  70850. }
  70851. };
  70852. /**
  70853. * Connects two audio nodes
  70854. * @param inputAudioNode defines first node to connect
  70855. * @param outputAudioNode defines second node to connect
  70856. */
  70857. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  70858. if (this._audioEngine.canUseWebAudio) {
  70859. inputAudioNode.connect(this._webAudioAnalyser);
  70860. this._webAudioAnalyser.connect(outputAudioNode);
  70861. }
  70862. };
  70863. /**
  70864. * Releases all associated resources
  70865. */
  70866. Analyser.prototype.dispose = function () {
  70867. if (this._audioEngine.canUseWebAudio) {
  70868. this._webAudioAnalyser.disconnect();
  70869. }
  70870. };
  70871. return Analyser;
  70872. }());
  70873. BABYLON.Analyser = Analyser;
  70874. })(BABYLON || (BABYLON = {}));
  70875. //# sourceMappingURL=babylon.analyser.js.map
  70876. var BABYLON;
  70877. (function (BABYLON) {
  70878. /**
  70879. * Wraps one or more Sound objects and selects one with random weight for playback.
  70880. */
  70881. var WeightedSound = /** @class */ (function () {
  70882. /**
  70883. * Creates a new WeightedSound from the list of sounds given.
  70884. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  70885. * @param sounds Array of Sounds that will be selected from.
  70886. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  70887. */
  70888. function WeightedSound(loop, sounds, weights) {
  70889. var _this = this;
  70890. /** When true a Sound will be selected and played when the current playing Sound completes. */
  70891. this.loop = false;
  70892. this._coneInnerAngle = 360;
  70893. this._coneOuterAngle = 360;
  70894. this._volume = 1;
  70895. /** A Sound is currently playing. */
  70896. this.isPlaying = false;
  70897. /** A Sound is currently paused. */
  70898. this.isPaused = false;
  70899. this._sounds = [];
  70900. this._weights = [];
  70901. if (sounds.length !== weights.length) {
  70902. throw new Error('Sounds length does not equal weights length');
  70903. }
  70904. this.loop = loop;
  70905. this._weights = weights;
  70906. // Normalize the weights
  70907. var weightSum = 0;
  70908. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  70909. var weight = weights_1[_i];
  70910. weightSum += weight;
  70911. }
  70912. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  70913. for (var i = 0; i < this._weights.length; i++) {
  70914. this._weights[i] *= invWeightSum;
  70915. }
  70916. this._sounds = sounds;
  70917. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  70918. var sound = _b[_a];
  70919. sound.onEndedObservable.add(function () { _this._onended(); });
  70920. }
  70921. }
  70922. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  70923. /**
  70924. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  70925. */
  70926. get: function () {
  70927. return this._coneInnerAngle;
  70928. },
  70929. /**
  70930. * The size of cone in degress for a directional sound in which there will be no attenuation.
  70931. */
  70932. set: function (value) {
  70933. if (value !== this._coneInnerAngle) {
  70934. if (this._coneOuterAngle < value) {
  70935. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70936. return;
  70937. }
  70938. this._coneInnerAngle = value;
  70939. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70940. var sound = _a[_i];
  70941. sound.directionalConeInnerAngle = value;
  70942. }
  70943. }
  70944. },
  70945. enumerable: true,
  70946. configurable: true
  70947. });
  70948. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  70949. /**
  70950. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70951. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70952. */
  70953. get: function () {
  70954. return this._coneOuterAngle;
  70955. },
  70956. /**
  70957. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70958. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70959. */
  70960. set: function (value) {
  70961. if (value !== this._coneOuterAngle) {
  70962. if (value < this._coneInnerAngle) {
  70963. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70964. return;
  70965. }
  70966. this._coneOuterAngle = value;
  70967. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70968. var sound = _a[_i];
  70969. sound.directionalConeOuterAngle = value;
  70970. }
  70971. }
  70972. },
  70973. enumerable: true,
  70974. configurable: true
  70975. });
  70976. Object.defineProperty(WeightedSound.prototype, "volume", {
  70977. /**
  70978. * Playback volume.
  70979. */
  70980. get: function () {
  70981. return this._volume;
  70982. },
  70983. /**
  70984. * Playback volume.
  70985. */
  70986. set: function (value) {
  70987. if (value !== this._volume) {
  70988. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70989. var sound = _a[_i];
  70990. sound.setVolume(value);
  70991. }
  70992. }
  70993. },
  70994. enumerable: true,
  70995. configurable: true
  70996. });
  70997. WeightedSound.prototype._onended = function () {
  70998. if (this._currentIndex !== undefined) {
  70999. this._sounds[this._currentIndex].autoplay = false;
  71000. }
  71001. if (this.loop && this.isPlaying) {
  71002. this.play();
  71003. }
  71004. else {
  71005. this.isPlaying = false;
  71006. }
  71007. };
  71008. /**
  71009. * Suspend playback
  71010. */
  71011. WeightedSound.prototype.pause = function () {
  71012. this.isPaused = true;
  71013. if (this._currentIndex !== undefined) {
  71014. this._sounds[this._currentIndex].pause();
  71015. }
  71016. };
  71017. /**
  71018. * Stop playback
  71019. */
  71020. WeightedSound.prototype.stop = function () {
  71021. this.isPlaying = false;
  71022. if (this._currentIndex !== undefined) {
  71023. this._sounds[this._currentIndex].stop();
  71024. }
  71025. };
  71026. /**
  71027. * Start playback.
  71028. * @param startOffset Position the clip head at a specific time in seconds.
  71029. */
  71030. WeightedSound.prototype.play = function (startOffset) {
  71031. if (!this.isPaused) {
  71032. this.stop();
  71033. var randomValue = Math.random();
  71034. var total = 0;
  71035. for (var i = 0; i < this._weights.length; i++) {
  71036. total += this._weights[i];
  71037. if (randomValue <= total) {
  71038. this._currentIndex = i;
  71039. break;
  71040. }
  71041. }
  71042. }
  71043. var sound = this._sounds[this._currentIndex];
  71044. if (sound.isReady()) {
  71045. sound.play(0, this.isPaused ? undefined : startOffset);
  71046. }
  71047. else {
  71048. sound.autoplay = true;
  71049. }
  71050. this.isPlaying = true;
  71051. this.isPaused = false;
  71052. };
  71053. return WeightedSound;
  71054. }());
  71055. BABYLON.WeightedSound = WeightedSound;
  71056. })(BABYLON || (BABYLON = {}));
  71057. //# sourceMappingURL=babylon.weightedsound.js.map
  71058. var BABYLON;
  71059. (function (BABYLON) {
  71060. // Adds the parser to the scene parsers.
  71061. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  71062. // TODO: add sound
  71063. var loadedSounds = [];
  71064. var loadedSound;
  71065. container.sounds = container.sounds || [];
  71066. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71067. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71068. var parsedSound = parsedData.sounds[index];
  71069. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71070. if (!parsedSound.url) {
  71071. parsedSound.url = parsedSound.name;
  71072. }
  71073. if (!loadedSounds[parsedSound.url]) {
  71074. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71075. loadedSounds[parsedSound.url] = loadedSound;
  71076. container.sounds.push(loadedSound);
  71077. }
  71078. else {
  71079. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71080. }
  71081. }
  71082. else {
  71083. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71084. }
  71085. }
  71086. }
  71087. loadedSounds = [];
  71088. });
  71089. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  71090. get: function () {
  71091. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71092. if (!compo) {
  71093. compo = new AudioSceneComponent(this);
  71094. this._addComponent(compo);
  71095. }
  71096. if (!this._mainSoundTrack) {
  71097. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  71098. }
  71099. return this._mainSoundTrack;
  71100. },
  71101. enumerable: true,
  71102. configurable: true
  71103. });
  71104. BABYLON.Scene.prototype.getSoundByName = function (name) {
  71105. var index;
  71106. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  71107. if (this.mainSoundTrack.soundCollection[index].name === name) {
  71108. return this.mainSoundTrack.soundCollection[index];
  71109. }
  71110. }
  71111. if (this.soundTracks) {
  71112. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  71113. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  71114. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  71115. return this.soundTracks[sdIndex].soundCollection[index];
  71116. }
  71117. }
  71118. }
  71119. }
  71120. return null;
  71121. };
  71122. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  71123. get: function () {
  71124. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71125. if (!compo) {
  71126. compo = new AudioSceneComponent(this);
  71127. this._addComponent(compo);
  71128. }
  71129. return compo.audioEnabled;
  71130. },
  71131. set: function (value) {
  71132. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71133. if (!compo) {
  71134. compo = new AudioSceneComponent(this);
  71135. this._addComponent(compo);
  71136. }
  71137. if (value) {
  71138. compo.enableAudio();
  71139. }
  71140. else {
  71141. compo.disableAudio();
  71142. }
  71143. },
  71144. enumerable: true,
  71145. configurable: true
  71146. });
  71147. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  71148. get: function () {
  71149. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71150. if (!compo) {
  71151. compo = new AudioSceneComponent(this);
  71152. this._addComponent(compo);
  71153. }
  71154. return compo.headphone;
  71155. },
  71156. set: function (value) {
  71157. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71158. if (!compo) {
  71159. compo = new AudioSceneComponent(this);
  71160. this._addComponent(compo);
  71161. }
  71162. if (value) {
  71163. compo.switchAudioModeForHeadphones();
  71164. }
  71165. else {
  71166. compo.switchAudioModeForNormalSpeakers();
  71167. }
  71168. },
  71169. enumerable: true,
  71170. configurable: true
  71171. });
  71172. /**
  71173. * Defines the sound scene component responsible to manage any sounds
  71174. * in a given scene.
  71175. */
  71176. var AudioSceneComponent = /** @class */ (function () {
  71177. /**
  71178. * Creates a new instance of the component for the given scene
  71179. * @param scene Defines the scene to register the component in
  71180. */
  71181. function AudioSceneComponent(scene) {
  71182. /**
  71183. * The component name helpfull to identify the component in the list of scene components.
  71184. */
  71185. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  71186. this._audioEnabled = true;
  71187. this._headphone = false;
  71188. this.scene = scene;
  71189. scene.soundTracks = new Array();
  71190. scene.sounds = new Array();
  71191. }
  71192. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  71193. /**
  71194. * Gets whether audio is enabled or not.
  71195. * Please use related enable/disable method to switch state.
  71196. */
  71197. get: function () {
  71198. return this._audioEnabled;
  71199. },
  71200. enumerable: true,
  71201. configurable: true
  71202. });
  71203. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  71204. /**
  71205. * Gets whether audio is outputing to headphone or not.
  71206. * Please use the according Switch methods to change output.
  71207. */
  71208. get: function () {
  71209. return this._headphone;
  71210. },
  71211. enumerable: true,
  71212. configurable: true
  71213. });
  71214. /**
  71215. * Registers the component in a given scene
  71216. */
  71217. AudioSceneComponent.prototype.register = function () {
  71218. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  71219. };
  71220. /**
  71221. * Rebuilds the elements related to this component in case of
  71222. * context lost for instance.
  71223. */
  71224. AudioSceneComponent.prototype.rebuild = function () {
  71225. // Nothing to do here. (Not rendering related)
  71226. };
  71227. /**
  71228. * Serializes the component data to the specified json object
  71229. * @param serializationObject The object to serialize to
  71230. */
  71231. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  71232. serializationObject.sounds = [];
  71233. if (this.scene.soundTracks) {
  71234. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  71235. var soundtrack = this.scene.soundTracks[index];
  71236. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  71237. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  71238. }
  71239. }
  71240. }
  71241. };
  71242. /**
  71243. * Adds all the element from the container to the scene
  71244. * @param container the container holding the elements
  71245. */
  71246. AudioSceneComponent.prototype.addFromContainer = function (container) {
  71247. var _this = this;
  71248. if (!container.sounds) {
  71249. return;
  71250. }
  71251. container.sounds.forEach(function (sound) {
  71252. sound.play();
  71253. sound.autoplay = true;
  71254. _this.scene.mainSoundTrack.AddSound(sound);
  71255. });
  71256. };
  71257. /**
  71258. * Removes all the elements in the container from the scene
  71259. * @param container contains the elements to remove
  71260. */
  71261. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  71262. var _this = this;
  71263. if (!container.sounds) {
  71264. return;
  71265. }
  71266. container.sounds.forEach(function (sound) {
  71267. sound.stop();
  71268. sound.autoplay = false;
  71269. _this.scene.mainSoundTrack.RemoveSound(sound);
  71270. });
  71271. };
  71272. /**
  71273. * Disposes the component and the associated ressources.
  71274. */
  71275. AudioSceneComponent.prototype.dispose = function () {
  71276. var scene = this.scene;
  71277. if (scene._mainSoundTrack) {
  71278. scene.mainSoundTrack.dispose();
  71279. }
  71280. if (scene.soundTracks) {
  71281. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  71282. scene.soundTracks[scIndex].dispose();
  71283. }
  71284. }
  71285. };
  71286. /**
  71287. * Disables audio in the associated scene.
  71288. */
  71289. AudioSceneComponent.prototype.disableAudio = function () {
  71290. var scene = this.scene;
  71291. this._audioEnabled = false;
  71292. var i;
  71293. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71294. scene.mainSoundTrack.soundCollection[i].pause();
  71295. }
  71296. if (scene.soundTracks) {
  71297. for (i = 0; i < scene.soundTracks.length; i++) {
  71298. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71299. scene.soundTracks[i].soundCollection[j].pause();
  71300. }
  71301. }
  71302. }
  71303. };
  71304. /**
  71305. * Enables audio in the associated scene.
  71306. */
  71307. AudioSceneComponent.prototype.enableAudio = function () {
  71308. var scene = this.scene;
  71309. this._audioEnabled = true;
  71310. var i;
  71311. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71312. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  71313. scene.mainSoundTrack.soundCollection[i].play();
  71314. }
  71315. }
  71316. if (scene.soundTracks) {
  71317. for (i = 0; i < scene.soundTracks.length; i++) {
  71318. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71319. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  71320. scene.soundTracks[i].soundCollection[j].play();
  71321. }
  71322. }
  71323. }
  71324. }
  71325. };
  71326. /**
  71327. * Switch audio to headphone output.
  71328. */
  71329. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  71330. var scene = this.scene;
  71331. this._headphone = true;
  71332. scene.mainSoundTrack.switchPanningModelToHRTF();
  71333. if (scene.soundTracks) {
  71334. for (var i = 0; i < scene.soundTracks.length; i++) {
  71335. scene.soundTracks[i].switchPanningModelToHRTF();
  71336. }
  71337. }
  71338. };
  71339. /**
  71340. * Switch audio to normal speakers.
  71341. */
  71342. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  71343. var scene = this.scene;
  71344. this._headphone = false;
  71345. scene.mainSoundTrack.switchPanningModelToEqualPower();
  71346. if (scene.soundTracks) {
  71347. for (var i = 0; i < scene.soundTracks.length; i++) {
  71348. scene.soundTracks[i].switchPanningModelToEqualPower();
  71349. }
  71350. }
  71351. };
  71352. AudioSceneComponent.prototype._afterRender = function () {
  71353. var scene = this.scene;
  71354. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  71355. return;
  71356. }
  71357. var listeningCamera;
  71358. var audioEngine = BABYLON.Engine.audioEngine;
  71359. if (scene.activeCameras.length > 0) {
  71360. listeningCamera = scene.activeCameras[0];
  71361. }
  71362. else {
  71363. listeningCamera = scene.activeCamera;
  71364. }
  71365. if (listeningCamera && audioEngine.audioContext) {
  71366. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  71367. // for VR cameras
  71368. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  71369. listeningCamera = listeningCamera.rigCameras[0];
  71370. }
  71371. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  71372. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  71373. cameraDirection.normalize();
  71374. // To avoid some errors on GearVR
  71375. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  71376. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  71377. }
  71378. var i;
  71379. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71380. var sound = scene.mainSoundTrack.soundCollection[i];
  71381. if (sound.useCustomAttenuation) {
  71382. sound.updateDistanceFromListener();
  71383. }
  71384. }
  71385. if (scene.soundTracks) {
  71386. for (i = 0; i < scene.soundTracks.length; i++) {
  71387. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71388. sound = scene.soundTracks[i].soundCollection[j];
  71389. if (sound.useCustomAttenuation) {
  71390. sound.updateDistanceFromListener();
  71391. }
  71392. }
  71393. }
  71394. }
  71395. }
  71396. };
  71397. return AudioSceneComponent;
  71398. }());
  71399. BABYLON.AudioSceneComponent = AudioSceneComponent;
  71400. })(BABYLON || (BABYLON = {}));
  71401. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  71402. var BABYLON;
  71403. (function (BABYLON) {
  71404. /**
  71405. * This defines an action helpful to play a defined sound on a triggered action.
  71406. */
  71407. var PlaySoundAction = /** @class */ (function (_super) {
  71408. __extends(PlaySoundAction, _super);
  71409. /**
  71410. * Instantiate the action
  71411. * @param triggerOptions defines the trigger options
  71412. * @param sound defines the sound to play
  71413. * @param condition defines the trigger related conditions
  71414. */
  71415. function PlaySoundAction(triggerOptions, sound, condition) {
  71416. var _this = _super.call(this, triggerOptions, condition) || this;
  71417. _this._sound = sound;
  71418. return _this;
  71419. }
  71420. /** @hidden */
  71421. PlaySoundAction.prototype._prepare = function () {
  71422. };
  71423. /**
  71424. * Execute the action and play the sound.
  71425. */
  71426. PlaySoundAction.prototype.execute = function () {
  71427. if (this._sound !== undefined) {
  71428. this._sound.play();
  71429. }
  71430. };
  71431. /**
  71432. * Serializes the actions and its related information.
  71433. * @param parent defines the object to serialize in
  71434. * @returns the serialized object
  71435. */
  71436. PlaySoundAction.prototype.serialize = function (parent) {
  71437. return _super.prototype._serialize.call(this, {
  71438. name: "PlaySoundAction",
  71439. properties: [{ name: "sound", value: this._sound.name }]
  71440. }, parent);
  71441. };
  71442. return PlaySoundAction;
  71443. }(BABYLON.Action));
  71444. BABYLON.PlaySoundAction = PlaySoundAction;
  71445. /**
  71446. * This defines an action helpful to stop a defined sound on a triggered action.
  71447. */
  71448. var StopSoundAction = /** @class */ (function (_super) {
  71449. __extends(StopSoundAction, _super);
  71450. /**
  71451. * Instantiate the action
  71452. * @param triggerOptions defines the trigger options
  71453. * @param sound defines the sound to stop
  71454. * @param condition defines the trigger related conditions
  71455. */
  71456. function StopSoundAction(triggerOptions, sound, condition) {
  71457. var _this = _super.call(this, triggerOptions, condition) || this;
  71458. _this._sound = sound;
  71459. return _this;
  71460. }
  71461. /** @hidden */
  71462. StopSoundAction.prototype._prepare = function () {
  71463. };
  71464. /**
  71465. * Execute the action and stop the sound.
  71466. */
  71467. StopSoundAction.prototype.execute = function () {
  71468. if (this._sound !== undefined) {
  71469. this._sound.stop();
  71470. }
  71471. };
  71472. /**
  71473. * Serializes the actions and its related information.
  71474. * @param parent defines the object to serialize in
  71475. * @returns the serialized object
  71476. */
  71477. StopSoundAction.prototype.serialize = function (parent) {
  71478. return _super.prototype._serialize.call(this, {
  71479. name: "StopSoundAction",
  71480. properties: [{ name: "sound", value: this._sound.name }]
  71481. }, parent);
  71482. };
  71483. return StopSoundAction;
  71484. }(BABYLON.Action));
  71485. BABYLON.StopSoundAction = StopSoundAction;
  71486. })(BABYLON || (BABYLON = {}));
  71487. //# sourceMappingURL=babylon.directAudioActions.js.map
  71488. var BABYLON;
  71489. (function (BABYLON) {
  71490. /**
  71491. * Class for creating a cube texture
  71492. */
  71493. var CubeTexture = /** @class */ (function (_super) {
  71494. __extends(CubeTexture, _super);
  71495. /**
  71496. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  71497. * as prefiltered data.
  71498. * @param rootUrl defines the url of the texture or the root name of the six images
  71499. * @param scene defines the scene the texture is attached to
  71500. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  71501. * @param noMipmap defines if mipmaps should be created or not
  71502. * @param files defines the six files to load for the different faces
  71503. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  71504. * @param onError defines a callback triggered in case of error during load
  71505. * @param format defines the internal format to use for the texture once loaded
  71506. * @param prefiltered defines whether or not the texture is created from prefiltered data
  71507. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  71508. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71509. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71510. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71511. * @return the cube texture
  71512. */
  71513. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  71514. if (extensions === void 0) { extensions = null; }
  71515. if (noMipmap === void 0) { noMipmap = false; }
  71516. if (files === void 0) { files = null; }
  71517. if (onLoad === void 0) { onLoad = null; }
  71518. if (onError === void 0) { onError = null; }
  71519. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71520. if (prefiltered === void 0) { prefiltered = false; }
  71521. if (forcedExtension === void 0) { forcedExtension = null; }
  71522. if (createPolynomials === void 0) { createPolynomials = false; }
  71523. if (lodScale === void 0) { lodScale = 0.8; }
  71524. if (lodOffset === void 0) { lodOffset = 0; }
  71525. var _this = _super.call(this, scene) || this;
  71526. /**
  71527. * Gets or sets the center of the bounding box associated with the cube texture.
  71528. * It must define where the camera used to render the texture was set
  71529. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71530. */
  71531. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71532. _this._rotationY = 0;
  71533. /** @hidden */
  71534. _this._prefiltered = false;
  71535. _this.name = rootUrl;
  71536. _this.url = rootUrl;
  71537. _this._noMipmap = noMipmap;
  71538. _this.hasAlpha = false;
  71539. _this._format = format;
  71540. _this.isCube = true;
  71541. _this._textureMatrix = BABYLON.Matrix.Identity();
  71542. _this._createPolynomials = createPolynomials;
  71543. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71544. if (!rootUrl && !files) {
  71545. return _this;
  71546. }
  71547. var lastDot = rootUrl.lastIndexOf(".");
  71548. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  71549. var isDDS = (extension === ".dds");
  71550. var isEnv = (extension === ".env");
  71551. if (isEnv) {
  71552. _this.gammaSpace = false;
  71553. _this._prefiltered = false;
  71554. }
  71555. else {
  71556. _this._prefiltered = prefiltered;
  71557. if (prefiltered) {
  71558. _this.gammaSpace = false;
  71559. }
  71560. }
  71561. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  71562. if (!files) {
  71563. if (!isEnv && !isDDS && !extensions) {
  71564. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  71565. }
  71566. files = [];
  71567. if (extensions) {
  71568. for (var index = 0; index < extensions.length; index++) {
  71569. files.push(rootUrl + extensions[index]);
  71570. }
  71571. }
  71572. }
  71573. _this._files = files;
  71574. if (!_this._texture) {
  71575. if (!scene.useDelayedTextureLoading) {
  71576. if (prefiltered) {
  71577. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  71578. }
  71579. else {
  71580. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  71581. }
  71582. }
  71583. else {
  71584. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71585. }
  71586. }
  71587. else if (onLoad) {
  71588. if (_this._texture.isReady) {
  71589. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  71590. }
  71591. else {
  71592. _this._texture.onLoadedObservable.add(onLoad);
  71593. }
  71594. }
  71595. return _this;
  71596. }
  71597. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  71598. /**
  71599. * Returns the bounding box size
  71600. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71601. */
  71602. get: function () {
  71603. return this._boundingBoxSize;
  71604. },
  71605. /**
  71606. * Gets or sets the size of the bounding box associated with the cube texture
  71607. * When defined, the cubemap will switch to local mode
  71608. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71609. * @example https://www.babylonjs-playground.com/#RNASML
  71610. */
  71611. set: function (value) {
  71612. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71613. return;
  71614. }
  71615. this._boundingBoxSize = value;
  71616. var scene = this.getScene();
  71617. if (scene) {
  71618. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71619. }
  71620. },
  71621. enumerable: true,
  71622. configurable: true
  71623. });
  71624. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  71625. /**
  71626. * Gets texture matrix rotation angle around Y axis radians.
  71627. */
  71628. get: function () {
  71629. return this._rotationY;
  71630. },
  71631. /**
  71632. * Sets texture matrix rotation angle around Y axis in radians.
  71633. */
  71634. set: function (value) {
  71635. this._rotationY = value;
  71636. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  71637. },
  71638. enumerable: true,
  71639. configurable: true
  71640. });
  71641. /**
  71642. * Creates a cube texture from an array of image urls
  71643. * @param files defines an array of image urls
  71644. * @param scene defines the hosting scene
  71645. * @param noMipmap specifies if mip maps are not used
  71646. * @returns a cube texture
  71647. */
  71648. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  71649. var rootUrlKey = "";
  71650. files.forEach(function (url) { return rootUrlKey += url; });
  71651. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  71652. };
  71653. /**
  71654. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  71655. * @param url defines the url of the prefiltered texture
  71656. * @param scene defines the scene the texture is attached to
  71657. * @param forcedExtension defines the extension of the file if different from the url
  71658. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71659. * @return the prefiltered texture
  71660. */
  71661. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  71662. if (forcedExtension === void 0) { forcedExtension = null; }
  71663. if (createPolynomials === void 0) { createPolynomials = true; }
  71664. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  71665. };
  71666. /**
  71667. * Delays loading of the cube texture
  71668. */
  71669. CubeTexture.prototype.delayLoad = function () {
  71670. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71671. return;
  71672. }
  71673. var scene = this.getScene();
  71674. if (!scene) {
  71675. return;
  71676. }
  71677. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71678. this._texture = this._getFromCache(this.url, this._noMipmap);
  71679. if (!this._texture) {
  71680. if (this._prefiltered) {
  71681. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  71682. }
  71683. else {
  71684. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  71685. }
  71686. }
  71687. };
  71688. /**
  71689. * Returns the reflection texture matrix
  71690. * @returns the reflection texture matrix
  71691. */
  71692. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  71693. return this._textureMatrix;
  71694. };
  71695. /**
  71696. * Sets the reflection texture matrix
  71697. * @param value Reflection texture matrix
  71698. */
  71699. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71700. this._textureMatrix = value;
  71701. };
  71702. /**
  71703. * Parses text to create a cube texture
  71704. * @param parsedTexture define the serialized text to read from
  71705. * @param scene defines the hosting scene
  71706. * @param rootUrl defines the root url of the cube texture
  71707. * @returns a cube texture
  71708. */
  71709. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71710. var texture = BABYLON.SerializationHelper.Parse(function () {
  71711. var prefiltered = false;
  71712. if (parsedTexture.prefiltered) {
  71713. prefiltered = parsedTexture.prefiltered;
  71714. }
  71715. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  71716. }, parsedTexture, scene);
  71717. // Local Cubemaps
  71718. if (parsedTexture.boundingBoxPosition) {
  71719. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  71720. }
  71721. if (parsedTexture.boundingBoxSize) {
  71722. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  71723. }
  71724. // Animations
  71725. if (parsedTexture.animations) {
  71726. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  71727. var parsedAnimation = parsedTexture.animations[animationIndex];
  71728. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71729. }
  71730. }
  71731. return texture;
  71732. };
  71733. /**
  71734. * Makes a clone, or deep copy, of the cube texture
  71735. * @returns a new cube texture
  71736. */
  71737. CubeTexture.prototype.clone = function () {
  71738. var _this = this;
  71739. return BABYLON.SerializationHelper.Clone(function () {
  71740. var scene = _this.getScene();
  71741. if (!scene) {
  71742. return _this;
  71743. }
  71744. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  71745. }, this);
  71746. };
  71747. __decorate([
  71748. BABYLON.serialize("rotationY")
  71749. ], CubeTexture.prototype, "rotationY", null);
  71750. return CubeTexture;
  71751. }(BABYLON.BaseTexture));
  71752. BABYLON.CubeTexture = CubeTexture;
  71753. })(BABYLON || (BABYLON = {}));
  71754. //# sourceMappingURL=babylon.cubeTexture.js.map
  71755. var BABYLON;
  71756. (function (BABYLON) {
  71757. /**
  71758. * Raw cube texture where the raw buffers are passed in
  71759. */
  71760. var RawCubeTexture = /** @class */ (function (_super) {
  71761. __extends(RawCubeTexture, _super);
  71762. /**
  71763. * Creates a cube texture where the raw buffers are passed in.
  71764. * @param scene defines the scene the texture is attached to
  71765. * @param data defines the array of data to use to create each face
  71766. * @param size defines the size of the textures
  71767. * @param format defines the format of the data
  71768. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  71769. * @param generateMipMaps defines if the engine should generate the mip levels
  71770. * @param invertY defines if data must be stored with Y axis inverted
  71771. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  71772. * @param compression defines the compression used (null by default)
  71773. */
  71774. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  71775. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71776. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71777. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71778. if (invertY === void 0) { invertY = false; }
  71779. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71780. if (compression === void 0) { compression = null; }
  71781. var _this = _super.call(this, "", scene) || this;
  71782. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  71783. return _this;
  71784. }
  71785. /**
  71786. * Updates the raw cube texture.
  71787. * @param data defines the data to store
  71788. * @param format defines the data format
  71789. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  71790. * @param invertY defines if data must be stored with Y axis inverted
  71791. * @param compression defines the compression used (null by default)
  71792. * @param level defines which level of the texture to update
  71793. */
  71794. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  71795. if (compression === void 0) { compression = null; }
  71796. if (level === void 0) { level = 0; }
  71797. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  71798. };
  71799. /**
  71800. * Updates a raw cube texture with RGBD encoded data.
  71801. * @param data defines the array of data [mipmap][face] to use to create each face
  71802. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  71803. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71804. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71805. * @returns a promsie that resolves when the operation is complete
  71806. */
  71807. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  71808. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  71809. if (lodScale === void 0) { lodScale = 0.8; }
  71810. if (lodOffset === void 0) { lodOffset = 0; }
  71811. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  71812. };
  71813. /**
  71814. * Clones the raw cube texture.
  71815. * @return a new cube texture
  71816. */
  71817. RawCubeTexture.prototype.clone = function () {
  71818. var _this = this;
  71819. return BABYLON.SerializationHelper.Clone(function () {
  71820. var scene = _this.getScene();
  71821. var internalTexture = _this._texture;
  71822. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  71823. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  71824. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  71825. }
  71826. return texture;
  71827. }, this);
  71828. };
  71829. /** @hidden */
  71830. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  71831. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  71832. internalTexture._bufferViewArrayArray = data;
  71833. internalTexture._lodGenerationScale = lodScale;
  71834. internalTexture._lodGenerationOffset = lodOffset;
  71835. internalTexture._sphericalPolynomial = sphericalPolynomial;
  71836. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  71837. internalTexture.isReady = true;
  71838. });
  71839. };
  71840. return RawCubeTexture;
  71841. }(BABYLON.CubeTexture));
  71842. BABYLON.RawCubeTexture = RawCubeTexture;
  71843. })(BABYLON || (BABYLON = {}));
  71844. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  71845. var BABYLON;
  71846. (function (BABYLON) {
  71847. /**
  71848. * This Helps creating a texture that will be created from a camera in your scene.
  71849. * It is basically a dynamic texture that could be used to create special effects for instance.
  71850. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  71851. */
  71852. var RenderTargetTexture = /** @class */ (function (_super) {
  71853. __extends(RenderTargetTexture, _super);
  71854. /**
  71855. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  71856. * or used a shadow, depth texture...
  71857. * @param name The friendly name of the texture
  71858. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  71859. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  71860. * @param generateMipMaps True if mip maps need to be generated after render.
  71861. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  71862. * @param type The type of the buffer in the RTT (int, half float, float...)
  71863. * @param isCube True if a cube texture needs to be created
  71864. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  71865. * @param generateDepthBuffer True to generate a depth buffer
  71866. * @param generateStencilBuffer True to generate a stencil buffer
  71867. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  71868. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  71869. */
  71870. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  71871. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  71872. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71873. if (isCube === void 0) { isCube = false; }
  71874. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71875. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71876. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  71877. if (isMulti === void 0) { isMulti = false; }
  71878. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71879. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71880. _this.isCube = isCube;
  71881. /**
  71882. * Define if particles should be rendered in your texture.
  71883. */
  71884. _this.renderParticles = true;
  71885. /**
  71886. * Define if sprites should be rendered in your texture.
  71887. */
  71888. _this.renderSprites = false;
  71889. /**
  71890. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  71891. */
  71892. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  71893. /**
  71894. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  71895. */
  71896. _this.ignoreCameraViewport = false;
  71897. /**
  71898. * An event triggered when the texture is unbind.
  71899. */
  71900. _this.onBeforeBindObservable = new BABYLON.Observable();
  71901. /**
  71902. * An event triggered when the texture is unbind.
  71903. */
  71904. _this.onAfterUnbindObservable = new BABYLON.Observable();
  71905. /**
  71906. * An event triggered before rendering the texture
  71907. */
  71908. _this.onBeforeRenderObservable = new BABYLON.Observable();
  71909. /**
  71910. * An event triggered after rendering the texture
  71911. */
  71912. _this.onAfterRenderObservable = new BABYLON.Observable();
  71913. /**
  71914. * An event triggered after the texture clear
  71915. */
  71916. _this.onClearObservable = new BABYLON.Observable();
  71917. _this._currentRefreshId = -1;
  71918. _this._refreshRate = 1;
  71919. _this._samples = 1;
  71920. /**
  71921. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  71922. * It must define where the camera used to render the texture is set
  71923. */
  71924. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71925. scene = _this.getScene();
  71926. if (!scene) {
  71927. return _this;
  71928. }
  71929. _this.renderList = new Array();
  71930. _this._engine = scene.getEngine();
  71931. _this.name = name;
  71932. _this.isRenderTarget = true;
  71933. _this._initialSizeParameter = size;
  71934. _this._processSizeParameter(size);
  71935. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  71936. });
  71937. _this._generateMipMaps = generateMipMaps ? true : false;
  71938. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  71939. // Rendering groups
  71940. _this._renderingManager = new BABYLON.RenderingManager(scene);
  71941. _this._renderingManager._useSceneAutoClearSetup = true;
  71942. if (isMulti) {
  71943. return _this;
  71944. }
  71945. _this._renderTargetOptions = {
  71946. generateMipMaps: generateMipMaps,
  71947. type: type,
  71948. format: format,
  71949. samplingMode: samplingMode,
  71950. generateDepthBuffer: generateDepthBuffer,
  71951. generateStencilBuffer: generateStencilBuffer
  71952. };
  71953. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  71954. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71955. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71956. }
  71957. if (isCube) {
  71958. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  71959. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  71960. _this._textureMatrix = BABYLON.Matrix.Identity();
  71961. }
  71962. else {
  71963. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  71964. }
  71965. return _this;
  71966. }
  71967. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  71968. /**
  71969. * Use this list to define the list of mesh you want to render.
  71970. */
  71971. get: function () {
  71972. return this._renderList;
  71973. },
  71974. set: function (value) {
  71975. this._renderList = value;
  71976. if (this._renderList) {
  71977. this._hookArray(this._renderList);
  71978. }
  71979. },
  71980. enumerable: true,
  71981. configurable: true
  71982. });
  71983. RenderTargetTexture.prototype._hookArray = function (array) {
  71984. var _this = this;
  71985. var oldPush = array.push;
  71986. array.push = function () {
  71987. var items = [];
  71988. for (var _i = 0; _i < arguments.length; _i++) {
  71989. items[_i] = arguments[_i];
  71990. }
  71991. var wasEmpty = array.length === 0;
  71992. var result = oldPush.apply(array, items);
  71993. if (wasEmpty) {
  71994. _this.getScene().meshes.forEach(function (mesh) {
  71995. mesh._markSubMeshesAsLightDirty();
  71996. });
  71997. }
  71998. return result;
  71999. };
  72000. var oldSplice = array.splice;
  72001. array.splice = function (index, deleteCount) {
  72002. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72003. if (array.length === 0) {
  72004. _this.getScene().meshes.forEach(function (mesh) {
  72005. mesh._markSubMeshesAsLightDirty();
  72006. });
  72007. }
  72008. return deleted;
  72009. };
  72010. };
  72011. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  72012. /**
  72013. * Set a after unbind callback in the texture.
  72014. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  72015. */
  72016. set: function (callback) {
  72017. if (this._onAfterUnbindObserver) {
  72018. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  72019. }
  72020. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  72021. },
  72022. enumerable: true,
  72023. configurable: true
  72024. });
  72025. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  72026. /**
  72027. * Set a before render callback in the texture.
  72028. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  72029. */
  72030. set: function (callback) {
  72031. if (this._onBeforeRenderObserver) {
  72032. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72033. }
  72034. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72035. },
  72036. enumerable: true,
  72037. configurable: true
  72038. });
  72039. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  72040. /**
  72041. * Set a after render callback in the texture.
  72042. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  72043. */
  72044. set: function (callback) {
  72045. if (this._onAfterRenderObserver) {
  72046. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72047. }
  72048. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72049. },
  72050. enumerable: true,
  72051. configurable: true
  72052. });
  72053. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  72054. /**
  72055. * Set a clear callback in the texture.
  72056. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  72057. */
  72058. set: function (callback) {
  72059. if (this._onClearObserver) {
  72060. this.onClearObservable.remove(this._onClearObserver);
  72061. }
  72062. this._onClearObserver = this.onClearObservable.add(callback);
  72063. },
  72064. enumerable: true,
  72065. configurable: true
  72066. });
  72067. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  72068. /**
  72069. * Gets render target creation options that were used.
  72070. */
  72071. get: function () {
  72072. return this._renderTargetOptions;
  72073. },
  72074. enumerable: true,
  72075. configurable: true
  72076. });
  72077. RenderTargetTexture.prototype._onRatioRescale = function () {
  72078. if (this._sizeRatio) {
  72079. this.resize(this._initialSizeParameter);
  72080. }
  72081. };
  72082. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  72083. get: function () {
  72084. return this._boundingBoxSize;
  72085. },
  72086. /**
  72087. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  72088. * When defined, the cubemap will switch to local mode
  72089. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72090. * @example https://www.babylonjs-playground.com/#RNASML
  72091. */
  72092. set: function (value) {
  72093. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72094. return;
  72095. }
  72096. this._boundingBoxSize = value;
  72097. var scene = this.getScene();
  72098. if (scene) {
  72099. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72100. }
  72101. },
  72102. enumerable: true,
  72103. configurable: true
  72104. });
  72105. /**
  72106. * Creates a depth stencil texture.
  72107. * This is only available in WebGL 2 or with the depth texture extension available.
  72108. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  72109. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  72110. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  72111. */
  72112. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  72113. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  72114. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  72115. if (generateStencil === void 0) { generateStencil = false; }
  72116. if (!this.getScene()) {
  72117. return;
  72118. }
  72119. var engine = this.getScene().getEngine();
  72120. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  72121. bilinearFiltering: bilinearFiltering,
  72122. comparisonFunction: comparisonFunction,
  72123. generateStencil: generateStencil,
  72124. isCube: this.isCube
  72125. });
  72126. engine.setFrameBufferDepthStencilTexture(this);
  72127. };
  72128. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  72129. if (size.ratio) {
  72130. this._sizeRatio = size.ratio;
  72131. this._size = {
  72132. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  72133. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  72134. };
  72135. }
  72136. else {
  72137. this._size = size;
  72138. }
  72139. };
  72140. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  72141. /**
  72142. * Define the number of samples to use in case of MSAA.
  72143. * It defaults to one meaning no MSAA has been enabled.
  72144. */
  72145. get: function () {
  72146. return this._samples;
  72147. },
  72148. set: function (value) {
  72149. if (this._samples === value) {
  72150. return;
  72151. }
  72152. var scene = this.getScene();
  72153. if (!scene) {
  72154. return;
  72155. }
  72156. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  72157. },
  72158. enumerable: true,
  72159. configurable: true
  72160. });
  72161. /**
  72162. * Resets the refresh counter of the texture and start bak from scratch.
  72163. * Could be usefull to regenerate the texture if it is setup to render only once.
  72164. */
  72165. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  72166. this._currentRefreshId = -1;
  72167. };
  72168. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  72169. /**
  72170. * Define the refresh rate of the texture or the rendering frequency.
  72171. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  72172. */
  72173. get: function () {
  72174. return this._refreshRate;
  72175. },
  72176. set: function (value) {
  72177. this._refreshRate = value;
  72178. this.resetRefreshCounter();
  72179. },
  72180. enumerable: true,
  72181. configurable: true
  72182. });
  72183. /**
  72184. * Adds a post process to the render target rendering passes.
  72185. * @param postProcess define the post process to add
  72186. */
  72187. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  72188. if (!this._postProcessManager) {
  72189. var scene = this.getScene();
  72190. if (!scene) {
  72191. return;
  72192. }
  72193. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  72194. this._postProcesses = new Array();
  72195. }
  72196. this._postProcesses.push(postProcess);
  72197. this._postProcesses[0].autoClear = false;
  72198. };
  72199. /**
  72200. * Clear all the post processes attached to the render target
  72201. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  72202. */
  72203. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  72204. if (dispose === void 0) { dispose = false; }
  72205. if (!this._postProcesses) {
  72206. return;
  72207. }
  72208. if (dispose) {
  72209. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  72210. var postProcess = _a[_i];
  72211. postProcess.dispose();
  72212. }
  72213. }
  72214. this._postProcesses = [];
  72215. };
  72216. /**
  72217. * Remove one of the post process from the list of attached post processes to the texture
  72218. * @param postProcess define the post process to remove from the list
  72219. */
  72220. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  72221. if (!this._postProcesses) {
  72222. return;
  72223. }
  72224. var index = this._postProcesses.indexOf(postProcess);
  72225. if (index === -1) {
  72226. return;
  72227. }
  72228. this._postProcesses.splice(index, 1);
  72229. if (this._postProcesses.length > 0) {
  72230. this._postProcesses[0].autoClear = false;
  72231. }
  72232. };
  72233. /** @hidden */
  72234. RenderTargetTexture.prototype._shouldRender = function () {
  72235. if (this._currentRefreshId === -1) { // At least render once
  72236. this._currentRefreshId = 1;
  72237. return true;
  72238. }
  72239. if (this.refreshRate === this._currentRefreshId) {
  72240. this._currentRefreshId = 1;
  72241. return true;
  72242. }
  72243. this._currentRefreshId++;
  72244. return false;
  72245. };
  72246. /**
  72247. * Gets the actual render size of the texture.
  72248. * @returns the width of the render size
  72249. */
  72250. RenderTargetTexture.prototype.getRenderSize = function () {
  72251. return this.getRenderWidth();
  72252. };
  72253. /**
  72254. * Gets the actual render width of the texture.
  72255. * @returns the width of the render size
  72256. */
  72257. RenderTargetTexture.prototype.getRenderWidth = function () {
  72258. if (this._size.width) {
  72259. return this._size.width;
  72260. }
  72261. return this._size;
  72262. };
  72263. /**
  72264. * Gets the actual render height of the texture.
  72265. * @returns the height of the render size
  72266. */
  72267. RenderTargetTexture.prototype.getRenderHeight = function () {
  72268. if (this._size.width) {
  72269. return this._size.height;
  72270. }
  72271. return this._size;
  72272. };
  72273. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  72274. /**
  72275. * Get if the texture can be rescaled or not.
  72276. */
  72277. get: function () {
  72278. return true;
  72279. },
  72280. enumerable: true,
  72281. configurable: true
  72282. });
  72283. /**
  72284. * Resize the texture using a ratio.
  72285. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  72286. */
  72287. RenderTargetTexture.prototype.scale = function (ratio) {
  72288. var newSize = this.getRenderSize() * ratio;
  72289. this.resize(newSize);
  72290. };
  72291. /**
  72292. * Get the texture reflection matrix used to rotate/transform the reflection.
  72293. * @returns the reflection matrix
  72294. */
  72295. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  72296. if (this.isCube) {
  72297. return this._textureMatrix;
  72298. }
  72299. return _super.prototype.getReflectionTextureMatrix.call(this);
  72300. };
  72301. /**
  72302. * Resize the texture to a new desired size.
  72303. * Be carrefull as it will recreate all the data in the new texture.
  72304. * @param size Define the new size. It can be:
  72305. * - a number for squared texture,
  72306. * - an object containing { width: number, height: number }
  72307. * - or an object containing a ratio { ratio: number }
  72308. */
  72309. RenderTargetTexture.prototype.resize = function (size) {
  72310. this.releaseInternalTexture();
  72311. var scene = this.getScene();
  72312. if (!scene) {
  72313. return;
  72314. }
  72315. this._processSizeParameter(size);
  72316. if (this.isCube) {
  72317. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  72318. }
  72319. else {
  72320. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  72321. }
  72322. };
  72323. /**
  72324. * Renders all the objects from the render list into the texture.
  72325. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  72326. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  72327. */
  72328. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  72329. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  72330. if (dumpForDebug === void 0) { dumpForDebug = false; }
  72331. var scene = this.getScene();
  72332. if (!scene) {
  72333. return;
  72334. }
  72335. var engine = scene.getEngine();
  72336. if (this.useCameraPostProcesses !== undefined) {
  72337. useCameraPostProcess = this.useCameraPostProcesses;
  72338. }
  72339. if (this._waitingRenderList) {
  72340. this.renderList = [];
  72341. for (var index = 0; index < this._waitingRenderList.length; index++) {
  72342. var id = this._waitingRenderList[index];
  72343. var mesh_1 = scene.getMeshByID(id);
  72344. if (mesh_1) {
  72345. this.renderList.push(mesh_1);
  72346. }
  72347. }
  72348. delete this._waitingRenderList;
  72349. }
  72350. // Is predicate defined?
  72351. if (this.renderListPredicate) {
  72352. if (this.renderList) {
  72353. this.renderList.splice(0); // Clear previous renderList
  72354. }
  72355. else {
  72356. this.renderList = [];
  72357. }
  72358. var scene = this.getScene();
  72359. if (!scene) {
  72360. return;
  72361. }
  72362. var sceneMeshes = scene.meshes;
  72363. for (var index = 0; index < sceneMeshes.length; index++) {
  72364. var mesh = sceneMeshes[index];
  72365. if (this.renderListPredicate(mesh)) {
  72366. this.renderList.push(mesh);
  72367. }
  72368. }
  72369. }
  72370. this.onBeforeBindObservable.notifyObservers(this);
  72371. // Set custom projection.
  72372. // Needs to be before binding to prevent changing the aspect ratio.
  72373. var camera;
  72374. if (this.activeCamera) {
  72375. camera = this.activeCamera;
  72376. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72377. if (this.activeCamera !== scene.activeCamera) {
  72378. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  72379. }
  72380. }
  72381. else {
  72382. camera = scene.activeCamera;
  72383. if (camera) {
  72384. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72385. }
  72386. }
  72387. // Prepare renderingManager
  72388. this._renderingManager.reset();
  72389. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  72390. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  72391. var sceneRenderId = scene.getRenderId();
  72392. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  72393. var mesh = currentRenderList[meshIndex];
  72394. if (mesh) {
  72395. if (!mesh.isReady(this.refreshRate === 0)) {
  72396. this.resetRefreshCounter();
  72397. continue;
  72398. }
  72399. mesh._preActivateForIntermediateRendering(sceneRenderId);
  72400. var isMasked = void 0;
  72401. if (!this.renderList && camera) {
  72402. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  72403. }
  72404. else {
  72405. isMasked = false;
  72406. }
  72407. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  72408. mesh._activate(sceneRenderId);
  72409. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  72410. var subMesh = mesh.subMeshes[subIndex];
  72411. scene._activeIndices.addCount(subMesh.indexCount, false);
  72412. this._renderingManager.dispatch(subMesh, mesh);
  72413. }
  72414. }
  72415. }
  72416. }
  72417. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  72418. var particleSystem = scene.particleSystems[particleIndex];
  72419. var emitter = particleSystem.emitter;
  72420. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  72421. continue;
  72422. }
  72423. if (currentRenderList.indexOf(emitter) >= 0) {
  72424. this._renderingManager.dispatchParticles(particleSystem);
  72425. }
  72426. }
  72427. if (this.isCube) {
  72428. for (var face = 0; face < 6; face++) {
  72429. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72430. scene.incrementRenderId();
  72431. scene.resetCachedMaterial();
  72432. }
  72433. }
  72434. else {
  72435. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72436. }
  72437. this.onAfterUnbindObservable.notifyObservers(this);
  72438. if (scene.activeCamera) {
  72439. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  72440. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  72441. }
  72442. engine.setViewport(scene.activeCamera.viewport);
  72443. }
  72444. scene.resetCachedMaterial();
  72445. };
  72446. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  72447. var minimum = 128;
  72448. var x = renderDimension * scale;
  72449. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  72450. // Ensure we don't exceed the render dimension (while staying POT)
  72451. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  72452. };
  72453. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72454. var _this = this;
  72455. if (!this._texture) {
  72456. return;
  72457. }
  72458. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  72459. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72460. });
  72461. };
  72462. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  72463. var scene = this.getScene();
  72464. if (!scene) {
  72465. return;
  72466. }
  72467. var engine = scene.getEngine();
  72468. if (!this._texture) {
  72469. return;
  72470. }
  72471. // Bind
  72472. if (this._postProcessManager) {
  72473. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  72474. }
  72475. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  72476. if (this._texture) {
  72477. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  72478. }
  72479. }
  72480. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  72481. // Clear
  72482. if (this.onClearObservable.hasObservers()) {
  72483. this.onClearObservable.notifyObservers(engine);
  72484. }
  72485. else {
  72486. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  72487. }
  72488. if (!this._doNotChangeAspectRatio) {
  72489. scene.updateTransformMatrix(true);
  72490. }
  72491. // Render
  72492. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  72493. if (this._postProcessManager) {
  72494. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  72495. }
  72496. else if (useCameraPostProcess) {
  72497. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  72498. }
  72499. if (!this._doNotChangeAspectRatio) {
  72500. scene.updateTransformMatrix(true);
  72501. }
  72502. // Dump ?
  72503. if (dumpForDebug) {
  72504. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  72505. }
  72506. // Unbind
  72507. if (!this.isCube || faceIndex === 5) {
  72508. if (this.isCube) {
  72509. if (faceIndex === 5) {
  72510. engine.generateMipMapsForCubemap(this._texture);
  72511. }
  72512. }
  72513. this.unbindFrameBuffer(engine, faceIndex);
  72514. }
  72515. else {
  72516. this.onAfterRenderObservable.notifyObservers(faceIndex);
  72517. }
  72518. };
  72519. /**
  72520. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  72521. * This allowed control for front to back rendering or reversly depending of the special needs.
  72522. *
  72523. * @param renderingGroupId The rendering group id corresponding to its index
  72524. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  72525. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  72526. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  72527. */
  72528. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  72529. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  72530. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  72531. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  72532. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  72533. };
  72534. /**
  72535. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  72536. *
  72537. * @param renderingGroupId The rendering group id corresponding to its index
  72538. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  72539. */
  72540. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  72541. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  72542. this._renderingManager._useSceneAutoClearSetup = false;
  72543. };
  72544. /**
  72545. * Clones the texture.
  72546. * @returns the cloned texture
  72547. */
  72548. RenderTargetTexture.prototype.clone = function () {
  72549. var textureSize = this.getSize();
  72550. 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);
  72551. // Base texture
  72552. newTexture.hasAlpha = this.hasAlpha;
  72553. newTexture.level = this.level;
  72554. // RenderTarget Texture
  72555. newTexture.coordinatesMode = this.coordinatesMode;
  72556. if (this.renderList) {
  72557. newTexture.renderList = this.renderList.slice(0);
  72558. }
  72559. return newTexture;
  72560. };
  72561. /**
  72562. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  72563. * @returns The JSON representation of the texture
  72564. */
  72565. RenderTargetTexture.prototype.serialize = function () {
  72566. if (!this.name) {
  72567. return null;
  72568. }
  72569. var serializationObject = _super.prototype.serialize.call(this);
  72570. serializationObject.renderTargetSize = this.getRenderSize();
  72571. serializationObject.renderList = [];
  72572. if (this.renderList) {
  72573. for (var index = 0; index < this.renderList.length; index++) {
  72574. serializationObject.renderList.push(this.renderList[index].id);
  72575. }
  72576. }
  72577. return serializationObject;
  72578. };
  72579. /**
  72580. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  72581. */
  72582. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  72583. var objBuffer = this.getInternalTexture();
  72584. var scene = this.getScene();
  72585. if (objBuffer && scene) {
  72586. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  72587. }
  72588. };
  72589. /**
  72590. * Dispose the texture and release its associated resources.
  72591. */
  72592. RenderTargetTexture.prototype.dispose = function () {
  72593. if (this._postProcessManager) {
  72594. this._postProcessManager.dispose();
  72595. this._postProcessManager = null;
  72596. }
  72597. this.clearPostProcesses(true);
  72598. if (this._resizeObserver) {
  72599. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  72600. this._resizeObserver = null;
  72601. }
  72602. this.renderList = null;
  72603. // Remove from custom render targets
  72604. var scene = this.getScene();
  72605. if (!scene) {
  72606. return;
  72607. }
  72608. var index = scene.customRenderTargets.indexOf(this);
  72609. if (index >= 0) {
  72610. scene.customRenderTargets.splice(index, 1);
  72611. }
  72612. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  72613. var camera = _a[_i];
  72614. index = camera.customRenderTargets.indexOf(this);
  72615. if (index >= 0) {
  72616. camera.customRenderTargets.splice(index, 1);
  72617. }
  72618. }
  72619. _super.prototype.dispose.call(this);
  72620. };
  72621. /** @hidden */
  72622. RenderTargetTexture.prototype._rebuild = function () {
  72623. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72624. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72625. }
  72626. if (this._postProcessManager) {
  72627. this._postProcessManager._rebuild();
  72628. }
  72629. };
  72630. /**
  72631. * Clear the info related to rendering groups preventing retention point in material dispose.
  72632. */
  72633. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  72634. if (this._renderingManager) {
  72635. this._renderingManager.freeRenderingGroups();
  72636. }
  72637. };
  72638. /**
  72639. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  72640. */
  72641. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  72642. /**
  72643. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  72644. */
  72645. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  72646. /**
  72647. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  72648. * the central point of your effect and can save a lot of performances.
  72649. */
  72650. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  72651. return RenderTargetTexture;
  72652. }(BABYLON.Texture));
  72653. BABYLON.RenderTargetTexture = RenderTargetTexture;
  72654. })(BABYLON || (BABYLON = {}));
  72655. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  72656. var BABYLON;
  72657. (function (BABYLON) {
  72658. /**
  72659. * A multi render target, like a render target provides the ability to render to a texture.
  72660. * Unlike the render target, it can render to several draw buffers in one draw.
  72661. * This is specially interesting in deferred rendering or for any effects requiring more than
  72662. * just one color from a single pass.
  72663. */
  72664. var MultiRenderTarget = /** @class */ (function (_super) {
  72665. __extends(MultiRenderTarget, _super);
  72666. /**
  72667. * Instantiate a new multi render target texture.
  72668. * A multi render target, like a render target provides the ability to render to a texture.
  72669. * Unlike the render target, it can render to several draw buffers in one draw.
  72670. * This is specially interesting in deferred rendering or for any effects requiring more than
  72671. * just one color from a single pass.
  72672. * @param name Define the name of the texture
  72673. * @param size Define the size of the buffers to render to
  72674. * @param count Define the number of target we are rendering into
  72675. * @param scene Define the scene the texture belongs to
  72676. * @param options Define the options used to create the multi render target
  72677. */
  72678. function MultiRenderTarget(name, size, count, scene, options) {
  72679. var _this = this;
  72680. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  72681. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  72682. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  72683. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  72684. _this._engine = scene.getEngine();
  72685. if (!_this.isSupported) {
  72686. _this.dispose();
  72687. return;
  72688. }
  72689. var types = [];
  72690. var samplingModes = [];
  72691. for (var i = 0; i < count; i++) {
  72692. if (options && options.types && options.types[i] !== undefined) {
  72693. types.push(options.types[i]);
  72694. }
  72695. else {
  72696. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72697. }
  72698. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  72699. samplingModes.push(options.samplingModes[i]);
  72700. }
  72701. else {
  72702. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72703. }
  72704. }
  72705. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  72706. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  72707. _this._size = size;
  72708. _this._multiRenderTargetOptions = {
  72709. samplingModes: samplingModes,
  72710. generateMipMaps: generateMipMaps,
  72711. generateDepthBuffer: generateDepthBuffer,
  72712. generateStencilBuffer: generateStencilBuffer,
  72713. generateDepthTexture: generateDepthTexture,
  72714. types: types,
  72715. textureCount: count
  72716. };
  72717. _this._createInternalTextures();
  72718. _this._createTextures();
  72719. return _this;
  72720. }
  72721. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  72722. /**
  72723. * Get if draw buffers are currently supported by the used hardware and browser.
  72724. */
  72725. get: function () {
  72726. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  72727. },
  72728. enumerable: true,
  72729. configurable: true
  72730. });
  72731. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  72732. /**
  72733. * Get the list of textures generated by the multi render target.
  72734. */
  72735. get: function () {
  72736. return this._textures;
  72737. },
  72738. enumerable: true,
  72739. configurable: true
  72740. });
  72741. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  72742. /**
  72743. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  72744. */
  72745. get: function () {
  72746. return this._textures[this._textures.length - 1];
  72747. },
  72748. enumerable: true,
  72749. configurable: true
  72750. });
  72751. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  72752. /**
  72753. * Set the wrapping mode on U of all the textures we are rendering to.
  72754. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72755. */
  72756. set: function (wrap) {
  72757. if (this._textures) {
  72758. for (var i = 0; i < this._textures.length; i++) {
  72759. this._textures[i].wrapU = wrap;
  72760. }
  72761. }
  72762. },
  72763. enumerable: true,
  72764. configurable: true
  72765. });
  72766. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  72767. /**
  72768. * Set the wrapping mode on V of all the textures we are rendering to.
  72769. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72770. */
  72771. set: function (wrap) {
  72772. if (this._textures) {
  72773. for (var i = 0; i < this._textures.length; i++) {
  72774. this._textures[i].wrapV = wrap;
  72775. }
  72776. }
  72777. },
  72778. enumerable: true,
  72779. configurable: true
  72780. });
  72781. /** @hidden */
  72782. MultiRenderTarget.prototype._rebuild = function () {
  72783. this.releaseInternalTextures();
  72784. this._createInternalTextures();
  72785. for (var i = 0; i < this._internalTextures.length; i++) {
  72786. var texture = this._textures[i];
  72787. texture._texture = this._internalTextures[i];
  72788. }
  72789. // Keeps references to frame buffer and stencil/depth buffer
  72790. this._texture = this._internalTextures[0];
  72791. };
  72792. MultiRenderTarget.prototype._createInternalTextures = function () {
  72793. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  72794. };
  72795. MultiRenderTarget.prototype._createTextures = function () {
  72796. this._textures = [];
  72797. for (var i = 0; i < this._internalTextures.length; i++) {
  72798. var texture = new BABYLON.Texture(null, this.getScene());
  72799. texture._texture = this._internalTextures[i];
  72800. this._textures.push(texture);
  72801. }
  72802. // Keeps references to frame buffer and stencil/depth buffer
  72803. this._texture = this._internalTextures[0];
  72804. };
  72805. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  72806. /**
  72807. * Define the number of samples used if MSAA is enabled.
  72808. */
  72809. get: function () {
  72810. return this._samples;
  72811. },
  72812. set: function (value) {
  72813. if (this._samples === value) {
  72814. return;
  72815. }
  72816. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  72817. },
  72818. enumerable: true,
  72819. configurable: true
  72820. });
  72821. /**
  72822. * Resize all the textures in the multi render target.
  72823. * Be carrefull as it will recreate all the data in the new texture.
  72824. * @param size Define the new size
  72825. */
  72826. MultiRenderTarget.prototype.resize = function (size) {
  72827. this.releaseInternalTextures();
  72828. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  72829. this._createInternalTextures();
  72830. };
  72831. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72832. var _this = this;
  72833. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  72834. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72835. });
  72836. };
  72837. /**
  72838. * Dispose the render targets and their associated resources
  72839. */
  72840. MultiRenderTarget.prototype.dispose = function () {
  72841. this.releaseInternalTextures();
  72842. _super.prototype.dispose.call(this);
  72843. };
  72844. /**
  72845. * Release all the underlying texture used as draw buffers.
  72846. */
  72847. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  72848. if (!this._internalTextures) {
  72849. return;
  72850. }
  72851. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  72852. if (this._internalTextures[i] !== undefined) {
  72853. this._internalTextures[i].dispose();
  72854. this._internalTextures.splice(i, 1);
  72855. }
  72856. }
  72857. };
  72858. return MultiRenderTarget;
  72859. }(BABYLON.RenderTargetTexture));
  72860. BABYLON.MultiRenderTarget = MultiRenderTarget;
  72861. })(BABYLON || (BABYLON = {}));
  72862. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  72863. var BABYLON;
  72864. (function (BABYLON) {
  72865. /**
  72866. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72867. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72868. * You can then easily use it as a reflectionTexture on a flat surface.
  72869. * In case the surface is not a plane, please consider relying on reflection probes.
  72870. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72871. */
  72872. var MirrorTexture = /** @class */ (function (_super) {
  72873. __extends(MirrorTexture, _super);
  72874. /**
  72875. * Instantiates a Mirror Texture.
  72876. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72877. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72878. * You can then easily use it as a reflectionTexture on a flat surface.
  72879. * In case the surface is not a plane, please consider relying on reflection probes.
  72880. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72881. * @param name
  72882. * @param size
  72883. * @param scene
  72884. * @param generateMipMaps
  72885. * @param type
  72886. * @param samplingMode
  72887. * @param generateDepthBuffer
  72888. */
  72889. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  72890. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72892. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  72893. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  72894. _this.scene = scene;
  72895. /**
  72896. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  72897. * 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.
  72898. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72899. */
  72900. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  72901. _this._transformMatrix = BABYLON.Matrix.Zero();
  72902. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  72903. _this._adaptiveBlurKernel = 0;
  72904. _this._blurKernelX = 0;
  72905. _this._blurKernelY = 0;
  72906. _this._blurRatio = 1.0;
  72907. _this.ignoreCameraViewport = true;
  72908. _this._updateGammaSpace();
  72909. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  72910. _this._updateGammaSpace;
  72911. });
  72912. _this.onBeforeRenderObservable.add(function () {
  72913. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  72914. _this._savedViewMatrix = scene.getViewMatrix();
  72915. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  72916. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  72917. scene.clipPlane = _this.mirrorPlane;
  72918. scene.getEngine().cullBackFaces = false;
  72919. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  72920. });
  72921. _this.onAfterRenderObservable.add(function () {
  72922. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  72923. scene.getEngine().cullBackFaces = true;
  72924. scene._mirroredCameraPosition = null;
  72925. delete scene.clipPlane;
  72926. });
  72927. return _this;
  72928. }
  72929. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  72930. get: function () {
  72931. return this._blurRatio;
  72932. },
  72933. /**
  72934. * Define the blur ratio used to blur the reflection if needed.
  72935. */
  72936. set: function (value) {
  72937. if (this._blurRatio === value) {
  72938. return;
  72939. }
  72940. this._blurRatio = value;
  72941. this._preparePostProcesses();
  72942. },
  72943. enumerable: true,
  72944. configurable: true
  72945. });
  72946. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  72947. /**
  72948. * Define the adaptive blur kernel used to blur the reflection if needed.
  72949. * This will autocompute the closest best match for the `blurKernel`
  72950. */
  72951. set: function (value) {
  72952. this._adaptiveBlurKernel = value;
  72953. this._autoComputeBlurKernel();
  72954. },
  72955. enumerable: true,
  72956. configurable: true
  72957. });
  72958. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  72959. /**
  72960. * Define the blur kernel used to blur the reflection if needed.
  72961. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72962. */
  72963. set: function (value) {
  72964. this.blurKernelX = value;
  72965. this.blurKernelY = value;
  72966. },
  72967. enumerable: true,
  72968. configurable: true
  72969. });
  72970. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  72971. get: function () {
  72972. return this._blurKernelX;
  72973. },
  72974. /**
  72975. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  72976. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72977. */
  72978. set: function (value) {
  72979. if (this._blurKernelX === value) {
  72980. return;
  72981. }
  72982. this._blurKernelX = value;
  72983. this._preparePostProcesses();
  72984. },
  72985. enumerable: true,
  72986. configurable: true
  72987. });
  72988. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  72989. get: function () {
  72990. return this._blurKernelY;
  72991. },
  72992. /**
  72993. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  72994. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72995. */
  72996. set: function (value) {
  72997. if (this._blurKernelY === value) {
  72998. return;
  72999. }
  73000. this._blurKernelY = value;
  73001. this._preparePostProcesses();
  73002. },
  73003. enumerable: true,
  73004. configurable: true
  73005. });
  73006. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  73007. var engine = this.getScene().getEngine();
  73008. var dw = this.getRenderWidth() / engine.getRenderWidth();
  73009. var dh = this.getRenderHeight() / engine.getRenderHeight();
  73010. this.blurKernelX = this._adaptiveBlurKernel * dw;
  73011. this.blurKernelY = this._adaptiveBlurKernel * dh;
  73012. };
  73013. MirrorTexture.prototype._onRatioRescale = function () {
  73014. if (this._sizeRatio) {
  73015. this.resize(this._initialSizeParameter);
  73016. if (!this._adaptiveBlurKernel) {
  73017. this._preparePostProcesses();
  73018. }
  73019. }
  73020. if (this._adaptiveBlurKernel) {
  73021. this._autoComputeBlurKernel();
  73022. }
  73023. };
  73024. MirrorTexture.prototype._updateGammaSpace = function () {
  73025. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  73026. };
  73027. MirrorTexture.prototype._preparePostProcesses = function () {
  73028. this.clearPostProcesses(true);
  73029. if (this._blurKernelX && this._blurKernelY) {
  73030. var engine = this.getScene().getEngine();
  73031. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73032. 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);
  73033. this._blurX.autoClear = false;
  73034. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  73035. this._blurX.inputTexture = this._texture;
  73036. }
  73037. else {
  73038. this._blurX.alwaysForcePOT = true;
  73039. }
  73040. 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);
  73041. this._blurY.autoClear = false;
  73042. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  73043. this.addPostProcess(this._blurX);
  73044. this.addPostProcess(this._blurY);
  73045. }
  73046. else {
  73047. if (this._blurY) {
  73048. this.removePostProcess(this._blurY);
  73049. this._blurY.dispose();
  73050. this._blurY = null;
  73051. }
  73052. if (this._blurX) {
  73053. this.removePostProcess(this._blurX);
  73054. this._blurX.dispose();
  73055. this._blurX = null;
  73056. }
  73057. }
  73058. };
  73059. /**
  73060. * Clone the mirror texture.
  73061. * @returns the cloned texture
  73062. */
  73063. MirrorTexture.prototype.clone = function () {
  73064. var scene = this.getScene();
  73065. if (!scene) {
  73066. return this;
  73067. }
  73068. var textureSize = this.getSize();
  73069. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  73070. // Base texture
  73071. newTexture.hasAlpha = this.hasAlpha;
  73072. newTexture.level = this.level;
  73073. // Mirror Texture
  73074. newTexture.mirrorPlane = this.mirrorPlane.clone();
  73075. if (this.renderList) {
  73076. newTexture.renderList = this.renderList.slice(0);
  73077. }
  73078. return newTexture;
  73079. };
  73080. /**
  73081. * Serialize the texture to a JSON representation you could use in Parse later on
  73082. * @returns the serialized JSON representation
  73083. */
  73084. MirrorTexture.prototype.serialize = function () {
  73085. if (!this.name) {
  73086. return null;
  73087. }
  73088. var serializationObject = _super.prototype.serialize.call(this);
  73089. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  73090. return serializationObject;
  73091. };
  73092. /**
  73093. * Dispose the texture and release its associated resources.
  73094. */
  73095. MirrorTexture.prototype.dispose = function () {
  73096. _super.prototype.dispose.call(this);
  73097. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  73098. };
  73099. return MirrorTexture;
  73100. }(BABYLON.RenderTargetTexture));
  73101. BABYLON.MirrorTexture = MirrorTexture;
  73102. })(BABYLON || (BABYLON = {}));
  73103. //# sourceMappingURL=babylon.mirrorTexture.js.map
  73104. var BABYLON;
  73105. (function (BABYLON) {
  73106. /**
  73107. * Creates a refraction texture used by refraction channel of the standard material.
  73108. * It is like a mirror but to see through a material.
  73109. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73110. */
  73111. var RefractionTexture = /** @class */ (function (_super) {
  73112. __extends(RefractionTexture, _super);
  73113. /**
  73114. * Creates a refraction texture used by refraction channel of the standard material.
  73115. * It is like a mirror but to see through a material.
  73116. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73117. * @param name Define the texture name
  73118. * @param size Define the size of the underlying texture
  73119. * @param scene Define the scene the refraction belongs to
  73120. * @param generateMipMaps Define if we need to generate mips level for the refraction
  73121. */
  73122. function RefractionTexture(name, size, scene, generateMipMaps) {
  73123. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  73124. /**
  73125. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  73126. * 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.
  73127. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73128. */
  73129. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  73130. /**
  73131. * Define how deep under the surface we should see.
  73132. */
  73133. _this.depth = 2.0;
  73134. _this.onBeforeRenderObservable.add(function () {
  73135. scene.clipPlane = _this.refractionPlane;
  73136. });
  73137. _this.onAfterRenderObservable.add(function () {
  73138. delete scene.clipPlane;
  73139. });
  73140. return _this;
  73141. }
  73142. /**
  73143. * Clone the refraction texture.
  73144. * @returns the cloned texture
  73145. */
  73146. RefractionTexture.prototype.clone = function () {
  73147. var scene = this.getScene();
  73148. if (!scene) {
  73149. return this;
  73150. }
  73151. var textureSize = this.getSize();
  73152. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  73153. // Base texture
  73154. newTexture.hasAlpha = this.hasAlpha;
  73155. newTexture.level = this.level;
  73156. // Refraction Texture
  73157. newTexture.refractionPlane = this.refractionPlane.clone();
  73158. if (this.renderList) {
  73159. newTexture.renderList = this.renderList.slice(0);
  73160. }
  73161. newTexture.depth = this.depth;
  73162. return newTexture;
  73163. };
  73164. /**
  73165. * Serialize the texture to a JSON representation you could use in Parse later on
  73166. * @returns the serialized JSON representation
  73167. */
  73168. RefractionTexture.prototype.serialize = function () {
  73169. if (!this.name) {
  73170. return null;
  73171. }
  73172. var serializationObject = _super.prototype.serialize.call(this);
  73173. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  73174. serializationObject.depth = this.depth;
  73175. return serializationObject;
  73176. };
  73177. return RefractionTexture;
  73178. }(BABYLON.RenderTargetTexture));
  73179. BABYLON.RefractionTexture = RefractionTexture;
  73180. })(BABYLON || (BABYLON = {}));
  73181. //# sourceMappingURL=babylon.refractionTexture.js.map
  73182. var BABYLON;
  73183. (function (BABYLON) {
  73184. /**
  73185. * A class extending Texture allowing drawing on a texture
  73186. * @see http://doc.babylonjs.com/how_to/dynamictexture
  73187. */
  73188. var DynamicTexture = /** @class */ (function (_super) {
  73189. __extends(DynamicTexture, _super);
  73190. /**
  73191. * Creates a DynamicTexture
  73192. * @param name defines the name of the texture
  73193. * @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
  73194. * @param scene defines the scene where you want the texture
  73195. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  73196. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  73197. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  73198. */
  73199. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  73200. if (scene === void 0) { scene = null; }
  73201. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73202. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73203. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  73204. _this.name = name;
  73205. _this._engine = _this.getScene().getEngine();
  73206. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73207. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73208. _this._generateMipMaps = generateMipMaps;
  73209. if (options.getContext) {
  73210. _this._canvas = options;
  73211. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  73212. }
  73213. else {
  73214. _this._canvas = document.createElement("canvas");
  73215. if (options.width || options.width === 0) {
  73216. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  73217. }
  73218. else {
  73219. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  73220. }
  73221. }
  73222. var textureSize = _this.getSize();
  73223. _this._canvas.width = textureSize.width;
  73224. _this._canvas.height = textureSize.height;
  73225. _this._context = _this._canvas.getContext("2d");
  73226. return _this;
  73227. }
  73228. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  73229. /**
  73230. * Gets the current state of canRescale
  73231. */
  73232. get: function () {
  73233. return true;
  73234. },
  73235. enumerable: true,
  73236. configurable: true
  73237. });
  73238. DynamicTexture.prototype._recreate = function (textureSize) {
  73239. this._canvas.width = textureSize.width;
  73240. this._canvas.height = textureSize.height;
  73241. this.releaseInternalTexture();
  73242. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  73243. };
  73244. /**
  73245. * Scales the texture
  73246. * @param ratio the scale factor to apply to both width and height
  73247. */
  73248. DynamicTexture.prototype.scale = function (ratio) {
  73249. var textureSize = this.getSize();
  73250. textureSize.width *= ratio;
  73251. textureSize.height *= ratio;
  73252. this._recreate(textureSize);
  73253. };
  73254. /**
  73255. * Resizes the texture
  73256. * @param width the new width
  73257. * @param height the new height
  73258. */
  73259. DynamicTexture.prototype.scaleTo = function (width, height) {
  73260. var textureSize = this.getSize();
  73261. textureSize.width = width;
  73262. textureSize.height = height;
  73263. this._recreate(textureSize);
  73264. };
  73265. /**
  73266. * Gets the context of the canvas used by the texture
  73267. * @returns the canvas context of the dynamic texture
  73268. */
  73269. DynamicTexture.prototype.getContext = function () {
  73270. return this._context;
  73271. };
  73272. /**
  73273. * Clears the texture
  73274. */
  73275. DynamicTexture.prototype.clear = function () {
  73276. var size = this.getSize();
  73277. this._context.fillRect(0, 0, size.width, size.height);
  73278. };
  73279. /**
  73280. * Updates the texture
  73281. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73282. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  73283. */
  73284. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  73285. if (premulAlpha === void 0) { premulAlpha = false; }
  73286. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  73287. };
  73288. /**
  73289. * Draws text onto the texture
  73290. * @param text defines the text to be drawn
  73291. * @param x defines the placement of the text from the left
  73292. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  73293. * @param font defines the font to be used with font-style, font-size, font-name
  73294. * @param color defines the color used for the text
  73295. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  73296. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73297. * @param update defines whether texture is immediately update (default is true)
  73298. */
  73299. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  73300. if (update === void 0) { update = true; }
  73301. var size = this.getSize();
  73302. if (clearColor) {
  73303. this._context.fillStyle = clearColor;
  73304. this._context.fillRect(0, 0, size.width, size.height);
  73305. }
  73306. this._context.font = font;
  73307. if (x === null || x === undefined) {
  73308. var textSize = this._context.measureText(text);
  73309. x = (size.width - textSize.width) / 2;
  73310. }
  73311. if (y === null || y === undefined) {
  73312. var fontSize = parseInt((font.replace(/\D/g, '')));
  73313. y = (size.height / 2) + (fontSize / 3.65);
  73314. }
  73315. this._context.fillStyle = color;
  73316. this._context.fillText(text, x, y);
  73317. if (update) {
  73318. this.update(invertY);
  73319. }
  73320. };
  73321. /**
  73322. * Clones the texture
  73323. * @returns the clone of the texture.
  73324. */
  73325. DynamicTexture.prototype.clone = function () {
  73326. var scene = this.getScene();
  73327. if (!scene) {
  73328. return this;
  73329. }
  73330. var textureSize = this.getSize();
  73331. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  73332. // Base texture
  73333. newTexture.hasAlpha = this.hasAlpha;
  73334. newTexture.level = this.level;
  73335. // Dynamic Texture
  73336. newTexture.wrapU = this.wrapU;
  73337. newTexture.wrapV = this.wrapV;
  73338. return newTexture;
  73339. };
  73340. /**
  73341. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  73342. * @returns a serialized dynamic texture object
  73343. */
  73344. DynamicTexture.prototype.serialize = function () {
  73345. var scene = this.getScene();
  73346. if (scene && !scene.isReady()) {
  73347. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  73348. }
  73349. var serializationObject = _super.prototype.serialize.call(this);
  73350. serializationObject.base64String = this._canvas.toDataURL();
  73351. serializationObject.invertY = this._invertY;
  73352. serializationObject.samplingMode = this.samplingMode;
  73353. return serializationObject;
  73354. };
  73355. /** @hidden */
  73356. DynamicTexture.prototype._rebuild = function () {
  73357. this.update();
  73358. };
  73359. return DynamicTexture;
  73360. }(BABYLON.Texture));
  73361. BABYLON.DynamicTexture = DynamicTexture;
  73362. })(BABYLON || (BABYLON = {}));
  73363. //# sourceMappingURL=babylon.dynamicTexture.js.map
  73364. var BABYLON;
  73365. (function (BABYLON) {
  73366. /**
  73367. * If you want to display a video in your scene, this is the special texture for that.
  73368. * This special texture works similar to other textures, with the exception of a few parameters.
  73369. * @see https://doc.babylonjs.com/how_to/video_texture
  73370. */
  73371. var VideoTexture = /** @class */ (function (_super) {
  73372. __extends(VideoTexture, _super);
  73373. /**
  73374. * Creates a video texture.
  73375. * If you want to display a video in your scene, this is the special texture for that.
  73376. * This special texture works similar to other textures, with the exception of a few parameters.
  73377. * @see https://doc.babylonjs.com/how_to/video_texture
  73378. * @param name optional name, will detect from video source, if not defined
  73379. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  73380. * @param scene is obviously the current scene.
  73381. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  73382. * @param invertY is false by default but can be used to invert video on Y axis
  73383. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  73384. * @param settings allows finer control over video usage
  73385. */
  73386. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  73387. if (generateMipMaps === void 0) { generateMipMaps = false; }
  73388. if (invertY === void 0) { invertY = false; }
  73389. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73390. if (settings === void 0) { settings = {
  73391. autoPlay: true,
  73392. loop: true,
  73393. autoUpdateTexture: true,
  73394. }; }
  73395. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73396. _this._onUserActionRequestedObservable = null;
  73397. _this._stillImageCaptured = false;
  73398. _this._poster = false;
  73399. _this._createInternalTexture = function () {
  73400. if (_this._texture != null) {
  73401. if (_this._poster) {
  73402. _this._texture.dispose();
  73403. _this._poster = false;
  73404. }
  73405. else {
  73406. return;
  73407. }
  73408. }
  73409. if (!_this._engine.needPOTTextures ||
  73410. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  73411. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73412. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73413. }
  73414. else {
  73415. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73416. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73417. _this._generateMipMaps = false;
  73418. }
  73419. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  73420. if (!_this.video.autoplay) {
  73421. var oldHandler_1 = _this.video.onplaying;
  73422. var error_1 = false;
  73423. _this.video.onplaying = function () {
  73424. _this.video.onplaying = oldHandler_1;
  73425. _this._texture.isReady = true;
  73426. _this._updateInternalTexture();
  73427. if (!error_1) {
  73428. _this.video.pause();
  73429. }
  73430. if (_this.onLoadObservable.hasObservers()) {
  73431. _this.onLoadObservable.notifyObservers(_this);
  73432. }
  73433. };
  73434. var playing = _this.video.play();
  73435. if (playing) {
  73436. playing.then(function () {
  73437. // Everything is good.
  73438. })
  73439. .catch(function () {
  73440. error_1 = true;
  73441. // On Chrome for instance, new policies might prevent playing without user interaction.
  73442. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  73443. _this._onUserActionRequestedObservable.notifyObservers(_this);
  73444. }
  73445. });
  73446. }
  73447. else {
  73448. _this.video.onplaying = oldHandler_1;
  73449. _this._texture.isReady = true;
  73450. _this._updateInternalTexture();
  73451. if (_this.onLoadObservable.hasObservers()) {
  73452. _this.onLoadObservable.notifyObservers(_this);
  73453. }
  73454. }
  73455. }
  73456. else {
  73457. _this._texture.isReady = true;
  73458. _this._updateInternalTexture();
  73459. if (_this.onLoadObservable.hasObservers()) {
  73460. _this.onLoadObservable.notifyObservers(_this);
  73461. }
  73462. }
  73463. };
  73464. _this.reset = function () {
  73465. if (_this._texture == null) {
  73466. return;
  73467. }
  73468. if (!_this._poster) {
  73469. _this._texture.dispose();
  73470. _this._texture = null;
  73471. }
  73472. };
  73473. _this._updateInternalTexture = function (e) {
  73474. if (_this._texture == null || !_this._texture.isReady) {
  73475. return;
  73476. }
  73477. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  73478. return;
  73479. }
  73480. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  73481. };
  73482. _this._engine = _this.getScene().getEngine();
  73483. _this._generateMipMaps = generateMipMaps;
  73484. _this._samplingMode = samplingMode;
  73485. _this.autoUpdateTexture = settings.autoUpdateTexture;
  73486. _this.name = name || _this._getName(src);
  73487. _this.video = _this._getVideo(src);
  73488. if (settings.poster) {
  73489. _this.video.poster = settings.poster;
  73490. }
  73491. if (settings.autoPlay !== undefined) {
  73492. _this.video.autoplay = settings.autoPlay;
  73493. }
  73494. if (settings.loop !== undefined) {
  73495. _this.video.loop = settings.loop;
  73496. }
  73497. _this.video.setAttribute("playsinline", "");
  73498. _this.video.addEventListener("canplay", _this._createInternalTexture);
  73499. _this.video.addEventListener("paused", _this._updateInternalTexture);
  73500. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  73501. _this.video.addEventListener("emptied", _this.reset);
  73502. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  73503. _this._createInternalTexture();
  73504. }
  73505. if (settings.poster) {
  73506. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  73507. _this._poster = true;
  73508. }
  73509. return _this;
  73510. }
  73511. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  73512. /**
  73513. * Event triggerd when a dom action is required by the user to play the video.
  73514. * This happens due to recent changes in browser policies preventing video to auto start.
  73515. */
  73516. get: function () {
  73517. if (!this._onUserActionRequestedObservable) {
  73518. this._onUserActionRequestedObservable = new BABYLON.Observable();
  73519. }
  73520. return this._onUserActionRequestedObservable;
  73521. },
  73522. enumerable: true,
  73523. configurable: true
  73524. });
  73525. VideoTexture.prototype._getName = function (src) {
  73526. if (src instanceof HTMLVideoElement) {
  73527. return src.currentSrc;
  73528. }
  73529. if (typeof src === "object") {
  73530. return src.toString();
  73531. }
  73532. return src;
  73533. };
  73534. VideoTexture.prototype._getVideo = function (src) {
  73535. if (src instanceof HTMLVideoElement) {
  73536. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  73537. return src;
  73538. }
  73539. var video = document.createElement("video");
  73540. if (typeof src === "string") {
  73541. BABYLON.Tools.SetCorsBehavior(src, video);
  73542. video.src = src;
  73543. }
  73544. else {
  73545. BABYLON.Tools.SetCorsBehavior(src[0], video);
  73546. src.forEach(function (url) {
  73547. var source = document.createElement("source");
  73548. source.src = url;
  73549. video.appendChild(source);
  73550. });
  73551. }
  73552. return video;
  73553. };
  73554. /**
  73555. * @hidden Internal method to initiate `update`.
  73556. */
  73557. VideoTexture.prototype._rebuild = function () {
  73558. this.update();
  73559. };
  73560. /**
  73561. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  73562. */
  73563. VideoTexture.prototype.update = function () {
  73564. if (!this.autoUpdateTexture) {
  73565. // Expecting user to call `updateTexture` manually
  73566. return;
  73567. }
  73568. this.updateTexture(true);
  73569. };
  73570. /**
  73571. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  73572. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  73573. */
  73574. VideoTexture.prototype.updateTexture = function (isVisible) {
  73575. if (!isVisible) {
  73576. return;
  73577. }
  73578. if (this.video.paused && this._stillImageCaptured) {
  73579. return;
  73580. }
  73581. this._stillImageCaptured = true;
  73582. this._updateInternalTexture();
  73583. };
  73584. /**
  73585. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  73586. * @param url New url.
  73587. */
  73588. VideoTexture.prototype.updateURL = function (url) {
  73589. this.video.src = url;
  73590. };
  73591. /**
  73592. * Dispose the texture and release its associated resources.
  73593. */
  73594. VideoTexture.prototype.dispose = function () {
  73595. _super.prototype.dispose.call(this);
  73596. if (this._onUserActionRequestedObservable) {
  73597. this._onUserActionRequestedObservable.clear();
  73598. this._onUserActionRequestedObservable = null;
  73599. }
  73600. this.video.removeEventListener("canplay", this._createInternalTexture);
  73601. this.video.removeEventListener("paused", this._updateInternalTexture);
  73602. this.video.removeEventListener("seeked", this._updateInternalTexture);
  73603. this.video.removeEventListener("emptied", this.reset);
  73604. this.video.pause();
  73605. };
  73606. /**
  73607. * Creates a video texture straight from your WebCam video feed.
  73608. * @param scene Define the scene the texture should be created in
  73609. * @param onReady Define a callback to triggered once the texture will be ready
  73610. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  73611. */
  73612. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  73613. var video = document.createElement("video");
  73614. video.setAttribute('autoplay', '');
  73615. video.setAttribute('muted', '');
  73616. video.setAttribute('playsinline', '');
  73617. var constraintsDeviceId;
  73618. if (constraints && constraints.deviceId) {
  73619. constraintsDeviceId = {
  73620. exact: constraints.deviceId,
  73621. };
  73622. }
  73623. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  73624. if (navigator.mediaDevices) {
  73625. navigator.mediaDevices.getUserMedia({ video: constraints })
  73626. .then(function (stream) {
  73627. if (video.mozSrcObject !== undefined) {
  73628. // hack for Firefox < 19
  73629. video.mozSrcObject = stream;
  73630. }
  73631. else {
  73632. video.srcObject = stream;
  73633. }
  73634. var onPlaying = function () {
  73635. if (onReady) {
  73636. onReady(new VideoTexture("video", video, scene, true, true));
  73637. }
  73638. video.removeEventListener("playing", onPlaying);
  73639. };
  73640. video.addEventListener("playing", onPlaying);
  73641. video.play();
  73642. })
  73643. .catch(function (err) {
  73644. BABYLON.Tools.Error(err.name);
  73645. });
  73646. }
  73647. else {
  73648. navigator.getUserMedia =
  73649. navigator.getUserMedia ||
  73650. navigator.webkitGetUserMedia ||
  73651. navigator.mozGetUserMedia ||
  73652. navigator.msGetUserMedia;
  73653. if (navigator.getUserMedia) {
  73654. navigator.getUserMedia({
  73655. video: {
  73656. deviceId: constraintsDeviceId,
  73657. width: {
  73658. min: (constraints && constraints.minWidth) || 256,
  73659. max: (constraints && constraints.maxWidth) || 640,
  73660. },
  73661. height: {
  73662. min: (constraints && constraints.minHeight) || 256,
  73663. max: (constraints && constraints.maxHeight) || 480,
  73664. },
  73665. },
  73666. }, function (stream) {
  73667. if (video.mozSrcObject !== undefined) {
  73668. // hack for Firefox < 19
  73669. video.mozSrcObject = stream;
  73670. }
  73671. else {
  73672. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  73673. }
  73674. video.play();
  73675. if (onReady) {
  73676. onReady(new VideoTexture("video", video, scene, true, true));
  73677. }
  73678. }, function (e) {
  73679. BABYLON.Tools.Error(e.name);
  73680. });
  73681. }
  73682. }
  73683. };
  73684. return VideoTexture;
  73685. }(BABYLON.Texture));
  73686. BABYLON.VideoTexture = VideoTexture;
  73687. })(BABYLON || (BABYLON = {}));
  73688. //# sourceMappingURL=babylon.videoTexture.js.map
  73689. var BABYLON;
  73690. (function (BABYLON) {
  73691. /**
  73692. * Raw texture can help creating a texture directly from an array of data.
  73693. * This can be super useful if you either get the data from an uncompressed source or
  73694. * if you wish to create your texture pixel by pixel.
  73695. */
  73696. var RawTexture = /** @class */ (function (_super) {
  73697. __extends(RawTexture, _super);
  73698. /**
  73699. * Instantiates a new RawTexture.
  73700. * Raw texture can help creating a texture directly from an array of data.
  73701. * This can be super useful if you either get the data from an uncompressed source or
  73702. * if you wish to create your texture pixel by pixel.
  73703. * @param data define the array of data to use to create the texture
  73704. * @param width define the width of the texture
  73705. * @param height define the height of the texture
  73706. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73707. * @param scene define the scene the texture belongs to
  73708. * @param generateMipMaps define whether mip maps should be generated or not
  73709. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73710. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73711. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73712. */
  73713. function RawTexture(data, width, height,
  73714. /**
  73715. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73716. */
  73717. format, scene, generateMipMaps, invertY, samplingMode, type) {
  73718. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73719. if (invertY === void 0) { invertY = false; }
  73720. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73721. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73722. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73723. _this.format = format;
  73724. _this._engine = scene.getEngine();
  73725. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  73726. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73727. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73728. return _this;
  73729. }
  73730. /**
  73731. * Updates the texture underlying data.
  73732. * @param data Define the new data of the texture
  73733. */
  73734. RawTexture.prototype.update = function (data) {
  73735. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73736. };
  73737. /**
  73738. * Creates a luminance texture from some data.
  73739. * @param data Define the texture data
  73740. * @param width Define the width of the texture
  73741. * @param height Define the height of the texture
  73742. * @param scene Define the scene the texture belongs to
  73743. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73744. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73745. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73746. * @returns the luminance texture
  73747. */
  73748. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73749. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73750. if (invertY === void 0) { invertY = false; }
  73751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73752. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  73753. };
  73754. /**
  73755. * Creates a luminance alpha texture from some data.
  73756. * @param data Define the texture data
  73757. * @param width Define the width of the texture
  73758. * @param height Define the height of the texture
  73759. * @param scene Define the scene the texture belongs to
  73760. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73761. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73762. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73763. * @returns the luminance alpha texture
  73764. */
  73765. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73766. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73767. if (invertY === void 0) { invertY = false; }
  73768. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73769. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73770. };
  73771. /**
  73772. * Creates an alpha texture from some data.
  73773. * @param data Define the texture data
  73774. * @param width Define the width of the texture
  73775. * @param height Define the height of the texture
  73776. * @param scene Define the scene the texture belongs to
  73777. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73778. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73779. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73780. * @returns the alpha texture
  73781. */
  73782. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73783. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73784. if (invertY === void 0) { invertY = false; }
  73785. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73786. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73787. };
  73788. /**
  73789. * Creates a RGB texture from some data.
  73790. * @param data Define the texture data
  73791. * @param width Define the width of the texture
  73792. * @param height Define the height of the texture
  73793. * @param scene Define the scene the texture belongs to
  73794. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73795. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73796. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73797. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73798. * @returns the RGB alpha texture
  73799. */
  73800. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73801. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73802. if (invertY === void 0) { invertY = false; }
  73803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73804. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73805. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  73806. };
  73807. /**
  73808. * Creates a RGBA texture from some data.
  73809. * @param data Define the texture data
  73810. * @param width Define the width of the texture
  73811. * @param height Define the height of the texture
  73812. * @param scene Define the scene the texture belongs to
  73813. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73814. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73815. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73816. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73817. * @returns the RGBA texture
  73818. */
  73819. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73820. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73821. if (invertY === void 0) { invertY = false; }
  73822. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73823. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73824. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  73825. };
  73826. /**
  73827. * Creates a R texture from some data.
  73828. * @param data Define the texture data
  73829. * @param width Define the width of the texture
  73830. * @param height Define the height of the texture
  73831. * @param scene Define the scene the texture belongs to
  73832. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73833. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73834. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73835. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73836. * @returns the R texture
  73837. */
  73838. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73839. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73840. if (invertY === void 0) { invertY = false; }
  73841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73842. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73843. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  73844. };
  73845. return RawTexture;
  73846. }(BABYLON.Texture));
  73847. BABYLON.RawTexture = RawTexture;
  73848. })(BABYLON || (BABYLON = {}));
  73849. //# sourceMappingURL=babylon.rawTexture.js.map
  73850. var BABYLON;
  73851. (function (BABYLON) {
  73852. /**
  73853. * Class used to store 3D textures containing user data
  73854. */
  73855. var RawTexture3D = /** @class */ (function (_super) {
  73856. __extends(RawTexture3D, _super);
  73857. /**
  73858. * Create a new RawTexture3D
  73859. * @param data defines the data of the texture
  73860. * @param width defines the width of the texture
  73861. * @param height defines the height of the texture
  73862. * @param depth defines the depth of the texture
  73863. * @param format defines the texture format to use
  73864. * @param scene defines the hosting scene
  73865. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  73866. * @param invertY defines if texture must be stored with Y axis inverted
  73867. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  73868. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  73869. */
  73870. function RawTexture3D(data, width, height, depth,
  73871. /** Gets or sets the texture format to use */
  73872. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  73873. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73874. if (invertY === void 0) { invertY = false; }
  73875. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73876. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73877. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73878. _this.format = format;
  73879. _this._engine = scene.getEngine();
  73880. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  73881. _this.is3D = true;
  73882. return _this;
  73883. }
  73884. /**
  73885. * Update the texture with new data
  73886. * @param data defines the data to store in the texture
  73887. */
  73888. RawTexture3D.prototype.update = function (data) {
  73889. if (!this._texture) {
  73890. return;
  73891. }
  73892. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73893. };
  73894. return RawTexture3D;
  73895. }(BABYLON.Texture));
  73896. BABYLON.RawTexture3D = RawTexture3D;
  73897. })(BABYLON || (BABYLON = {}));
  73898. //# sourceMappingURL=babylon.rawTexture3D.js.map
  73899. var BABYLON;
  73900. (function (BABYLON) {
  73901. /**
  73902. * PostProcessManager is used to manage one or more post processes or post process pipelines
  73903. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73904. */
  73905. var PostProcessManager = /** @class */ (function () {
  73906. /**
  73907. * Creates a new instance PostProcess
  73908. * @param scene The scene that the post process is associated with.
  73909. */
  73910. function PostProcessManager(scene) {
  73911. this._vertexBuffers = {};
  73912. this._scene = scene;
  73913. }
  73914. PostProcessManager.prototype._prepareBuffers = function () {
  73915. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  73916. return;
  73917. }
  73918. // VBO
  73919. var vertices = [];
  73920. vertices.push(1, 1);
  73921. vertices.push(-1, 1);
  73922. vertices.push(-1, -1);
  73923. vertices.push(1, -1);
  73924. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73925. this._buildIndexBuffer();
  73926. };
  73927. PostProcessManager.prototype._buildIndexBuffer = function () {
  73928. // Indices
  73929. var indices = [];
  73930. indices.push(0);
  73931. indices.push(1);
  73932. indices.push(2);
  73933. indices.push(0);
  73934. indices.push(2);
  73935. indices.push(3);
  73936. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  73937. };
  73938. /**
  73939. * Rebuilds the vertex buffers of the manager.
  73940. * @hidden
  73941. */
  73942. PostProcessManager.prototype._rebuild = function () {
  73943. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73944. if (!vb) {
  73945. return;
  73946. }
  73947. vb._rebuild();
  73948. this._buildIndexBuffer();
  73949. };
  73950. // Methods
  73951. /**
  73952. * Prepares a frame to be run through a post process.
  73953. * @param sourceTexture The input texture to the post procesess. (default: null)
  73954. * @param postProcesses An array of post processes to be run. (default: null)
  73955. * @returns True if the post processes were able to be run.
  73956. * @hidden
  73957. */
  73958. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  73959. if (sourceTexture === void 0) { sourceTexture = null; }
  73960. if (postProcesses === void 0) { postProcesses = null; }
  73961. var camera = this._scene.activeCamera;
  73962. if (!camera) {
  73963. return false;
  73964. }
  73965. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73966. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73967. return false;
  73968. }
  73969. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  73970. return true;
  73971. };
  73972. /**
  73973. * Manually render a set of post processes to a texture.
  73974. * @param postProcesses An array of post processes to be run.
  73975. * @param targetTexture The target texture to render to.
  73976. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  73977. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  73978. * @param lodLevel defines which lod of the texture to render to
  73979. */
  73980. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  73981. if (targetTexture === void 0) { targetTexture = null; }
  73982. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  73983. if (faceIndex === void 0) { faceIndex = 0; }
  73984. if (lodLevel === void 0) { lodLevel = 0; }
  73985. var engine = this._scene.getEngine();
  73986. for (var index = 0; index < postProcesses.length; index++) {
  73987. if (index < postProcesses.length - 1) {
  73988. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  73989. }
  73990. else {
  73991. if (targetTexture) {
  73992. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  73993. }
  73994. else {
  73995. engine.restoreDefaultFramebuffer();
  73996. }
  73997. }
  73998. var pp = postProcesses[index];
  73999. var effect = pp.apply();
  74000. if (effect) {
  74001. pp.onBeforeRenderObservable.notifyObservers(effect);
  74002. // VBOs
  74003. this._prepareBuffers();
  74004. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  74005. // Draw order
  74006. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74007. pp.onAfterRenderObservable.notifyObservers(effect);
  74008. }
  74009. }
  74010. // Restore depth buffer
  74011. engine.setDepthBuffer(true);
  74012. engine.setDepthWrite(true);
  74013. };
  74014. /**
  74015. * Finalize the result of the output of the postprocesses.
  74016. * @param doNotPresent If true the result will not be displayed to the screen.
  74017. * @param targetTexture The target texture to render to.
  74018. * @param faceIndex The index of the face to bind the target texture to.
  74019. * @param postProcesses The array of post processes to render.
  74020. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  74021. * @hidden
  74022. */
  74023. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  74024. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  74025. var camera = this._scene.activeCamera;
  74026. if (!camera) {
  74027. return;
  74028. }
  74029. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  74030. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  74031. return;
  74032. }
  74033. var engine = this._scene.getEngine();
  74034. for (var index = 0, len = postProcesses.length; index < len; index++) {
  74035. var pp = postProcesses[index];
  74036. if (index < len - 1) {
  74037. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  74038. }
  74039. else {
  74040. if (targetTexture) {
  74041. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  74042. pp._outputTexture = targetTexture;
  74043. }
  74044. else {
  74045. engine.restoreDefaultFramebuffer();
  74046. pp._outputTexture = null;
  74047. }
  74048. }
  74049. if (doNotPresent) {
  74050. break;
  74051. }
  74052. var effect = pp.apply();
  74053. if (effect) {
  74054. pp.onBeforeRenderObservable.notifyObservers(effect);
  74055. // VBOs
  74056. this._prepareBuffers();
  74057. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  74058. // Draw order
  74059. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74060. pp.onAfterRenderObservable.notifyObservers(effect);
  74061. }
  74062. }
  74063. // Restore states
  74064. engine.setDepthBuffer(true);
  74065. engine.setDepthWrite(true);
  74066. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74067. };
  74068. /**
  74069. * Disposes of the post process manager.
  74070. */
  74071. PostProcessManager.prototype.dispose = function () {
  74072. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74073. if (buffer) {
  74074. buffer.dispose();
  74075. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74076. }
  74077. if (this._indexBuffer) {
  74078. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74079. this._indexBuffer = null;
  74080. }
  74081. };
  74082. return PostProcessManager;
  74083. }());
  74084. BABYLON.PostProcessManager = PostProcessManager;
  74085. })(BABYLON || (BABYLON = {}));
  74086. //# sourceMappingURL=babylon.postProcessManager.js.map
  74087. var BABYLON;
  74088. (function (BABYLON) {
  74089. /**
  74090. * PostProcess can be used to apply a shader to a texture after it has been rendered
  74091. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  74092. */
  74093. var PostProcess = /** @class */ (function () {
  74094. /**
  74095. * Creates a new instance PostProcess
  74096. * @param name The name of the PostProcess.
  74097. * @param fragmentUrl The url of the fragment shader to be used.
  74098. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  74099. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  74100. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74101. * @param camera The camera to apply the render pass to.
  74102. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74103. * @param engine The engine which the post process will be applied. (default: current engine)
  74104. * @param reusable If the post process can be reused on the same frame. (default: false)
  74105. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  74106. * @param textureType Type of textures used when performing the post process. (default: 0)
  74107. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  74108. * @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
  74109. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  74110. */
  74111. function PostProcess(
  74112. /** Name of the PostProcess. */
  74113. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  74114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  74115. if (defines === void 0) { defines = null; }
  74116. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74117. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  74118. if (blockCompilation === void 0) { blockCompilation = false; }
  74119. this.name = name;
  74120. /**
  74121. * Width of the texture to apply the post process on
  74122. */
  74123. this.width = -1;
  74124. /**
  74125. * Height of the texture to apply the post process on
  74126. */
  74127. this.height = -1;
  74128. /**
  74129. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  74130. * @hidden
  74131. */
  74132. this._outputTexture = null;
  74133. /**
  74134. * If the buffer needs to be cleared before applying the post process. (default: true)
  74135. * Should be set to false if shader will overwrite all previous pixels.
  74136. */
  74137. this.autoClear = true;
  74138. /**
  74139. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  74140. */
  74141. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  74142. /**
  74143. * Animations to be used for the post processing
  74144. */
  74145. this.animations = new Array();
  74146. /**
  74147. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  74148. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  74149. */
  74150. this.enablePixelPerfectMode = false;
  74151. /**
  74152. * Force the postprocess to be applied without taking in account viewport
  74153. */
  74154. this.forceFullscreenViewport = true;
  74155. /**
  74156. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  74157. *
  74158. * | Value | Type | Description |
  74159. * | ----- | ----------------------------------- | ----------- |
  74160. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  74161. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  74162. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  74163. *
  74164. */
  74165. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  74166. /**
  74167. * Force textures to be a power of two (default: false)
  74168. */
  74169. this.alwaysForcePOT = false;
  74170. this._samples = 1;
  74171. /**
  74172. * Modify the scale of the post process to be the same as the viewport (default: false)
  74173. */
  74174. this.adaptScaleToCurrentViewport = false;
  74175. this._reusable = false;
  74176. /**
  74177. * Smart array of input and output textures for the post process.
  74178. * @hidden
  74179. */
  74180. this._textures = new BABYLON.SmartArray(2);
  74181. /**
  74182. * The index in _textures that corresponds to the output texture.
  74183. * @hidden
  74184. */
  74185. this._currentRenderTextureInd = 0;
  74186. this._scaleRatio = new BABYLON.Vector2(1, 1);
  74187. this._texelSize = BABYLON.Vector2.Zero();
  74188. // Events
  74189. /**
  74190. * An event triggered when the postprocess is activated.
  74191. */
  74192. this.onActivateObservable = new BABYLON.Observable();
  74193. /**
  74194. * An event triggered when the postprocess changes its size.
  74195. */
  74196. this.onSizeChangedObservable = new BABYLON.Observable();
  74197. /**
  74198. * An event triggered when the postprocess applies its effect.
  74199. */
  74200. this.onApplyObservable = new BABYLON.Observable();
  74201. /**
  74202. * An event triggered before rendering the postprocess
  74203. */
  74204. this.onBeforeRenderObservable = new BABYLON.Observable();
  74205. /**
  74206. * An event triggered after rendering the postprocess
  74207. */
  74208. this.onAfterRenderObservable = new BABYLON.Observable();
  74209. if (camera != null) {
  74210. this._camera = camera;
  74211. this._scene = camera.getScene();
  74212. camera.attachPostProcess(this);
  74213. this._engine = this._scene.getEngine();
  74214. this._scene.postProcesses.push(this);
  74215. }
  74216. else if (engine) {
  74217. this._engine = engine;
  74218. this._engine.postProcesses.push(this);
  74219. }
  74220. this._options = options;
  74221. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  74222. this._reusable = reusable || false;
  74223. this._textureType = textureType;
  74224. this._samplers = samplers || [];
  74225. this._samplers.push("textureSampler");
  74226. this._fragmentUrl = fragmentUrl;
  74227. this._vertexUrl = vertexUrl;
  74228. this._parameters = parameters || [];
  74229. this._parameters.push("scale");
  74230. this._indexParameters = indexParameters;
  74231. if (!blockCompilation) {
  74232. this.updateEffect(defines);
  74233. }
  74234. }
  74235. Object.defineProperty(PostProcess.prototype, "samples", {
  74236. /**
  74237. * Number of sample textures (default: 1)
  74238. */
  74239. get: function () {
  74240. return this._samples;
  74241. },
  74242. set: function (n) {
  74243. var _this = this;
  74244. this._samples = n;
  74245. this._textures.forEach(function (texture) {
  74246. if (texture.samples !== _this._samples) {
  74247. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  74248. }
  74249. });
  74250. },
  74251. enumerable: true,
  74252. configurable: true
  74253. });
  74254. Object.defineProperty(PostProcess.prototype, "onActivate", {
  74255. /**
  74256. * A function that is added to the onActivateObservable
  74257. */
  74258. set: function (callback) {
  74259. if (this._onActivateObserver) {
  74260. this.onActivateObservable.remove(this._onActivateObserver);
  74261. }
  74262. if (callback) {
  74263. this._onActivateObserver = this.onActivateObservable.add(callback);
  74264. }
  74265. },
  74266. enumerable: true,
  74267. configurable: true
  74268. });
  74269. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  74270. /**
  74271. * A function that is added to the onSizeChangedObservable
  74272. */
  74273. set: function (callback) {
  74274. if (this._onSizeChangedObserver) {
  74275. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  74276. }
  74277. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  74278. },
  74279. enumerable: true,
  74280. configurable: true
  74281. });
  74282. Object.defineProperty(PostProcess.prototype, "onApply", {
  74283. /**
  74284. * A function that is added to the onApplyObservable
  74285. */
  74286. set: function (callback) {
  74287. if (this._onApplyObserver) {
  74288. this.onApplyObservable.remove(this._onApplyObserver);
  74289. }
  74290. this._onApplyObserver = this.onApplyObservable.add(callback);
  74291. },
  74292. enumerable: true,
  74293. configurable: true
  74294. });
  74295. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  74296. /**
  74297. * A function that is added to the onBeforeRenderObservable
  74298. */
  74299. set: function (callback) {
  74300. if (this._onBeforeRenderObserver) {
  74301. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74302. }
  74303. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74304. },
  74305. enumerable: true,
  74306. configurable: true
  74307. });
  74308. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  74309. /**
  74310. * A function that is added to the onAfterRenderObservable
  74311. */
  74312. set: function (callback) {
  74313. if (this._onAfterRenderObserver) {
  74314. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74315. }
  74316. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74317. },
  74318. enumerable: true,
  74319. configurable: true
  74320. });
  74321. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  74322. /**
  74323. * 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
  74324. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  74325. */
  74326. get: function () {
  74327. return this._textures.data[this._currentRenderTextureInd];
  74328. },
  74329. set: function (value) {
  74330. this._forcedOutputTexture = value;
  74331. },
  74332. enumerable: true,
  74333. configurable: true
  74334. });
  74335. /**
  74336. * Gets the camera which post process is applied to.
  74337. * @returns The camera the post process is applied to.
  74338. */
  74339. PostProcess.prototype.getCamera = function () {
  74340. return this._camera;
  74341. };
  74342. Object.defineProperty(PostProcess.prototype, "texelSize", {
  74343. /**
  74344. * Gets the texel size of the postprocess.
  74345. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  74346. */
  74347. get: function () {
  74348. if (this._shareOutputWithPostProcess) {
  74349. return this._shareOutputWithPostProcess.texelSize;
  74350. }
  74351. if (this._forcedOutputTexture) {
  74352. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  74353. }
  74354. return this._texelSize;
  74355. },
  74356. enumerable: true,
  74357. configurable: true
  74358. });
  74359. /**
  74360. * Gets the engine which this post process belongs to.
  74361. * @returns The engine the post process was enabled with.
  74362. */
  74363. PostProcess.prototype.getEngine = function () {
  74364. return this._engine;
  74365. };
  74366. /**
  74367. * The effect that is created when initializing the post process.
  74368. * @returns The created effect corrisponding the the postprocess.
  74369. */
  74370. PostProcess.prototype.getEffect = function () {
  74371. return this._effect;
  74372. };
  74373. /**
  74374. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  74375. * @param postProcess The post process to share the output with.
  74376. * @returns This post process.
  74377. */
  74378. PostProcess.prototype.shareOutputWith = function (postProcess) {
  74379. this._disposeTextures();
  74380. this._shareOutputWithPostProcess = postProcess;
  74381. return this;
  74382. };
  74383. /**
  74384. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  74385. * This should be called if the post process that shares output with this post process is disabled/disposed.
  74386. */
  74387. PostProcess.prototype.useOwnOutput = function () {
  74388. if (this._textures.length == 0) {
  74389. this._textures = new BABYLON.SmartArray(2);
  74390. }
  74391. this._shareOutputWithPostProcess = null;
  74392. };
  74393. /**
  74394. * Updates the effect with the current post process compile time values and recompiles the shader.
  74395. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74396. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74397. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74398. * @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
  74399. * @param onCompiled Called when the shader has been compiled.
  74400. * @param onError Called if there is an error when compiling a shader.
  74401. */
  74402. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74403. if (defines === void 0) { defines = null; }
  74404. if (uniforms === void 0) { uniforms = null; }
  74405. if (samplers === void 0) { samplers = null; }
  74406. 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);
  74407. };
  74408. /**
  74409. * The post process is reusable if it can be used multiple times within one frame.
  74410. * @returns If the post process is reusable
  74411. */
  74412. PostProcess.prototype.isReusable = function () {
  74413. return this._reusable;
  74414. };
  74415. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  74416. PostProcess.prototype.markTextureDirty = function () {
  74417. this.width = -1;
  74418. };
  74419. /**
  74420. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  74421. * 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.
  74422. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  74423. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  74424. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  74425. * @returns The target texture that was bound to be written to.
  74426. */
  74427. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  74428. var _this = this;
  74429. if (sourceTexture === void 0) { sourceTexture = null; }
  74430. camera = camera || this._camera;
  74431. var scene = camera.getScene();
  74432. var engine = scene.getEngine();
  74433. var maxSize = engine.getCaps().maxTextureSize;
  74434. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  74435. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  74436. // 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
  74437. var webVRCamera = camera.parent;
  74438. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  74439. requiredWidth /= 2;
  74440. }
  74441. var desiredWidth = (this._options.width || requiredWidth);
  74442. var desiredHeight = this._options.height || requiredHeight;
  74443. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  74444. if (this.adaptScaleToCurrentViewport) {
  74445. var currentViewport = engine.currentViewport;
  74446. if (currentViewport) {
  74447. desiredWidth *= currentViewport.width;
  74448. desiredHeight *= currentViewport.height;
  74449. }
  74450. }
  74451. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  74452. if (!this._options.width) {
  74453. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  74454. }
  74455. if (!this._options.height) {
  74456. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  74457. }
  74458. }
  74459. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  74460. if (this._textures.length > 0) {
  74461. for (var i = 0; i < this._textures.length; i++) {
  74462. this._engine._releaseTexture(this._textures.data[i]);
  74463. }
  74464. this._textures.reset();
  74465. }
  74466. this.width = desiredWidth;
  74467. this.height = desiredHeight;
  74468. var textureSize = { width: this.width, height: this.height };
  74469. var textureOptions = {
  74470. generateMipMaps: false,
  74471. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  74472. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  74473. samplingMode: this.renderTargetSamplingMode,
  74474. type: this._textureType
  74475. };
  74476. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74477. if (this._reusable) {
  74478. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74479. }
  74480. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  74481. this.onSizeChangedObservable.notifyObservers(this);
  74482. }
  74483. this._textures.forEach(function (texture) {
  74484. if (texture.samples !== _this.samples) {
  74485. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  74486. }
  74487. });
  74488. }
  74489. var target;
  74490. if (this._shareOutputWithPostProcess) {
  74491. target = this._shareOutputWithPostProcess.inputTexture;
  74492. }
  74493. else if (this._forcedOutputTexture) {
  74494. target = this._forcedOutputTexture;
  74495. this.width = this._forcedOutputTexture.width;
  74496. this.height = this._forcedOutputTexture.height;
  74497. }
  74498. else {
  74499. target = this.inputTexture;
  74500. }
  74501. // Bind the input of this post process to be used as the output of the previous post process.
  74502. if (this.enablePixelPerfectMode) {
  74503. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  74504. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  74505. }
  74506. else {
  74507. this._scaleRatio.copyFromFloats(1, 1);
  74508. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  74509. }
  74510. this.onActivateObservable.notifyObservers(camera);
  74511. // Clear
  74512. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  74513. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  74514. }
  74515. if (this._reusable) {
  74516. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  74517. }
  74518. return target;
  74519. };
  74520. Object.defineProperty(PostProcess.prototype, "isSupported", {
  74521. /**
  74522. * If the post process is supported.
  74523. */
  74524. get: function () {
  74525. return this._effect.isSupported;
  74526. },
  74527. enumerable: true,
  74528. configurable: true
  74529. });
  74530. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  74531. /**
  74532. * The aspect ratio of the output texture.
  74533. */
  74534. get: function () {
  74535. if (this._shareOutputWithPostProcess) {
  74536. return this._shareOutputWithPostProcess.aspectRatio;
  74537. }
  74538. if (this._forcedOutputTexture) {
  74539. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  74540. }
  74541. return this.width / this.height;
  74542. },
  74543. enumerable: true,
  74544. configurable: true
  74545. });
  74546. /**
  74547. * Get a value indicating if the post-process is ready to be used
  74548. * @returns true if the post-process is ready (shader is compiled)
  74549. */
  74550. PostProcess.prototype.isReady = function () {
  74551. return this._effect && this._effect.isReady();
  74552. };
  74553. /**
  74554. * Binds all textures and uniforms to the shader, this will be run on every pass.
  74555. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  74556. */
  74557. PostProcess.prototype.apply = function () {
  74558. // Check
  74559. if (!this._effect || !this._effect.isReady()) {
  74560. return null;
  74561. }
  74562. // States
  74563. this._engine.enableEffect(this._effect);
  74564. this._engine.setState(false);
  74565. this._engine.setDepthBuffer(false);
  74566. this._engine.setDepthWrite(false);
  74567. // Alpha
  74568. this._engine.setAlphaMode(this.alphaMode);
  74569. if (this.alphaConstants) {
  74570. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  74571. }
  74572. // Bind the output texture of the preivous post process as the input to this post process.
  74573. var source;
  74574. if (this._shareOutputWithPostProcess) {
  74575. source = this._shareOutputWithPostProcess.inputTexture;
  74576. }
  74577. else if (this._forcedOutputTexture) {
  74578. source = this._forcedOutputTexture;
  74579. }
  74580. else {
  74581. source = this.inputTexture;
  74582. }
  74583. this._effect._bindTexture("textureSampler", source);
  74584. // Parameters
  74585. this._effect.setVector2("scale", this._scaleRatio);
  74586. this.onApplyObservable.notifyObservers(this._effect);
  74587. return this._effect;
  74588. };
  74589. PostProcess.prototype._disposeTextures = function () {
  74590. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  74591. return;
  74592. }
  74593. if (this._textures.length > 0) {
  74594. for (var i = 0; i < this._textures.length; i++) {
  74595. this._engine._releaseTexture(this._textures.data[i]);
  74596. }
  74597. }
  74598. this._textures.dispose();
  74599. };
  74600. /**
  74601. * Disposes the post process.
  74602. * @param camera The camera to dispose the post process on.
  74603. */
  74604. PostProcess.prototype.dispose = function (camera) {
  74605. camera = camera || this._camera;
  74606. this._disposeTextures();
  74607. if (this._scene) {
  74608. var index_1 = this._scene.postProcesses.indexOf(this);
  74609. if (index_1 !== -1) {
  74610. this._scene.postProcesses.splice(index_1, 1);
  74611. }
  74612. }
  74613. else {
  74614. var index_2 = this._engine.postProcesses.indexOf(this);
  74615. if (index_2 !== -1) {
  74616. this._engine.postProcesses.splice(index_2, 1);
  74617. }
  74618. }
  74619. if (!camera) {
  74620. return;
  74621. }
  74622. camera.detachPostProcess(this);
  74623. var index = camera._postProcesses.indexOf(this);
  74624. if (index === 0 && camera._postProcesses.length > 0) {
  74625. var firstPostProcess = this._camera._getFirstPostProcess();
  74626. if (firstPostProcess) {
  74627. firstPostProcess.markTextureDirty();
  74628. }
  74629. }
  74630. this.onActivateObservable.clear();
  74631. this.onAfterRenderObservable.clear();
  74632. this.onApplyObservable.clear();
  74633. this.onBeforeRenderObservable.clear();
  74634. this.onSizeChangedObservable.clear();
  74635. };
  74636. return PostProcess;
  74637. }());
  74638. BABYLON.PostProcess = PostProcess;
  74639. })(BABYLON || (BABYLON = {}));
  74640. //# sourceMappingURL=babylon.postProcess.js.map
  74641. var BABYLON;
  74642. (function (BABYLON) {
  74643. /**
  74644. * PassPostProcess which produces an output the same as it's input
  74645. */
  74646. var PassPostProcess = /** @class */ (function (_super) {
  74647. __extends(PassPostProcess, _super);
  74648. /**
  74649. * Creates the PassPostProcess
  74650. * @param name The name of the effect.
  74651. * @param options The required width/height ratio to downsize to before computing the render pass.
  74652. * @param camera The camera to apply the render pass to.
  74653. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74654. * @param engine The engine which the post process will be applied. (default: current engine)
  74655. * @param reusable If the post process can be reused on the same frame. (default: false)
  74656. * @param textureType The type of texture to be used when performing the post processing.
  74657. * @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)
  74658. */
  74659. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74660. if (camera === void 0) { camera = null; }
  74661. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74662. if (blockCompilation === void 0) { blockCompilation = false; }
  74663. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  74664. }
  74665. return PassPostProcess;
  74666. }(BABYLON.PostProcess));
  74667. BABYLON.PassPostProcess = PassPostProcess;
  74668. })(BABYLON || (BABYLON = {}));
  74669. //# sourceMappingURL=babylon.passPostProcess.js.map
  74670. var __assign = (this && this.__assign) || function () {
  74671. __assign = Object.assign || function(t) {
  74672. for (var s, i = 1, n = arguments.length; i < n; i++) {
  74673. s = arguments[i];
  74674. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  74675. t[p] = s[p];
  74676. }
  74677. return t;
  74678. };
  74679. return __assign.apply(this, arguments);
  74680. };
  74681. var BABYLON;
  74682. (function (BABYLON) {
  74683. /**
  74684. * Default implementation IShadowGenerator.
  74685. * This is the main object responsible of generating shadows in the framework.
  74686. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  74687. */
  74688. var ShadowGenerator = /** @class */ (function () {
  74689. /**
  74690. * Creates a ShadowGenerator object.
  74691. * A ShadowGenerator is the required tool to use the shadows.
  74692. * Each light casting shadows needs to use its own ShadowGenerator.
  74693. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  74694. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  74695. * @param light The light object generating the shadows.
  74696. * @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.
  74697. */
  74698. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  74699. this._bias = 0.00005;
  74700. this._normalBias = 0;
  74701. this._blurBoxOffset = 1;
  74702. this._blurScale = 2;
  74703. this._blurKernel = 1;
  74704. this._useKernelBlur = false;
  74705. this._filter = ShadowGenerator.FILTER_NONE;
  74706. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  74707. this._contactHardeningLightSizeUVRatio = 0.1;
  74708. this._darkness = 0;
  74709. this._transparencyShadow = false;
  74710. /**
  74711. * Controls the extent to which the shadows fade out at the edge of the frustum
  74712. * Used only by directionals and spots
  74713. */
  74714. this.frustumEdgeFalloff = 0;
  74715. /**
  74716. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  74717. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  74718. * It might on the other hand introduce peter panning.
  74719. */
  74720. this.forceBackFacesOnly = false;
  74721. this._lightDirection = BABYLON.Vector3.Zero();
  74722. this._viewMatrix = BABYLON.Matrix.Zero();
  74723. this._projectionMatrix = BABYLON.Matrix.Zero();
  74724. this._transformMatrix = BABYLON.Matrix.Zero();
  74725. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74726. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74727. this._currentFaceIndex = 0;
  74728. this._currentFaceIndexCache = 0;
  74729. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  74730. this._mapSize = mapSize;
  74731. this._light = light;
  74732. this._scene = light.getScene();
  74733. light._shadowGenerator = this;
  74734. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  74735. if (!component) {
  74736. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  74737. this._scene._addComponent(component);
  74738. }
  74739. // Texture type fallback from float to int if not supported.
  74740. var caps = this._scene.getEngine().getCaps();
  74741. if (!useFullFloatFirst) {
  74742. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74743. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74744. }
  74745. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74746. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74747. }
  74748. else {
  74749. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74750. }
  74751. }
  74752. else {
  74753. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74754. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74755. }
  74756. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74757. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74758. }
  74759. else {
  74760. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74761. }
  74762. }
  74763. this._initializeGenerator();
  74764. this._applyFilterValues();
  74765. }
  74766. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  74767. /**
  74768. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  74769. */
  74770. get: function () {
  74771. return this._bias;
  74772. },
  74773. /**
  74774. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  74775. */
  74776. set: function (bias) {
  74777. this._bias = bias;
  74778. },
  74779. enumerable: true,
  74780. configurable: true
  74781. });
  74782. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  74783. /**
  74784. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74785. */
  74786. get: function () {
  74787. return this._normalBias;
  74788. },
  74789. /**
  74790. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74791. */
  74792. set: function (normalBias) {
  74793. this._normalBias = normalBias;
  74794. },
  74795. enumerable: true,
  74796. configurable: true
  74797. });
  74798. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  74799. /**
  74800. * Gets the blur box offset: offset applied during the blur pass.
  74801. * Only usefull if useKernelBlur = false
  74802. */
  74803. get: function () {
  74804. return this._blurBoxOffset;
  74805. },
  74806. /**
  74807. * Sets the blur box offset: offset applied during the blur pass.
  74808. * Only usefull if useKernelBlur = false
  74809. */
  74810. set: function (value) {
  74811. if (this._blurBoxOffset === value) {
  74812. return;
  74813. }
  74814. this._blurBoxOffset = value;
  74815. this._disposeBlurPostProcesses();
  74816. },
  74817. enumerable: true,
  74818. configurable: true
  74819. });
  74820. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  74821. /**
  74822. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  74823. * 2 means half of the size.
  74824. */
  74825. get: function () {
  74826. return this._blurScale;
  74827. },
  74828. /**
  74829. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  74830. * 2 means half of the size.
  74831. */
  74832. set: function (value) {
  74833. if (this._blurScale === value) {
  74834. return;
  74835. }
  74836. this._blurScale = value;
  74837. this._disposeBlurPostProcesses();
  74838. },
  74839. enumerable: true,
  74840. configurable: true
  74841. });
  74842. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  74843. /**
  74844. * Gets the blur kernel: kernel size of the blur pass.
  74845. * Only usefull if useKernelBlur = true
  74846. */
  74847. get: function () {
  74848. return this._blurKernel;
  74849. },
  74850. /**
  74851. * Sets the blur kernel: kernel size of the blur pass.
  74852. * Only usefull if useKernelBlur = true
  74853. */
  74854. set: function (value) {
  74855. if (this._blurKernel === value) {
  74856. return;
  74857. }
  74858. this._blurKernel = value;
  74859. this._disposeBlurPostProcesses();
  74860. },
  74861. enumerable: true,
  74862. configurable: true
  74863. });
  74864. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  74865. /**
  74866. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  74867. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74868. */
  74869. get: function () {
  74870. return this._useKernelBlur;
  74871. },
  74872. /**
  74873. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  74874. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74875. */
  74876. set: function (value) {
  74877. if (this._useKernelBlur === value) {
  74878. return;
  74879. }
  74880. this._useKernelBlur = value;
  74881. this._disposeBlurPostProcesses();
  74882. },
  74883. enumerable: true,
  74884. configurable: true
  74885. });
  74886. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  74887. /**
  74888. * Gets the depth scale used in ESM mode.
  74889. */
  74890. get: function () {
  74891. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  74892. },
  74893. /**
  74894. * Sets the depth scale used in ESM mode.
  74895. * This can override the scale stored on the light.
  74896. */
  74897. set: function (value) {
  74898. this._depthScale = value;
  74899. },
  74900. enumerable: true,
  74901. configurable: true
  74902. });
  74903. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  74904. /**
  74905. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  74906. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74907. */
  74908. get: function () {
  74909. return this._filter;
  74910. },
  74911. /**
  74912. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  74913. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74914. */
  74915. set: function (value) {
  74916. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  74917. if (this._light.needCube()) {
  74918. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74919. this.useExponentialShadowMap = true;
  74920. return;
  74921. }
  74922. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74923. this.useCloseExponentialShadowMap = true;
  74924. return;
  74925. }
  74926. // PCF on cubemap would also be expensive
  74927. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74928. this.usePoissonSampling = true;
  74929. return;
  74930. }
  74931. }
  74932. // Weblg1 fallback for PCF.
  74933. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74934. if (this._scene.getEngine().webGLVersion === 1) {
  74935. this.usePoissonSampling = true;
  74936. return;
  74937. }
  74938. }
  74939. if (this._filter === value) {
  74940. return;
  74941. }
  74942. this._filter = value;
  74943. this._disposeBlurPostProcesses();
  74944. this._applyFilterValues();
  74945. this._light._markMeshesAsLightDirty();
  74946. },
  74947. enumerable: true,
  74948. configurable: true
  74949. });
  74950. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  74951. /**
  74952. * Gets if the current filter is set to Poisson Sampling.
  74953. */
  74954. get: function () {
  74955. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  74956. },
  74957. /**
  74958. * Sets the current filter to Poisson Sampling.
  74959. */
  74960. set: function (value) {
  74961. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  74962. return;
  74963. }
  74964. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  74965. },
  74966. enumerable: true,
  74967. configurable: true
  74968. });
  74969. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  74970. /**
  74971. * Gets if the current filter is set to VSM.
  74972. * DEPRECATED. Should use useExponentialShadowMap instead.
  74973. */
  74974. get: function () {
  74975. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  74976. return this.useExponentialShadowMap;
  74977. },
  74978. /**
  74979. * Sets the current filter is to VSM.
  74980. * DEPRECATED. Should use useExponentialShadowMap instead.
  74981. */
  74982. set: function (value) {
  74983. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  74984. this.useExponentialShadowMap = value;
  74985. },
  74986. enumerable: true,
  74987. configurable: true
  74988. });
  74989. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  74990. /**
  74991. * Gets if the current filter is set to blurred VSM.
  74992. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  74993. */
  74994. get: function () {
  74995. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  74996. return this.useBlurExponentialShadowMap;
  74997. },
  74998. /**
  74999. * Sets the current filter is to blurred VSM.
  75000. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  75001. */
  75002. set: function (value) {
  75003. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  75004. this.useBlurExponentialShadowMap = value;
  75005. },
  75006. enumerable: true,
  75007. configurable: true
  75008. });
  75009. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  75010. /**
  75011. * Gets if the current filter is set to ESM.
  75012. */
  75013. get: function () {
  75014. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  75015. },
  75016. /**
  75017. * Sets the current filter is to ESM.
  75018. */
  75019. set: function (value) {
  75020. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  75021. return;
  75022. }
  75023. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75024. },
  75025. enumerable: true,
  75026. configurable: true
  75027. });
  75028. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  75029. /**
  75030. * Gets if the current filter is set to filtered ESM.
  75031. */
  75032. get: function () {
  75033. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  75034. },
  75035. /**
  75036. * Gets if the current filter is set to filtered ESM.
  75037. */
  75038. set: function (value) {
  75039. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  75040. return;
  75041. }
  75042. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75043. },
  75044. enumerable: true,
  75045. configurable: true
  75046. });
  75047. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  75048. /**
  75049. * Gets if the current filter is set to "close ESM" (using the inverse of the
  75050. * exponential to prevent steep falloff artifacts).
  75051. */
  75052. get: function () {
  75053. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  75054. },
  75055. /**
  75056. * Sets the current filter to "close ESM" (using the inverse of the
  75057. * exponential to prevent steep falloff artifacts).
  75058. */
  75059. set: function (value) {
  75060. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  75061. return;
  75062. }
  75063. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75064. },
  75065. enumerable: true,
  75066. configurable: true
  75067. });
  75068. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  75069. /**
  75070. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  75071. * exponential to prevent steep falloff artifacts).
  75072. */
  75073. get: function () {
  75074. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  75075. },
  75076. /**
  75077. * Sets the current filter to filtered "close ESM" (using the inverse of the
  75078. * exponential to prevent steep falloff artifacts).
  75079. */
  75080. set: function (value) {
  75081. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  75082. return;
  75083. }
  75084. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75085. },
  75086. enumerable: true,
  75087. configurable: true
  75088. });
  75089. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  75090. /**
  75091. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  75092. */
  75093. get: function () {
  75094. return this.filter === ShadowGenerator.FILTER_PCF;
  75095. },
  75096. /**
  75097. * Sets the current filter to "PCF" (percentage closer filtering).
  75098. */
  75099. set: function (value) {
  75100. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  75101. return;
  75102. }
  75103. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  75104. },
  75105. enumerable: true,
  75106. configurable: true
  75107. });
  75108. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  75109. /**
  75110. * Gets the PCF or PCSS Quality.
  75111. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  75112. */
  75113. get: function () {
  75114. return this._filteringQuality;
  75115. },
  75116. /**
  75117. * Sets the PCF or PCSS Quality.
  75118. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  75119. */
  75120. set: function (filteringQuality) {
  75121. this._filteringQuality = filteringQuality;
  75122. },
  75123. enumerable: true,
  75124. configurable: true
  75125. });
  75126. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  75127. /**
  75128. * Gets if the current filter is set to "PCSS" (contact hardening).
  75129. */
  75130. get: function () {
  75131. return this.filter === ShadowGenerator.FILTER_PCSS;
  75132. },
  75133. /**
  75134. * Sets the current filter to "PCSS" (contact hardening).
  75135. */
  75136. set: function (value) {
  75137. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  75138. return;
  75139. }
  75140. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  75141. },
  75142. enumerable: true,
  75143. configurable: true
  75144. });
  75145. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  75146. /**
  75147. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  75148. * Using a ratio helps keeping shape stability independently of the map size.
  75149. *
  75150. * It does not account for the light projection as it was having too much
  75151. * instability during the light setup or during light position changes.
  75152. *
  75153. * Only valid if useContactHardeningShadow is true.
  75154. */
  75155. get: function () {
  75156. return this._contactHardeningLightSizeUVRatio;
  75157. },
  75158. /**
  75159. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  75160. * Using a ratio helps keeping shape stability independently of the map size.
  75161. *
  75162. * It does not account for the light projection as it was having too much
  75163. * instability during the light setup or during light position changes.
  75164. *
  75165. * Only valid if useContactHardeningShadow is true.
  75166. */
  75167. set: function (contactHardeningLightSizeUVRatio) {
  75168. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  75169. },
  75170. enumerable: true,
  75171. configurable: true
  75172. });
  75173. /**
  75174. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  75175. * 0 means strongest and 1 would means no shadow.
  75176. * @returns the darkness.
  75177. */
  75178. ShadowGenerator.prototype.getDarkness = function () {
  75179. return this._darkness;
  75180. };
  75181. /**
  75182. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  75183. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  75184. * @returns the shadow generator allowing fluent coding.
  75185. */
  75186. ShadowGenerator.prototype.setDarkness = function (darkness) {
  75187. if (darkness >= 1.0) {
  75188. this._darkness = 1.0;
  75189. }
  75190. else if (darkness <= 0.0) {
  75191. this._darkness = 0.0;
  75192. }
  75193. else {
  75194. this._darkness = darkness;
  75195. }
  75196. return this;
  75197. };
  75198. /**
  75199. * Sets the ability to have transparent shadow (boolean).
  75200. * @param transparent True if transparent else False
  75201. * @returns the shadow generator allowing fluent coding
  75202. */
  75203. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  75204. this._transparencyShadow = transparent;
  75205. return this;
  75206. };
  75207. /**
  75208. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  75209. * @returns The render target texture if present otherwise, null
  75210. */
  75211. ShadowGenerator.prototype.getShadowMap = function () {
  75212. return this._shadowMap;
  75213. };
  75214. /**
  75215. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  75216. * @returns The render target texture if the shadow map is present otherwise, null
  75217. */
  75218. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  75219. if (this._shadowMap2) {
  75220. return this._shadowMap2;
  75221. }
  75222. return this._shadowMap;
  75223. };
  75224. /**
  75225. * Helper function to add a mesh and its descendants to the list of shadow casters.
  75226. * @param mesh Mesh to add
  75227. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  75228. * @returns the Shadow Generator itself
  75229. */
  75230. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  75231. if (includeDescendants === void 0) { includeDescendants = true; }
  75232. var _a;
  75233. if (!this._shadowMap) {
  75234. return this;
  75235. }
  75236. if (!this._shadowMap.renderList) {
  75237. this._shadowMap.renderList = [];
  75238. }
  75239. this._shadowMap.renderList.push(mesh);
  75240. if (includeDescendants) {
  75241. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  75242. }
  75243. return this;
  75244. };
  75245. /**
  75246. * Helper function to remove a mesh and its descendants from the list of shadow casters
  75247. * @param mesh Mesh to remove
  75248. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  75249. * @returns the Shadow Generator itself
  75250. */
  75251. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  75252. if (includeDescendants === void 0) { includeDescendants = true; }
  75253. if (!this._shadowMap || !this._shadowMap.renderList) {
  75254. return this;
  75255. }
  75256. var index = this._shadowMap.renderList.indexOf(mesh);
  75257. if (index !== -1) {
  75258. this._shadowMap.renderList.splice(index, 1);
  75259. }
  75260. if (includeDescendants) {
  75261. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  75262. var child = _a[_i];
  75263. this.removeShadowCaster(child);
  75264. }
  75265. }
  75266. return this;
  75267. };
  75268. /**
  75269. * Returns the associated light object.
  75270. * @returns the light generating the shadow
  75271. */
  75272. ShadowGenerator.prototype.getLight = function () {
  75273. return this._light;
  75274. };
  75275. ShadowGenerator.prototype._initializeGenerator = function () {
  75276. this._light._markMeshesAsLightDirty();
  75277. this._initializeShadowMap();
  75278. };
  75279. ShadowGenerator.prototype._initializeShadowMap = function () {
  75280. var _this = this;
  75281. // Render target
  75282. var engine = this._scene.getEngine();
  75283. if (engine.webGLVersion > 1) {
  75284. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  75285. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  75286. }
  75287. else {
  75288. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  75289. }
  75290. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75291. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75292. this._shadowMap.anisotropicFilteringLevel = 1;
  75293. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75294. this._shadowMap.renderParticles = false;
  75295. this._shadowMap.ignoreCameraViewport = true;
  75296. // Record Face Index before render.
  75297. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  75298. _this._currentFaceIndex = faceIndex;
  75299. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75300. engine.setColorWrite(false);
  75301. }
  75302. });
  75303. // Custom render function.
  75304. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  75305. // Blur if required afer render.
  75306. this._shadowMap.onAfterUnbindObservable.add(function () {
  75307. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75308. engine.setColorWrite(true);
  75309. }
  75310. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  75311. return;
  75312. }
  75313. var shadowMap = _this.getShadowMapForRendering();
  75314. if (shadowMap) {
  75315. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  75316. }
  75317. });
  75318. // Clear according to the chosen filter.
  75319. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  75320. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  75321. this._shadowMap.onClearObservable.add(function (engine) {
  75322. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75323. engine.clear(clearOne, false, true, false);
  75324. }
  75325. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  75326. engine.clear(clearZero, true, true, false);
  75327. }
  75328. else {
  75329. engine.clear(clearOne, true, true, false);
  75330. }
  75331. });
  75332. };
  75333. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  75334. var _this = this;
  75335. var engine = this._scene.getEngine();
  75336. var targetSize = this._mapSize / this.blurScale;
  75337. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  75338. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  75339. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75340. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75341. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75342. }
  75343. if (this.useKernelBlur) {
  75344. 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);
  75345. this._kernelBlurXPostprocess.width = targetSize;
  75346. this._kernelBlurXPostprocess.height = targetSize;
  75347. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  75348. effect.setTexture("textureSampler", _this._shadowMap);
  75349. });
  75350. 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);
  75351. this._kernelBlurXPostprocess.autoClear = false;
  75352. this._kernelBlurYPostprocess.autoClear = false;
  75353. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75354. this._kernelBlurXPostprocess.packedFloat = true;
  75355. this._kernelBlurYPostprocess.packedFloat = true;
  75356. }
  75357. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  75358. }
  75359. else {
  75360. 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);
  75361. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  75362. effect.setFloat2("screenSize", targetSize, targetSize);
  75363. effect.setTexture("textureSampler", _this._shadowMap);
  75364. });
  75365. this._boxBlurPostprocess.autoClear = false;
  75366. this._blurPostProcesses = [this._boxBlurPostprocess];
  75367. }
  75368. };
  75369. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75370. var index;
  75371. var engine = this._scene.getEngine();
  75372. if (depthOnlySubMeshes.length) {
  75373. engine.setColorWrite(false);
  75374. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75375. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  75376. }
  75377. engine.setColorWrite(true);
  75378. }
  75379. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75380. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  75381. }
  75382. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75383. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  75384. }
  75385. if (this._transparencyShadow) {
  75386. for (index = 0; index < transparentSubMeshes.length; index++) {
  75387. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  75388. }
  75389. }
  75390. };
  75391. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  75392. var _this = this;
  75393. var mesh = subMesh.getRenderingMesh();
  75394. var scene = this._scene;
  75395. var engine = scene.getEngine();
  75396. var material = subMesh.getMaterial();
  75397. if (!material) {
  75398. return;
  75399. }
  75400. // Culling
  75401. engine.setState(material.backFaceCulling);
  75402. // Managing instances
  75403. var batch = mesh._getInstancesRenderList(subMesh._id);
  75404. if (batch.mustReturn) {
  75405. return;
  75406. }
  75407. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75408. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  75409. engine.enableEffect(this._effect);
  75410. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  75411. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  75412. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  75413. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75414. this._effect.setVector3("lightData", this._cachedDirection);
  75415. }
  75416. else {
  75417. this._effect.setVector3("lightData", this._cachedPosition);
  75418. }
  75419. if (scene.activeCamera) {
  75420. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  75421. }
  75422. // Alpha test
  75423. if (material && material.needAlphaTesting()) {
  75424. var alphaTexture = material.getAlphaTestTexture();
  75425. if (alphaTexture) {
  75426. this._effect.setTexture("diffuseSampler", alphaTexture);
  75427. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  75428. }
  75429. }
  75430. // Bones
  75431. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75432. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  75433. }
  75434. // Morph targets
  75435. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  75436. if (this.forceBackFacesOnly) {
  75437. engine.setState(true, 0, false, true);
  75438. }
  75439. // Draw
  75440. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75441. if (this.forceBackFacesOnly) {
  75442. engine.setState(true, 0, false, false);
  75443. }
  75444. }
  75445. else {
  75446. // Need to reset refresh rate of the shadowMap
  75447. if (this._shadowMap) {
  75448. this._shadowMap.resetRefreshCounter();
  75449. }
  75450. }
  75451. };
  75452. ShadowGenerator.prototype._applyFilterValues = function () {
  75453. if (!this._shadowMap) {
  75454. return;
  75455. }
  75456. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  75457. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  75458. }
  75459. else {
  75460. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75461. }
  75462. };
  75463. /**
  75464. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75465. * @param onCompiled Callback triggered at the and of the effects compilation
  75466. * @param options Sets of optional options forcing the compilation with different modes
  75467. */
  75468. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  75469. var _this = this;
  75470. var localOptions = __assign({ useInstances: false }, options);
  75471. var shadowMap = this.getShadowMap();
  75472. if (!shadowMap) {
  75473. if (onCompiled) {
  75474. onCompiled(this);
  75475. }
  75476. return;
  75477. }
  75478. var renderList = shadowMap.renderList;
  75479. if (!renderList) {
  75480. if (onCompiled) {
  75481. onCompiled(this);
  75482. }
  75483. return;
  75484. }
  75485. var subMeshes = new Array();
  75486. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  75487. var mesh = renderList_1[_i];
  75488. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  75489. }
  75490. if (subMeshes.length === 0) {
  75491. if (onCompiled) {
  75492. onCompiled(this);
  75493. }
  75494. return;
  75495. }
  75496. var currentIndex = 0;
  75497. var checkReady = function () {
  75498. if (!_this._scene || !_this._scene.getEngine()) {
  75499. return;
  75500. }
  75501. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  75502. currentIndex++;
  75503. if (currentIndex >= subMeshes.length) {
  75504. if (onCompiled) {
  75505. onCompiled(_this);
  75506. }
  75507. return;
  75508. }
  75509. }
  75510. setTimeout(checkReady, 16);
  75511. };
  75512. checkReady();
  75513. };
  75514. /**
  75515. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75516. * @param options Sets of optional options forcing the compilation with different modes
  75517. * @returns A promise that resolves when the compilation completes
  75518. */
  75519. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  75520. var _this = this;
  75521. return new Promise(function (resolve) {
  75522. _this.forceCompilation(function () {
  75523. resolve();
  75524. }, options);
  75525. });
  75526. };
  75527. /**
  75528. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  75529. * @param subMesh The submesh we want to render in the shadow map
  75530. * @param useInstances Defines wether will draw in the map using instances
  75531. * @returns true if ready otherwise, false
  75532. */
  75533. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  75534. var defines = [];
  75535. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75536. defines.push("#define FLOAT");
  75537. }
  75538. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75539. defines.push("#define ESM");
  75540. }
  75541. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  75542. defines.push("#define DEPTHTEXTURE");
  75543. }
  75544. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75545. var mesh = subMesh.getMesh();
  75546. var material = subMesh.getMaterial();
  75547. // Normal bias.
  75548. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75549. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75550. defines.push("#define NORMAL");
  75551. if (mesh.nonUniformScaling) {
  75552. defines.push("#define NONUNIFORMSCALING");
  75553. }
  75554. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75555. defines.push("#define DIRECTIONINLIGHTDATA");
  75556. }
  75557. }
  75558. // Alpha test
  75559. if (material && material.needAlphaTesting()) {
  75560. var alphaTexture = material.getAlphaTestTexture();
  75561. if (alphaTexture) {
  75562. defines.push("#define ALPHATEST");
  75563. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75564. attribs.push(BABYLON.VertexBuffer.UVKind);
  75565. defines.push("#define UV1");
  75566. }
  75567. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75568. if (alphaTexture.coordinatesIndex === 1) {
  75569. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75570. defines.push("#define UV2");
  75571. }
  75572. }
  75573. }
  75574. }
  75575. // Bones
  75576. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75577. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75578. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75579. if (mesh.numBoneInfluencers > 4) {
  75580. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75581. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75582. }
  75583. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75584. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  75585. }
  75586. else {
  75587. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75588. }
  75589. // Morph targets
  75590. var manager = mesh.morphTargetManager;
  75591. var morphInfluencers = 0;
  75592. if (manager) {
  75593. if (manager.numInfluencers > 0) {
  75594. defines.push("#define MORPHTARGETS");
  75595. morphInfluencers = manager.numInfluencers;
  75596. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  75597. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  75598. }
  75599. }
  75600. // Instances
  75601. if (useInstances) {
  75602. defines.push("#define INSTANCES");
  75603. attribs.push("world0");
  75604. attribs.push("world1");
  75605. attribs.push("world2");
  75606. attribs.push("world3");
  75607. }
  75608. // Get correct effect
  75609. var join = defines.join("\n");
  75610. if (this._cachedDefines !== join) {
  75611. this._cachedDefines = join;
  75612. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  75613. }
  75614. if (!this._effect.isReady()) {
  75615. return false;
  75616. }
  75617. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75618. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  75619. this._initializeBlurRTTAndPostProcesses();
  75620. }
  75621. }
  75622. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  75623. return false;
  75624. }
  75625. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  75626. return false;
  75627. }
  75628. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  75629. return false;
  75630. }
  75631. return true;
  75632. };
  75633. /**
  75634. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  75635. * @param defines Defines of the material we want to update
  75636. * @param lightIndex Index of the light in the enabled light list of the material
  75637. */
  75638. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  75639. var scene = this._scene;
  75640. var light = this._light;
  75641. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75642. return;
  75643. }
  75644. defines["SHADOW" + lightIndex] = true;
  75645. if (this.useContactHardeningShadow) {
  75646. defines["SHADOWPCSS" + lightIndex] = true;
  75647. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75648. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75649. }
  75650. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75651. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75652. }
  75653. // else default to high.
  75654. }
  75655. if (this.usePercentageCloserFiltering) {
  75656. defines["SHADOWPCF" + lightIndex] = true;
  75657. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75658. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75659. }
  75660. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75661. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75662. }
  75663. // else default to high.
  75664. }
  75665. else if (this.usePoissonSampling) {
  75666. defines["SHADOWPOISSON" + lightIndex] = true;
  75667. }
  75668. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75669. defines["SHADOWESM" + lightIndex] = true;
  75670. }
  75671. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75672. defines["SHADOWCLOSEESM" + lightIndex] = true;
  75673. }
  75674. if (light.needCube()) {
  75675. defines["SHADOWCUBE" + lightIndex] = true;
  75676. }
  75677. };
  75678. /**
  75679. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  75680. * defined in the generator but impacting the effect).
  75681. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  75682. * @param effect The effect we are binfing the information for
  75683. */
  75684. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  75685. var light = this._light;
  75686. var scene = this._scene;
  75687. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75688. return;
  75689. }
  75690. var camera = scene.activeCamera;
  75691. if (!camera) {
  75692. return;
  75693. }
  75694. var shadowMap = this.getShadowMap();
  75695. if (!shadowMap) {
  75696. return;
  75697. }
  75698. if (!light.needCube()) {
  75699. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  75700. }
  75701. // Only PCF uses depth stencil texture.
  75702. if (this._filter === ShadowGenerator.FILTER_PCF) {
  75703. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75704. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75705. }
  75706. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  75707. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75708. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  75709. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75710. }
  75711. else {
  75712. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75713. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  75714. }
  75715. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  75716. };
  75717. /**
  75718. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  75719. * (eq to shadow prjection matrix * light transform matrix)
  75720. * @returns The transform matrix used to create the shadow map
  75721. */
  75722. ShadowGenerator.prototype.getTransformMatrix = function () {
  75723. var scene = this._scene;
  75724. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  75725. return this._transformMatrix;
  75726. }
  75727. this._currentRenderID = scene.getRenderId();
  75728. this._currentFaceIndexCache = this._currentFaceIndex;
  75729. var lightPosition = this._light.position;
  75730. if (this._light.computeTransformedInformation()) {
  75731. lightPosition = this._light.transformedPosition;
  75732. }
  75733. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  75734. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  75735. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  75736. }
  75737. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  75738. this._cachedPosition.copyFrom(lightPosition);
  75739. this._cachedDirection.copyFrom(this._lightDirection);
  75740. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  75741. var shadowMap = this.getShadowMap();
  75742. if (shadowMap) {
  75743. var renderList = shadowMap.renderList;
  75744. if (renderList) {
  75745. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  75746. }
  75747. }
  75748. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  75749. }
  75750. return this._transformMatrix;
  75751. };
  75752. /**
  75753. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  75754. * Cube and 2D textures for instance.
  75755. */
  75756. ShadowGenerator.prototype.recreateShadowMap = function () {
  75757. var shadowMap = this._shadowMap;
  75758. if (!shadowMap) {
  75759. return;
  75760. }
  75761. // Track render list.
  75762. var renderList = shadowMap.renderList;
  75763. // Clean up existing data.
  75764. this._disposeRTTandPostProcesses();
  75765. // Reinitializes.
  75766. this._initializeGenerator();
  75767. // Reaffect the filter to ensure a correct fallback if necessary.
  75768. this.filter = this.filter;
  75769. // Reaffect the filter.
  75770. this._applyFilterValues();
  75771. // Reaffect Render List.
  75772. this._shadowMap.renderList = renderList;
  75773. };
  75774. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  75775. if (this._shadowMap2) {
  75776. this._shadowMap2.dispose();
  75777. this._shadowMap2 = null;
  75778. }
  75779. if (this._boxBlurPostprocess) {
  75780. this._boxBlurPostprocess.dispose();
  75781. this._boxBlurPostprocess = null;
  75782. }
  75783. if (this._kernelBlurXPostprocess) {
  75784. this._kernelBlurXPostprocess.dispose();
  75785. this._kernelBlurXPostprocess = null;
  75786. }
  75787. if (this._kernelBlurYPostprocess) {
  75788. this._kernelBlurYPostprocess.dispose();
  75789. this._kernelBlurYPostprocess = null;
  75790. }
  75791. this._blurPostProcesses = [];
  75792. };
  75793. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  75794. if (this._shadowMap) {
  75795. this._shadowMap.dispose();
  75796. this._shadowMap = null;
  75797. }
  75798. this._disposeBlurPostProcesses();
  75799. };
  75800. /**
  75801. * Disposes the ShadowGenerator.
  75802. * Returns nothing.
  75803. */
  75804. ShadowGenerator.prototype.dispose = function () {
  75805. this._disposeRTTandPostProcesses();
  75806. if (this._light) {
  75807. this._light._shadowGenerator = null;
  75808. this._light._markMeshesAsLightDirty();
  75809. }
  75810. };
  75811. /**
  75812. * Serializes the shadow generator setup to a json object.
  75813. * @returns The serialized JSON object
  75814. */
  75815. ShadowGenerator.prototype.serialize = function () {
  75816. var serializationObject = {};
  75817. var shadowMap = this.getShadowMap();
  75818. if (!shadowMap) {
  75819. return serializationObject;
  75820. }
  75821. serializationObject.lightId = this._light.id;
  75822. serializationObject.mapSize = shadowMap.getRenderSize();
  75823. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  75824. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  75825. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75826. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75827. serializationObject.usePoissonSampling = this.usePoissonSampling;
  75828. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  75829. serializationObject.depthScale = this.depthScale;
  75830. serializationObject.darkness = this.getDarkness();
  75831. serializationObject.blurBoxOffset = this.blurBoxOffset;
  75832. serializationObject.blurKernel = this.blurKernel;
  75833. serializationObject.blurScale = this.blurScale;
  75834. serializationObject.useKernelBlur = this.useKernelBlur;
  75835. serializationObject.transparencyShadow = this._transparencyShadow;
  75836. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  75837. serializationObject.bias = this.bias;
  75838. serializationObject.normalBias = this.normalBias;
  75839. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  75840. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  75841. serializationObject.filteringQuality = this.filteringQuality;
  75842. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  75843. serializationObject.renderList = [];
  75844. if (shadowMap.renderList) {
  75845. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  75846. var mesh = shadowMap.renderList[meshIndex];
  75847. serializationObject.renderList.push(mesh.id);
  75848. }
  75849. }
  75850. return serializationObject;
  75851. };
  75852. /**
  75853. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  75854. * @param parsedShadowGenerator The JSON object to parse
  75855. * @param scene The scene to create the shadow map for
  75856. * @returns The parsed shadow generator
  75857. */
  75858. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  75859. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  75860. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  75861. var shadowMap = shadowGenerator.getShadowMap();
  75862. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  75863. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  75864. meshes.forEach(function (mesh) {
  75865. if (!shadowMap) {
  75866. return;
  75867. }
  75868. if (!shadowMap.renderList) {
  75869. shadowMap.renderList = [];
  75870. }
  75871. shadowMap.renderList.push(mesh);
  75872. });
  75873. }
  75874. if (parsedShadowGenerator.usePoissonSampling) {
  75875. shadowGenerator.usePoissonSampling = true;
  75876. }
  75877. else if (parsedShadowGenerator.useExponentialShadowMap) {
  75878. shadowGenerator.useExponentialShadowMap = true;
  75879. }
  75880. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  75881. shadowGenerator.useBlurExponentialShadowMap = true;
  75882. }
  75883. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  75884. shadowGenerator.useCloseExponentialShadowMap = true;
  75885. }
  75886. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  75887. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  75888. }
  75889. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  75890. shadowGenerator.usePercentageCloserFiltering = true;
  75891. }
  75892. else if (parsedShadowGenerator.useContactHardeningShadow) {
  75893. shadowGenerator.useContactHardeningShadow = true;
  75894. }
  75895. if (parsedShadowGenerator.filteringQuality) {
  75896. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  75897. }
  75898. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  75899. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  75900. }
  75901. // Backward compat
  75902. else if (parsedShadowGenerator.useVarianceShadowMap) {
  75903. shadowGenerator.useExponentialShadowMap = true;
  75904. }
  75905. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  75906. shadowGenerator.useBlurExponentialShadowMap = true;
  75907. }
  75908. if (parsedShadowGenerator.depthScale) {
  75909. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  75910. }
  75911. if (parsedShadowGenerator.blurScale) {
  75912. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  75913. }
  75914. if (parsedShadowGenerator.blurBoxOffset) {
  75915. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  75916. }
  75917. if (parsedShadowGenerator.useKernelBlur) {
  75918. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  75919. }
  75920. if (parsedShadowGenerator.blurKernel) {
  75921. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  75922. }
  75923. if (parsedShadowGenerator.bias !== undefined) {
  75924. shadowGenerator.bias = parsedShadowGenerator.bias;
  75925. }
  75926. if (parsedShadowGenerator.normalBias !== undefined) {
  75927. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  75928. }
  75929. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  75930. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  75931. }
  75932. if (parsedShadowGenerator.darkness) {
  75933. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  75934. }
  75935. if (parsedShadowGenerator.transparencyShadow) {
  75936. shadowGenerator.setTransparencyShadow(true);
  75937. }
  75938. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  75939. return shadowGenerator;
  75940. };
  75941. /**
  75942. * Shadow generator mode None: no filtering applied.
  75943. */
  75944. ShadowGenerator.FILTER_NONE = 0;
  75945. /**
  75946. * Shadow generator mode ESM: Exponential Shadow Mapping.
  75947. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75948. */
  75949. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  75950. /**
  75951. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  75952. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  75953. */
  75954. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  75955. /**
  75956. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  75957. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75958. */
  75959. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  75960. /**
  75961. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  75962. * edge artifacts on steep falloff.
  75963. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75964. */
  75965. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  75966. /**
  75967. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  75968. * edge artifacts on steep falloff.
  75969. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75970. */
  75971. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  75972. /**
  75973. * Shadow generator mode PCF: Percentage Closer Filtering
  75974. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  75975. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  75976. */
  75977. ShadowGenerator.FILTER_PCF = 6;
  75978. /**
  75979. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  75980. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  75981. * Contact Hardening
  75982. */
  75983. ShadowGenerator.FILTER_PCSS = 7;
  75984. /**
  75985. * Reserved for PCF and PCSS
  75986. * Highest Quality.
  75987. *
  75988. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  75989. *
  75990. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  75991. */
  75992. ShadowGenerator.QUALITY_HIGH = 0;
  75993. /**
  75994. * Reserved for PCF and PCSS
  75995. * Good tradeoff for quality/perf cross devices
  75996. *
  75997. * Execute PCF on a 3*3 kernel.
  75998. *
  75999. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  76000. */
  76001. ShadowGenerator.QUALITY_MEDIUM = 1;
  76002. /**
  76003. * Reserved for PCF and PCSS
  76004. * The lowest quality but the fastest.
  76005. *
  76006. * Execute PCF on a 1*1 kernel.
  76007. *
  76008. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  76009. */
  76010. ShadowGenerator.QUALITY_LOW = 2;
  76011. return ShadowGenerator;
  76012. }());
  76013. BABYLON.ShadowGenerator = ShadowGenerator;
  76014. })(BABYLON || (BABYLON = {}));
  76015. //# sourceMappingURL=babylon.shadowGenerator.js.map
  76016. var BABYLON;
  76017. (function (BABYLON) {
  76018. // Adds the parser to the scene parsers.
  76019. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  76020. // Shadows
  76021. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  76022. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  76023. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  76024. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  76025. // SG would be available on their associated lights
  76026. }
  76027. }
  76028. });
  76029. /**
  76030. * Defines the shadow generator component responsible to manage any shadow generators
  76031. * in a given scene.
  76032. */
  76033. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  76034. /**
  76035. * Creates a new instance of the component for the given scene
  76036. * @param scene Defines the scene to register the component in
  76037. */
  76038. function ShadowGeneratorSceneComponent(scene) {
  76039. /**
  76040. * The component name helpfull to identify the component in the list of scene components.
  76041. */
  76042. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  76043. this.scene = scene;
  76044. }
  76045. /**
  76046. * Registers the component in a given scene
  76047. */
  76048. ShadowGeneratorSceneComponent.prototype.register = function () {
  76049. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  76050. };
  76051. /**
  76052. * Rebuilds the elements related to this component in case of
  76053. * context lost for instance.
  76054. */
  76055. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  76056. // Nothing To Do Here.
  76057. };
  76058. /**
  76059. * Serializes the component data to the specified json object
  76060. * @param serializationObject The object to serialize to
  76061. */
  76062. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  76063. // Shadows
  76064. serializationObject.shadowGenerators = [];
  76065. var lights = this.scene.lights;
  76066. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  76067. var light = lights_1[_i];
  76068. var shadowGenerator = light.getShadowGenerator();
  76069. if (shadowGenerator) {
  76070. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  76071. }
  76072. }
  76073. };
  76074. /**
  76075. * Adds all the element from the container to the scene
  76076. * @param container the container holding the elements
  76077. */
  76078. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  76079. // Nothing To Do Here. (directly attached to a light)
  76080. };
  76081. /**
  76082. * Removes all the elements in the container from the scene
  76083. * @param container contains the elements to remove
  76084. */
  76085. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  76086. // Nothing To Do Here. (directly attached to a light)
  76087. };
  76088. /**
  76089. * Rebuilds the elements related to this component in case of
  76090. * context lost for instance.
  76091. */
  76092. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  76093. // Nothing To Do Here.
  76094. };
  76095. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76096. // Shadows
  76097. var scene = this.scene;
  76098. if (this.scene.shadowsEnabled) {
  76099. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  76100. var light = scene.lights[lightIndex];
  76101. var shadowGenerator = light.getShadowGenerator();
  76102. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  76103. var shadowMap = (shadowGenerator.getShadowMap());
  76104. if (scene.textures.indexOf(shadowMap) !== -1) {
  76105. renderTargets.push(shadowMap);
  76106. }
  76107. }
  76108. }
  76109. }
  76110. };
  76111. return ShadowGeneratorSceneComponent;
  76112. }());
  76113. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  76114. })(BABYLON || (BABYLON = {}));
  76115. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  76116. var BABYLON;
  76117. (function (BABYLON) {
  76118. /**
  76119. * Class used for the default loading screen
  76120. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  76121. */
  76122. var DefaultLoadingScreen = /** @class */ (function () {
  76123. /**
  76124. * Creates a new default loading screen
  76125. * @param _renderingCanvas defines the canvas used to render the scene
  76126. * @param _loadingText defines the default text to display
  76127. * @param _loadingDivBackgroundColor defines the default background color
  76128. */
  76129. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  76130. if (_loadingText === void 0) { _loadingText = ""; }
  76131. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  76132. var _this = this;
  76133. this._renderingCanvas = _renderingCanvas;
  76134. this._loadingText = _loadingText;
  76135. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  76136. // Resize
  76137. this._resizeLoadingUI = function () {
  76138. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  76139. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  76140. if (!_this._loadingDiv) {
  76141. return;
  76142. }
  76143. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  76144. _this._loadingDiv.style.left = canvasRect.left + "px";
  76145. _this._loadingDiv.style.top = canvasRect.top + "px";
  76146. _this._loadingDiv.style.width = canvasRect.width + "px";
  76147. _this._loadingDiv.style.height = canvasRect.height + "px";
  76148. };
  76149. }
  76150. /**
  76151. * Function called to display the loading screen
  76152. */
  76153. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  76154. if (this._loadingDiv) {
  76155. // Do not add a loading screen if there is already one
  76156. return;
  76157. }
  76158. this._loadingDiv = document.createElement("div");
  76159. this._loadingDiv.id = "babylonjsLoadingDiv";
  76160. this._loadingDiv.style.opacity = "0";
  76161. this._loadingDiv.style.transition = "opacity 1.5s ease";
  76162. this._loadingDiv.style.pointerEvents = "none";
  76163. // Loading text
  76164. this._loadingTextDiv = document.createElement("div");
  76165. this._loadingTextDiv.style.position = "absolute";
  76166. this._loadingTextDiv.style.left = "0";
  76167. this._loadingTextDiv.style.top = "50%";
  76168. this._loadingTextDiv.style.marginTop = "80px";
  76169. this._loadingTextDiv.style.width = "100%";
  76170. this._loadingTextDiv.style.height = "20px";
  76171. this._loadingTextDiv.style.fontFamily = "Arial";
  76172. this._loadingTextDiv.style.fontSize = "14px";
  76173. this._loadingTextDiv.style.color = "white";
  76174. this._loadingTextDiv.style.textAlign = "center";
  76175. this._loadingTextDiv.innerHTML = "Loading";
  76176. this._loadingDiv.appendChild(this._loadingTextDiv);
  76177. //set the predefined text
  76178. this._loadingTextDiv.innerHTML = this._loadingText;
  76179. // Generating keyframes
  76180. var style = document.createElement('style');
  76181. style.type = 'text/css';
  76182. 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 }";
  76183. style.innerHTML = keyFrames;
  76184. document.getElementsByTagName('head')[0].appendChild(style);
  76185. // Loading img
  76186. var imgBack = new Image();
  76187. 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";
  76188. imgBack.style.position = "absolute";
  76189. imgBack.style.left = "50%";
  76190. imgBack.style.top = "50%";
  76191. imgBack.style.marginLeft = "-60px";
  76192. imgBack.style.marginTop = "-60px";
  76193. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  76194. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  76195. imgBack.style.transformOrigin = "50% 50%";
  76196. imgBack.style.webkitTransformOrigin = "50% 50%";
  76197. this._loadingDiv.appendChild(imgBack);
  76198. this._resizeLoadingUI();
  76199. window.addEventListener("resize", this._resizeLoadingUI);
  76200. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  76201. document.body.appendChild(this._loadingDiv);
  76202. this._loadingDiv.style.opacity = "1";
  76203. };
  76204. /**
  76205. * Function called to hide the loading screen
  76206. */
  76207. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  76208. var _this = this;
  76209. if (!this._loadingDiv) {
  76210. return;
  76211. }
  76212. var onTransitionEnd = function () {
  76213. if (!_this._loadingDiv) {
  76214. return;
  76215. }
  76216. document.body.removeChild(_this._loadingDiv);
  76217. window.removeEventListener("resize", _this._resizeLoadingUI);
  76218. _this._loadingDiv = null;
  76219. };
  76220. this._loadingDiv.style.opacity = "0";
  76221. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  76222. };
  76223. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  76224. get: function () {
  76225. return this._loadingText;
  76226. },
  76227. /**
  76228. * Gets or sets the text to display while loading
  76229. */
  76230. set: function (text) {
  76231. this._loadingText = text;
  76232. if (this._loadingTextDiv) {
  76233. this._loadingTextDiv.innerHTML = this._loadingText;
  76234. }
  76235. },
  76236. enumerable: true,
  76237. configurable: true
  76238. });
  76239. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  76240. /**
  76241. * Gets or sets the color to use for the background
  76242. */
  76243. get: function () {
  76244. return this._loadingDivBackgroundColor;
  76245. },
  76246. set: function (color) {
  76247. this._loadingDivBackgroundColor = color;
  76248. if (!this._loadingDiv) {
  76249. return;
  76250. }
  76251. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  76252. },
  76253. enumerable: true,
  76254. configurable: true
  76255. });
  76256. return DefaultLoadingScreen;
  76257. }());
  76258. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  76259. })(BABYLON || (BABYLON = {}));
  76260. //# sourceMappingURL=babylon.loadingScreen.js.map
  76261. var BABYLON;
  76262. (function (BABYLON) {
  76263. /**
  76264. * Class used to represent data loading progression
  76265. */
  76266. var SceneLoaderProgressEvent = /** @class */ (function () {
  76267. /**
  76268. * Create a new progress event
  76269. * @param lengthComputable defines if data length to load can be evaluated
  76270. * @param loaded defines the loaded data length
  76271. * @param total defines the data length to load
  76272. */
  76273. function SceneLoaderProgressEvent(
  76274. /** defines if data length to load can be evaluated */
  76275. lengthComputable,
  76276. /** defines the loaded data length */
  76277. loaded,
  76278. /** defines the data length to load */
  76279. total) {
  76280. this.lengthComputable = lengthComputable;
  76281. this.loaded = loaded;
  76282. this.total = total;
  76283. }
  76284. /**
  76285. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  76286. * @param event defines the source event
  76287. * @returns a new SceneLoaderProgressEvent
  76288. */
  76289. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  76290. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  76291. };
  76292. return SceneLoaderProgressEvent;
  76293. }());
  76294. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  76295. /**
  76296. * Class used to load scene from various file formats using registered plugins
  76297. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  76298. */
  76299. var SceneLoader = /** @class */ (function () {
  76300. function SceneLoader() {
  76301. }
  76302. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  76303. /**
  76304. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  76305. */
  76306. get: function () {
  76307. return SceneLoader._ForceFullSceneLoadingForIncremental;
  76308. },
  76309. set: function (value) {
  76310. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  76311. },
  76312. enumerable: true,
  76313. configurable: true
  76314. });
  76315. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  76316. /**
  76317. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  76318. */
  76319. get: function () {
  76320. return SceneLoader._ShowLoadingScreen;
  76321. },
  76322. set: function (value) {
  76323. SceneLoader._ShowLoadingScreen = value;
  76324. },
  76325. enumerable: true,
  76326. configurable: true
  76327. });
  76328. Object.defineProperty(SceneLoader, "loggingLevel", {
  76329. /**
  76330. * Defines the current logging level (while loading the scene)
  76331. * @ignorenaming
  76332. */
  76333. get: function () {
  76334. return SceneLoader._loggingLevel;
  76335. },
  76336. set: function (value) {
  76337. SceneLoader._loggingLevel = value;
  76338. },
  76339. enumerable: true,
  76340. configurable: true
  76341. });
  76342. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  76343. /**
  76344. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  76345. */
  76346. get: function () {
  76347. return SceneLoader._CleanBoneMatrixWeights;
  76348. },
  76349. set: function (value) {
  76350. SceneLoader._CleanBoneMatrixWeights = value;
  76351. },
  76352. enumerable: true,
  76353. configurable: true
  76354. });
  76355. SceneLoader._getDefaultPlugin = function () {
  76356. return SceneLoader._registeredPlugins[".babylon"];
  76357. };
  76358. SceneLoader._getPluginForExtension = function (extension) {
  76359. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  76360. if (registeredPlugin) {
  76361. return registeredPlugin;
  76362. }
  76363. 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");
  76364. return SceneLoader._getDefaultPlugin();
  76365. };
  76366. SceneLoader._getPluginForDirectLoad = function (data) {
  76367. for (var extension in SceneLoader._registeredPlugins) {
  76368. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  76369. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  76370. return SceneLoader._registeredPlugins[extension];
  76371. }
  76372. }
  76373. return SceneLoader._getDefaultPlugin();
  76374. };
  76375. SceneLoader._getPluginForFilename = function (sceneFilename) {
  76376. var queryStringPosition = sceneFilename.indexOf("?");
  76377. if (queryStringPosition !== -1) {
  76378. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  76379. }
  76380. var dotPosition = sceneFilename.lastIndexOf(".");
  76381. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  76382. return SceneLoader._getPluginForExtension(extension);
  76383. };
  76384. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  76385. SceneLoader._getDirectLoad = function (sceneFilename) {
  76386. if (sceneFilename.substr(0, 5) === "data:") {
  76387. return sceneFilename.substr(5);
  76388. }
  76389. return null;
  76390. };
  76391. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  76392. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  76393. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  76394. var plugin;
  76395. if (registeredPlugin.plugin.createPlugin) {
  76396. plugin = registeredPlugin.plugin.createPlugin();
  76397. }
  76398. else {
  76399. plugin = registeredPlugin.plugin;
  76400. }
  76401. var useArrayBuffer = registeredPlugin.isBinary;
  76402. var database;
  76403. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  76404. var dataCallback = function (data, responseURL) {
  76405. if (scene.isDisposed) {
  76406. onError("Scene has been disposed");
  76407. return;
  76408. }
  76409. scene.database = database;
  76410. onSuccess(plugin, data, responseURL);
  76411. };
  76412. var request = null;
  76413. var pluginDisposed = false;
  76414. var onDisposeObservable = plugin.onDisposeObservable;
  76415. if (onDisposeObservable) {
  76416. onDisposeObservable.add(function () {
  76417. pluginDisposed = true;
  76418. if (request) {
  76419. request.abort();
  76420. request = null;
  76421. }
  76422. onDispose();
  76423. });
  76424. }
  76425. var manifestChecked = function () {
  76426. if (pluginDisposed) {
  76427. return;
  76428. }
  76429. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  76430. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  76431. } : undefined, database, useArrayBuffer, function (request, exception) {
  76432. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  76433. });
  76434. };
  76435. if (directLoad) {
  76436. dataCallback(directLoad);
  76437. return plugin;
  76438. }
  76439. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  76440. var engine = scene.getEngine();
  76441. var canUseOfflineSupport = engine.enableOfflineSupport;
  76442. if (canUseOfflineSupport) {
  76443. // Also check for exceptions
  76444. var exceptionFound = false;
  76445. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  76446. var regex = _a[_i];
  76447. if (regex.test(fileInfo.url)) {
  76448. exceptionFound = true;
  76449. break;
  76450. }
  76451. }
  76452. canUseOfflineSupport = !exceptionFound;
  76453. }
  76454. if (canUseOfflineSupport) {
  76455. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  76456. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  76457. }
  76458. else {
  76459. manifestChecked();
  76460. }
  76461. }
  76462. // Loading file from disk via input file or drag'n'drop
  76463. else {
  76464. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  76465. if (file) {
  76466. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  76467. }
  76468. else {
  76469. onError("Unable to find file named " + fileInfo.name);
  76470. }
  76471. }
  76472. return plugin;
  76473. };
  76474. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  76475. var url;
  76476. var name;
  76477. if (!sceneFilename) {
  76478. url = rootUrl;
  76479. name = BABYLON.Tools.GetFilename(rootUrl);
  76480. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  76481. }
  76482. else {
  76483. if (sceneFilename.substr(0, 1) === "/") {
  76484. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  76485. return null;
  76486. }
  76487. url = rootUrl + sceneFilename;
  76488. name = sceneFilename;
  76489. }
  76490. return {
  76491. url: url,
  76492. rootUrl: rootUrl,
  76493. name: name
  76494. };
  76495. };
  76496. // Public functions
  76497. /**
  76498. * Gets a plugin that can load the given extension
  76499. * @param extension defines the extension to load
  76500. * @returns a plugin or null if none works
  76501. */
  76502. SceneLoader.GetPluginForExtension = function (extension) {
  76503. return SceneLoader._getPluginForExtension(extension).plugin;
  76504. };
  76505. /**
  76506. * Gets a boolean indicating that the given extension can be loaded
  76507. * @param extension defines the extension to load
  76508. * @returns true if the extension is supported
  76509. */
  76510. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  76511. return !!SceneLoader._registeredPlugins[extension];
  76512. };
  76513. /**
  76514. * Adds a new plugin to the list of registered plugins
  76515. * @param plugin defines the plugin to add
  76516. */
  76517. SceneLoader.RegisterPlugin = function (plugin) {
  76518. if (typeof plugin.extensions === "string") {
  76519. var extension = plugin.extensions;
  76520. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76521. plugin: plugin,
  76522. isBinary: false
  76523. };
  76524. }
  76525. else {
  76526. var extensions = plugin.extensions;
  76527. Object.keys(extensions).forEach(function (extension) {
  76528. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76529. plugin: plugin,
  76530. isBinary: extensions[extension].isBinary
  76531. };
  76532. });
  76533. }
  76534. };
  76535. /**
  76536. * Import meshes into a scene
  76537. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76538. * @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)
  76539. * @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)
  76540. * @param scene the instance of BABYLON.Scene to append to
  76541. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  76542. * @param onProgress a callback with a progress event for each file being loaded
  76543. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76544. * @param pluginExtension the extension used to determine the plugin
  76545. * @returns The loaded plugin
  76546. */
  76547. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76548. if (sceneFilename === void 0) { sceneFilename = ""; }
  76549. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76550. if (onSuccess === void 0) { onSuccess = null; }
  76551. if (onProgress === void 0) { onProgress = null; }
  76552. if (onError === void 0) { onError = null; }
  76553. if (pluginExtension === void 0) { pluginExtension = null; }
  76554. if (!scene) {
  76555. BABYLON.Tools.Error("No scene available to import mesh to");
  76556. return null;
  76557. }
  76558. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76559. if (!fileInfo) {
  76560. return null;
  76561. }
  76562. var loadingToken = {};
  76563. scene._addPendingData(loadingToken);
  76564. var disposeHandler = function () {
  76565. scene._removePendingData(loadingToken);
  76566. };
  76567. var errorHandler = function (message, exception) {
  76568. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  76569. if (onError) {
  76570. onError(scene, errorMessage, exception);
  76571. }
  76572. else {
  76573. BABYLON.Tools.Error(errorMessage);
  76574. // should the exception be thrown?
  76575. }
  76576. disposeHandler();
  76577. };
  76578. var progressHandler = onProgress ? function (event) {
  76579. try {
  76580. onProgress(event);
  76581. }
  76582. catch (e) {
  76583. errorHandler("Error in onProgress callback", e);
  76584. }
  76585. } : undefined;
  76586. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  76587. scene.importedMeshesFiles.push(fileInfo.url);
  76588. if (onSuccess) {
  76589. try {
  76590. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  76591. }
  76592. catch (e) {
  76593. errorHandler("Error in onSuccess callback", e);
  76594. }
  76595. }
  76596. scene._removePendingData(loadingToken);
  76597. };
  76598. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76599. if (plugin.rewriteRootURL) {
  76600. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  76601. }
  76602. if (plugin.importMesh) {
  76603. var syncedPlugin = plugin;
  76604. var meshes = new Array();
  76605. var particleSystems = new Array();
  76606. var skeletons = new Array();
  76607. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  76608. return;
  76609. }
  76610. scene.loadingPluginName = plugin.name;
  76611. successHandler(meshes, particleSystems, skeletons, []);
  76612. }
  76613. else {
  76614. var asyncedPlugin = plugin;
  76615. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  76616. scene.loadingPluginName = plugin.name;
  76617. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  76618. }).catch(function (error) {
  76619. errorHandler(error.message, error);
  76620. });
  76621. }
  76622. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76623. };
  76624. /**
  76625. * Import meshes into a scene
  76626. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76627. * @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)
  76628. * @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)
  76629. * @param scene the instance of BABYLON.Scene to append to
  76630. * @param onProgress a callback with a progress event for each file being loaded
  76631. * @param pluginExtension the extension used to determine the plugin
  76632. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  76633. */
  76634. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76635. if (sceneFilename === void 0) { sceneFilename = ""; }
  76636. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76637. if (onProgress === void 0) { onProgress = null; }
  76638. if (pluginExtension === void 0) { pluginExtension = null; }
  76639. return new Promise(function (resolve, reject) {
  76640. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  76641. resolve({
  76642. meshes: meshes,
  76643. particleSystems: particleSystems,
  76644. skeletons: skeletons,
  76645. animationGroups: animationGroups
  76646. });
  76647. }, onProgress, function (scene, message, exception) {
  76648. reject(exception || new Error(message));
  76649. }, pluginExtension);
  76650. });
  76651. };
  76652. /**
  76653. * Load a scene
  76654. * @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)
  76655. * @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)
  76656. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76657. * @param onSuccess a callback with the scene when import succeeds
  76658. * @param onProgress a callback with a progress event for each file being loaded
  76659. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76660. * @param pluginExtension the extension used to determine the plugin
  76661. * @returns The loaded plugin
  76662. */
  76663. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  76664. if (onSuccess === void 0) { onSuccess = null; }
  76665. if (onProgress === void 0) { onProgress = null; }
  76666. if (onError === void 0) { onError = null; }
  76667. if (pluginExtension === void 0) { pluginExtension = null; }
  76668. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  76669. };
  76670. /**
  76671. * Load a scene
  76672. * @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)
  76673. * @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)
  76674. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76675. * @param onProgress a callback with a progress event for each file being loaded
  76676. * @param pluginExtension the extension used to determine the plugin
  76677. * @returns The loaded scene
  76678. */
  76679. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  76680. if (onProgress === void 0) { onProgress = null; }
  76681. if (pluginExtension === void 0) { pluginExtension = null; }
  76682. return new Promise(function (resolve, reject) {
  76683. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  76684. resolve(scene);
  76685. }, onProgress, function (scene, message, exception) {
  76686. reject(exception || new Error(message));
  76687. }, pluginExtension);
  76688. });
  76689. };
  76690. /**
  76691. * Append a scene
  76692. * @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)
  76693. * @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)
  76694. * @param scene is the instance of BABYLON.Scene to append to
  76695. * @param onSuccess a callback with the scene when import succeeds
  76696. * @param onProgress a callback with a progress event for each file being loaded
  76697. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76698. * @param pluginExtension the extension used to determine the plugin
  76699. * @returns The loaded plugin
  76700. */
  76701. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76702. if (sceneFilename === void 0) { sceneFilename = ""; }
  76703. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76704. if (onSuccess === void 0) { onSuccess = null; }
  76705. if (onProgress === void 0) { onProgress = null; }
  76706. if (onError === void 0) { onError = null; }
  76707. if (pluginExtension === void 0) { pluginExtension = null; }
  76708. if (!scene) {
  76709. BABYLON.Tools.Error("No scene available to append to");
  76710. return null;
  76711. }
  76712. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76713. if (!fileInfo) {
  76714. return null;
  76715. }
  76716. if (SceneLoader.ShowLoadingScreen) {
  76717. scene.getEngine().displayLoadingUI();
  76718. }
  76719. var loadingToken = {};
  76720. scene._addPendingData(loadingToken);
  76721. var disposeHandler = function () {
  76722. scene._removePendingData(loadingToken);
  76723. scene.getEngine().hideLoadingUI();
  76724. };
  76725. var errorHandler = function (message, exception) {
  76726. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  76727. if (onError) {
  76728. onError(scene, errorMessage, exception);
  76729. }
  76730. else {
  76731. BABYLON.Tools.Error(errorMessage);
  76732. // should the exception be thrown?
  76733. }
  76734. disposeHandler();
  76735. };
  76736. var progressHandler = onProgress ? function (event) {
  76737. try {
  76738. onProgress(event);
  76739. }
  76740. catch (e) {
  76741. errorHandler("Error in onProgress callback", e);
  76742. }
  76743. } : undefined;
  76744. var successHandler = function () {
  76745. if (onSuccess) {
  76746. try {
  76747. onSuccess(scene);
  76748. }
  76749. catch (e) {
  76750. errorHandler("Error in onSuccess callback", e);
  76751. }
  76752. }
  76753. scene._removePendingData(loadingToken);
  76754. };
  76755. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76756. if (plugin.load) {
  76757. var syncedPlugin = plugin;
  76758. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  76759. return;
  76760. }
  76761. scene.loadingPluginName = plugin.name;
  76762. successHandler();
  76763. }
  76764. else {
  76765. var asyncedPlugin = plugin;
  76766. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  76767. scene.loadingPluginName = plugin.name;
  76768. successHandler();
  76769. }).catch(function (error) {
  76770. errorHandler(error.message, error);
  76771. });
  76772. }
  76773. if (SceneLoader.ShowLoadingScreen) {
  76774. scene.executeWhenReady(function () {
  76775. scene.getEngine().hideLoadingUI();
  76776. });
  76777. }
  76778. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76779. };
  76780. /**
  76781. * Append a scene
  76782. * @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)
  76783. * @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)
  76784. * @param scene is the instance of BABYLON.Scene to append to
  76785. * @param onProgress a callback with a progress event for each file being loaded
  76786. * @param pluginExtension the extension used to determine the plugin
  76787. * @returns The given scene
  76788. */
  76789. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76790. if (sceneFilename === void 0) { sceneFilename = ""; }
  76791. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76792. if (onProgress === void 0) { onProgress = null; }
  76793. if (pluginExtension === void 0) { pluginExtension = null; }
  76794. return new Promise(function (resolve, reject) {
  76795. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  76796. resolve(scene);
  76797. }, onProgress, function (scene, message, exception) {
  76798. reject(exception || new Error(message));
  76799. }, pluginExtension);
  76800. });
  76801. };
  76802. /**
  76803. * Load a scene into an asset container
  76804. * @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)
  76805. * @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)
  76806. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  76807. * @param onSuccess a callback with the scene when import succeeds
  76808. * @param onProgress a callback with a progress event for each file being loaded
  76809. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76810. * @param pluginExtension the extension used to determine the plugin
  76811. * @returns The loaded plugin
  76812. */
  76813. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76814. if (sceneFilename === void 0) { sceneFilename = ""; }
  76815. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76816. if (onSuccess === void 0) { onSuccess = null; }
  76817. if (onProgress === void 0) { onProgress = null; }
  76818. if (onError === void 0) { onError = null; }
  76819. if (pluginExtension === void 0) { pluginExtension = null; }
  76820. if (!scene) {
  76821. BABYLON.Tools.Error("No scene available to load asset container to");
  76822. return null;
  76823. }
  76824. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76825. if (!fileInfo) {
  76826. return null;
  76827. }
  76828. var loadingToken = {};
  76829. scene._addPendingData(loadingToken);
  76830. var disposeHandler = function () {
  76831. scene._removePendingData(loadingToken);
  76832. };
  76833. var errorHandler = function (message, exception) {
  76834. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  76835. if (onError) {
  76836. onError(scene, errorMessage, exception);
  76837. }
  76838. else {
  76839. BABYLON.Tools.Error(errorMessage);
  76840. // should the exception be thrown?
  76841. }
  76842. disposeHandler();
  76843. };
  76844. var progressHandler = onProgress ? function (event) {
  76845. try {
  76846. onProgress(event);
  76847. }
  76848. catch (e) {
  76849. errorHandler("Error in onProgress callback", e);
  76850. }
  76851. } : undefined;
  76852. var successHandler = function (assets) {
  76853. if (onSuccess) {
  76854. try {
  76855. onSuccess(assets);
  76856. }
  76857. catch (e) {
  76858. errorHandler("Error in onSuccess callback", e);
  76859. }
  76860. }
  76861. scene._removePendingData(loadingToken);
  76862. };
  76863. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76864. if (plugin.loadAssetContainer) {
  76865. var syncedPlugin = plugin;
  76866. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  76867. if (!assetContainer) {
  76868. return;
  76869. }
  76870. scene.loadingPluginName = plugin.name;
  76871. successHandler(assetContainer);
  76872. }
  76873. else if (plugin.loadAssetContainerAsync) {
  76874. var asyncedPlugin = plugin;
  76875. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  76876. scene.loadingPluginName = plugin.name;
  76877. successHandler(assetContainer);
  76878. }).catch(function (error) {
  76879. errorHandler(error.message, error);
  76880. });
  76881. }
  76882. else {
  76883. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  76884. }
  76885. if (SceneLoader.ShowLoadingScreen) {
  76886. scene.executeWhenReady(function () {
  76887. scene.getEngine().hideLoadingUI();
  76888. });
  76889. }
  76890. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76891. };
  76892. /**
  76893. * Load a scene into an asset container
  76894. * @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)
  76895. * @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)
  76896. * @param scene is the instance of BABYLON.Scene to append to
  76897. * @param onProgress a callback with a progress event for each file being loaded
  76898. * @param pluginExtension the extension used to determine the plugin
  76899. * @returns The loaded asset container
  76900. */
  76901. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76902. if (sceneFilename === void 0) { sceneFilename = ""; }
  76903. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76904. if (onProgress === void 0) { onProgress = null; }
  76905. if (pluginExtension === void 0) { pluginExtension = null; }
  76906. return new Promise(function (resolve, reject) {
  76907. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  76908. resolve(assetContainer);
  76909. }, onProgress, function (scene, message, exception) {
  76910. reject(exception || new Error(message));
  76911. }, pluginExtension);
  76912. });
  76913. };
  76914. // Flags
  76915. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  76916. SceneLoader._ShowLoadingScreen = true;
  76917. SceneLoader._CleanBoneMatrixWeights = false;
  76918. /**
  76919. * No logging while loading
  76920. */
  76921. SceneLoader.NO_LOGGING = 0;
  76922. /**
  76923. * Minimal logging while loading
  76924. */
  76925. SceneLoader.MINIMAL_LOGGING = 1;
  76926. /**
  76927. * Summary logging while loading
  76928. */
  76929. SceneLoader.SUMMARY_LOGGING = 2;
  76930. /**
  76931. * Detailled logging while loading
  76932. */
  76933. SceneLoader.DETAILED_LOGGING = 3;
  76934. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  76935. // Members
  76936. /**
  76937. * Event raised when a plugin is used to load a scene
  76938. */
  76939. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  76940. SceneLoader._registeredPlugins = {};
  76941. return SceneLoader;
  76942. }());
  76943. BABYLON.SceneLoader = SceneLoader;
  76944. })(BABYLON || (BABYLON = {}));
  76945. //# sourceMappingURL=babylon.sceneLoader.js.map
  76946. var BABYLON;
  76947. (function (BABYLON) {
  76948. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  76949. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  76950. var parsedMaterial = parsedData.materials[index];
  76951. if (parsedMaterial.id === id) {
  76952. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  76953. }
  76954. }
  76955. return null;
  76956. };
  76957. var isDescendantOf = function (mesh, names, hierarchyIds) {
  76958. for (var i in names) {
  76959. if (mesh.name === names[i]) {
  76960. hierarchyIds.push(mesh.id);
  76961. return true;
  76962. }
  76963. }
  76964. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  76965. hierarchyIds.push(mesh.id);
  76966. return true;
  76967. }
  76968. return false;
  76969. };
  76970. var logOperation = function (operation, producer) {
  76971. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  76972. };
  76973. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  76974. if (addToScene === void 0) { addToScene = false; }
  76975. var container = new BABYLON.AssetContainer(scene);
  76976. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76977. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76978. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76979. // and avoid problems with multiple concurrent .babylon loads.
  76980. var log = "importScene has failed JSON parse";
  76981. try {
  76982. var parsedData = JSON.parse(data);
  76983. log = "";
  76984. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  76985. var index;
  76986. var cache;
  76987. // Lights
  76988. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  76989. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  76990. var parsedLight = parsedData.lights[index];
  76991. var light = BABYLON.Light.Parse(parsedLight, scene);
  76992. if (light) {
  76993. container.lights.push(light);
  76994. log += (index === 0 ? "\n\tLights:" : "");
  76995. log += "\n\t\t" + light.toString(fullDetails);
  76996. }
  76997. }
  76998. }
  76999. // Animations
  77000. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  77001. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  77002. var parsedAnimation = parsedData.animations[index];
  77003. var animation = BABYLON.Animation.Parse(parsedAnimation);
  77004. scene.animations.push(animation);
  77005. container.animations.push(animation);
  77006. log += (index === 0 ? "\n\tAnimations:" : "");
  77007. log += "\n\t\t" + animation.toString(fullDetails);
  77008. }
  77009. }
  77010. // Materials
  77011. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  77012. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  77013. var parsedMaterial = parsedData.materials[index];
  77014. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  77015. container.materials.push(mat);
  77016. log += (index === 0 ? "\n\tMaterials:" : "");
  77017. log += "\n\t\t" + mat.toString(fullDetails);
  77018. }
  77019. }
  77020. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77021. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  77022. var parsedMultiMaterial = parsedData.multiMaterials[index];
  77023. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77024. container.multiMaterials.push(mmat);
  77025. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  77026. log += "\n\t\t" + mmat.toString(fullDetails);
  77027. }
  77028. }
  77029. // Morph targets
  77030. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77031. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77032. var managerData = _a[_i];
  77033. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  77034. }
  77035. }
  77036. // Skeletons
  77037. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77038. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  77039. var parsedSkeleton = parsedData.skeletons[index];
  77040. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77041. container.skeletons.push(skeleton);
  77042. log += (index === 0 ? "\n\tSkeletons:" : "");
  77043. log += "\n\t\t" + skeleton.toString(fullDetails);
  77044. }
  77045. }
  77046. // Geometries
  77047. var geometries = parsedData.geometries;
  77048. if (geometries !== undefined && geometries !== null) {
  77049. var addedGeometry = new Array();
  77050. // Boxes
  77051. var boxes = geometries.boxes;
  77052. if (boxes !== undefined && boxes !== null) {
  77053. for (index = 0, cache = boxes.length; index < cache; index++) {
  77054. var parsedBox = boxes[index];
  77055. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  77056. }
  77057. }
  77058. // Spheres
  77059. var spheres = geometries.spheres;
  77060. if (spheres !== undefined && spheres !== null) {
  77061. for (index = 0, cache = spheres.length; index < cache; index++) {
  77062. var parsedSphere = spheres[index];
  77063. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  77064. }
  77065. }
  77066. // Cylinders
  77067. var cylinders = geometries.cylinders;
  77068. if (cylinders !== undefined && cylinders !== null) {
  77069. for (index = 0, cache = cylinders.length; index < cache; index++) {
  77070. var parsedCylinder = cylinders[index];
  77071. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  77072. }
  77073. }
  77074. // Toruses
  77075. var toruses = geometries.toruses;
  77076. if (toruses !== undefined && toruses !== null) {
  77077. for (index = 0, cache = toruses.length; index < cache; index++) {
  77078. var parsedTorus = toruses[index];
  77079. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  77080. }
  77081. }
  77082. // Grounds
  77083. var grounds = geometries.grounds;
  77084. if (grounds !== undefined && grounds !== null) {
  77085. for (index = 0, cache = grounds.length; index < cache; index++) {
  77086. var parsedGround = grounds[index];
  77087. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  77088. }
  77089. }
  77090. // Planes
  77091. var planes = geometries.planes;
  77092. if (planes !== undefined && planes !== null) {
  77093. for (index = 0, cache = planes.length; index < cache; index++) {
  77094. var parsedPlane = planes[index];
  77095. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  77096. }
  77097. }
  77098. // TorusKnots
  77099. var torusKnots = geometries.torusKnots;
  77100. if (torusKnots !== undefined && torusKnots !== null) {
  77101. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  77102. var parsedTorusKnot = torusKnots[index];
  77103. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  77104. }
  77105. }
  77106. // VertexData
  77107. var vertexData = geometries.vertexData;
  77108. if (vertexData !== undefined && vertexData !== null) {
  77109. for (index = 0, cache = vertexData.length; index < cache; index++) {
  77110. var parsedVertexData = vertexData[index];
  77111. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  77112. }
  77113. }
  77114. addedGeometry.forEach(function (g) {
  77115. if (g) {
  77116. container.geometries.push(g);
  77117. }
  77118. });
  77119. }
  77120. // Transform nodes
  77121. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  77122. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  77123. var parsedTransformNode = parsedData.transformNodes[index];
  77124. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  77125. container.transformNodes.push(node);
  77126. }
  77127. }
  77128. // Meshes
  77129. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77130. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77131. var parsedMesh = parsedData.meshes[index];
  77132. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77133. container.meshes.push(mesh);
  77134. log += (index === 0 ? "\n\tMeshes:" : "");
  77135. log += "\n\t\t" + mesh.toString(fullDetails);
  77136. }
  77137. }
  77138. // Cameras
  77139. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  77140. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  77141. var parsedCamera = parsedData.cameras[index];
  77142. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  77143. container.cameras.push(camera);
  77144. log += (index === 0 ? "\n\tCameras:" : "");
  77145. log += "\n\t\t" + camera.toString(fullDetails);
  77146. }
  77147. }
  77148. // Animation Groups
  77149. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  77150. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  77151. var parsedAnimationGroup = parsedData.animationGroups[index];
  77152. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  77153. container.animationGroups.push(animationGroup);
  77154. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  77155. log += "\n\t\t" + animationGroup.toString(fullDetails);
  77156. }
  77157. }
  77158. // Browsing all the graph to connect the dots
  77159. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  77160. var camera = scene.cameras[index];
  77161. if (camera._waitingParentId) {
  77162. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  77163. camera._waitingParentId = null;
  77164. }
  77165. }
  77166. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  77167. var light_1 = scene.lights[index];
  77168. if (light_1 && light_1._waitingParentId) {
  77169. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  77170. light_1._waitingParentId = null;
  77171. }
  77172. }
  77173. // Connect parents & children and parse actions
  77174. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  77175. var transformNode = scene.transformNodes[index];
  77176. if (transformNode._waitingParentId) {
  77177. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  77178. transformNode._waitingParentId = null;
  77179. }
  77180. }
  77181. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77182. var mesh = scene.meshes[index];
  77183. if (mesh._waitingParentId) {
  77184. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  77185. mesh._waitingParentId = null;
  77186. }
  77187. }
  77188. // freeze world matrix application
  77189. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77190. var currentMesh = scene.meshes[index];
  77191. if (currentMesh._waitingFreezeWorldMatrix) {
  77192. currentMesh.freezeWorldMatrix();
  77193. currentMesh._waitingFreezeWorldMatrix = null;
  77194. }
  77195. else {
  77196. currentMesh.computeWorldMatrix(true);
  77197. }
  77198. }
  77199. // Lights exclusions / inclusions
  77200. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  77201. var light_2 = scene.lights[index];
  77202. // Excluded check
  77203. if (light_2._excludedMeshesIds.length > 0) {
  77204. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  77205. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  77206. if (excludedMesh) {
  77207. light_2.excludedMeshes.push(excludedMesh);
  77208. }
  77209. }
  77210. light_2._excludedMeshesIds = [];
  77211. }
  77212. // Included check
  77213. if (light_2._includedOnlyMeshesIds.length > 0) {
  77214. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  77215. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  77216. if (includedOnlyMesh) {
  77217. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  77218. }
  77219. }
  77220. light_2._includedOnlyMeshesIds = [];
  77221. }
  77222. }
  77223. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  77224. // Actions (scene) Done last as it can access other objects.
  77225. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77226. var mesh = scene.meshes[index];
  77227. if (mesh._waitingActions) {
  77228. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  77229. mesh._waitingActions = null;
  77230. }
  77231. }
  77232. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  77233. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  77234. }
  77235. if (!addToScene) {
  77236. container.removeAllFromScene();
  77237. }
  77238. }
  77239. catch (err) {
  77240. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  77241. if (onError) {
  77242. onError(msg, err);
  77243. }
  77244. else {
  77245. BABYLON.Tools.Log(msg);
  77246. throw err;
  77247. }
  77248. }
  77249. finally {
  77250. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77251. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77252. }
  77253. }
  77254. return container;
  77255. };
  77256. BABYLON.SceneLoader.RegisterPlugin({
  77257. name: "babylon.js",
  77258. extensions: ".babylon",
  77259. canDirectLoad: function (data) {
  77260. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  77261. return true;
  77262. }
  77263. return false;
  77264. },
  77265. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  77266. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77267. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77268. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77269. // and avoid problems with multiple concurrent .babylon loads.
  77270. var log = "importMesh has failed JSON parse";
  77271. try {
  77272. var parsedData = JSON.parse(data);
  77273. log = "";
  77274. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  77275. if (!meshesNames) {
  77276. meshesNames = null;
  77277. }
  77278. else if (!Array.isArray(meshesNames)) {
  77279. meshesNames = [meshesNames];
  77280. }
  77281. var hierarchyIds = new Array();
  77282. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77283. var loadedSkeletonsIds = [];
  77284. var loadedMaterialsIds = [];
  77285. var index;
  77286. var cache;
  77287. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77288. var parsedMesh = parsedData.meshes[index];
  77289. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  77290. if (meshesNames !== null) {
  77291. // Remove found mesh name from list.
  77292. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  77293. }
  77294. //Geometry?
  77295. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  77296. //does the file contain geometries?
  77297. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  77298. //find the correct geometry and add it to the scene
  77299. var found = false;
  77300. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  77301. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  77302. return;
  77303. }
  77304. else {
  77305. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  77306. if (parsedGeometryData.id === parsedMesh.geometryId) {
  77307. switch (geometryType) {
  77308. case "boxes":
  77309. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  77310. break;
  77311. case "spheres":
  77312. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  77313. break;
  77314. case "cylinders":
  77315. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  77316. break;
  77317. case "toruses":
  77318. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  77319. break;
  77320. case "grounds":
  77321. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  77322. break;
  77323. case "planes":
  77324. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  77325. break;
  77326. case "torusKnots":
  77327. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  77328. break;
  77329. case "vertexData":
  77330. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  77331. break;
  77332. }
  77333. found = true;
  77334. }
  77335. });
  77336. }
  77337. });
  77338. if (found === false) {
  77339. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  77340. }
  77341. }
  77342. }
  77343. // Material ?
  77344. if (parsedMesh.materialId) {
  77345. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  77346. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77347. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  77348. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  77349. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  77350. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  77351. var subMatId = parsedMultiMaterial.materials[matIndex];
  77352. loadedMaterialsIds.push(subMatId);
  77353. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  77354. if (mat) {
  77355. log += "\n\tMaterial " + mat.toString(fullDetails);
  77356. }
  77357. }
  77358. loadedMaterialsIds.push(parsedMultiMaterial.id);
  77359. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77360. if (mmat) {
  77361. materialFound = true;
  77362. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  77363. }
  77364. break;
  77365. }
  77366. }
  77367. }
  77368. if (materialFound === false) {
  77369. loadedMaterialsIds.push(parsedMesh.materialId);
  77370. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  77371. if (!mat) {
  77372. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  77373. }
  77374. else {
  77375. log += "\n\tMaterial " + mat.toString(fullDetails);
  77376. }
  77377. }
  77378. }
  77379. // Skeleton ?
  77380. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77381. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  77382. if (skeletonAlreadyLoaded === false) {
  77383. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  77384. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  77385. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  77386. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77387. skeletons.push(skeleton);
  77388. loadedSkeletonsIds.push(parsedSkeleton.id);
  77389. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  77390. }
  77391. }
  77392. }
  77393. }
  77394. // Morph targets ?
  77395. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77396. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77397. var managerData = _a[_i];
  77398. BABYLON.MorphTargetManager.Parse(managerData, scene);
  77399. }
  77400. }
  77401. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77402. meshes.push(mesh);
  77403. log += "\n\tMesh " + mesh.toString(fullDetails);
  77404. }
  77405. }
  77406. // Connecting parents
  77407. var currentMesh;
  77408. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77409. currentMesh = scene.meshes[index];
  77410. if (currentMesh._waitingParentId) {
  77411. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  77412. currentMesh._waitingParentId = null;
  77413. }
  77414. }
  77415. // freeze and compute world matrix application
  77416. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77417. currentMesh = scene.meshes[index];
  77418. if (currentMesh._waitingFreezeWorldMatrix) {
  77419. currentMesh.freezeWorldMatrix();
  77420. currentMesh._waitingFreezeWorldMatrix = null;
  77421. }
  77422. else {
  77423. currentMesh.computeWorldMatrix(true);
  77424. }
  77425. }
  77426. }
  77427. // Particles
  77428. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  77429. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  77430. if (parser) {
  77431. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  77432. var parsedParticleSystem = parsedData.particleSystems[index];
  77433. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  77434. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  77435. }
  77436. }
  77437. }
  77438. }
  77439. return true;
  77440. }
  77441. catch (err) {
  77442. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  77443. if (onError) {
  77444. onError(msg, err);
  77445. }
  77446. else {
  77447. BABYLON.Tools.Log(msg);
  77448. throw err;
  77449. }
  77450. }
  77451. finally {
  77452. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77453. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77454. }
  77455. }
  77456. return false;
  77457. },
  77458. load: function (scene, data, rootUrl, onError) {
  77459. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77460. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77461. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77462. // and avoid problems with multiple concurrent .babylon loads.
  77463. var log = "importScene has failed JSON parse";
  77464. try {
  77465. var parsedData = JSON.parse(data);
  77466. log = "";
  77467. // Scene
  77468. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  77469. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  77470. }
  77471. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  77472. scene.autoClear = parsedData.autoClear;
  77473. }
  77474. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  77475. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  77476. }
  77477. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  77478. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  77479. }
  77480. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  77481. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  77482. }
  77483. // Fog
  77484. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  77485. scene.fogMode = parsedData.fogMode;
  77486. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  77487. scene.fogStart = parsedData.fogStart;
  77488. scene.fogEnd = parsedData.fogEnd;
  77489. scene.fogDensity = parsedData.fogDensity;
  77490. log += "\tFog mode for scene: ";
  77491. switch (scene.fogMode) {
  77492. // getters not compiling, so using hardcoded
  77493. case 1:
  77494. log += "exp\n";
  77495. break;
  77496. case 2:
  77497. log += "exp2\n";
  77498. break;
  77499. case 3:
  77500. log += "linear\n";
  77501. break;
  77502. }
  77503. }
  77504. //Physics
  77505. if (parsedData.physicsEnabled) {
  77506. var physicsPlugin;
  77507. if (parsedData.physicsEngine === "cannon") {
  77508. physicsPlugin = new BABYLON.CannonJSPlugin();
  77509. }
  77510. else if (parsedData.physicsEngine === "oimo") {
  77511. physicsPlugin = new BABYLON.OimoJSPlugin();
  77512. }
  77513. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  77514. //else - default engine, which is currently oimo
  77515. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  77516. scene.enablePhysics(physicsGravity, physicsPlugin);
  77517. }
  77518. // Metadata
  77519. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  77520. scene.metadata = parsedData.metadata;
  77521. }
  77522. //collisions, if defined. otherwise, default is true
  77523. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  77524. scene.collisionsEnabled = parsedData.collisionsEnabled;
  77525. }
  77526. scene.workerCollisions = !!parsedData.workerCollisions;
  77527. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  77528. if (!container) {
  77529. return false;
  77530. }
  77531. if (parsedData.autoAnimate) {
  77532. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  77533. }
  77534. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  77535. scene.setActiveCameraByID(parsedData.activeCameraID);
  77536. }
  77537. // Environment texture
  77538. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  77539. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  77540. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  77541. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  77542. if (parsedData.environmentTextureRotationY) {
  77543. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  77544. }
  77545. scene.environmentTexture = hdrTexture;
  77546. }
  77547. else {
  77548. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  77549. if (parsedData.environmentTextureRotationY) {
  77550. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  77551. }
  77552. scene.environmentTexture = cubeTexture;
  77553. }
  77554. if (parsedData.createDefaultSkybox === true) {
  77555. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  77556. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  77557. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  77558. }
  77559. }
  77560. // Finish
  77561. return true;
  77562. }
  77563. catch (err) {
  77564. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  77565. if (onError) {
  77566. onError(msg, err);
  77567. }
  77568. else {
  77569. BABYLON.Tools.Log(msg);
  77570. throw err;
  77571. }
  77572. }
  77573. finally {
  77574. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77575. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77576. }
  77577. }
  77578. return false;
  77579. },
  77580. loadAssetContainer: function (scene, data, rootUrl, onError) {
  77581. var container = loadAssetContainer(scene, data, rootUrl, onError);
  77582. return container;
  77583. }
  77584. });
  77585. })(BABYLON || (BABYLON = {}));
  77586. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  77587. var BABYLON;
  77588. (function (BABYLON) {
  77589. /**
  77590. * Class used to help managing file picking and drag'n'drop
  77591. */
  77592. var FilesInput = /** @class */ (function () {
  77593. /**
  77594. * Creates a new FilesInput
  77595. * @param engine defines the rendering engine
  77596. * @param scene defines the hosting scene
  77597. * @param sceneLoadedCallback callback called when scene is loaded
  77598. * @param progressCallback callback called to track progress
  77599. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  77600. * @param textureLoadingCallback callback called when a texture is loading
  77601. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  77602. * @param onReloadCallback callback called when a reload is requested
  77603. * @param errorCallback callback call if an error occurs
  77604. */
  77605. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  77606. /**
  77607. * Callback called when a file is processed
  77608. */
  77609. this.onProcessFileCallback = function () { return true; };
  77610. this._engine = engine;
  77611. this._currentScene = scene;
  77612. this._sceneLoadedCallback = sceneLoadedCallback;
  77613. this._progressCallback = progressCallback;
  77614. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  77615. this._textureLoadingCallback = textureLoadingCallback;
  77616. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  77617. this._onReloadCallback = onReloadCallback;
  77618. this._errorCallback = errorCallback;
  77619. }
  77620. /**
  77621. * Calls this function to listen to drag'n'drop events on a specific DOM element
  77622. * @param elementToMonitor defines the DOM element to track
  77623. */
  77624. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  77625. var _this = this;
  77626. if (elementToMonitor) {
  77627. this._elementToMonitor = elementToMonitor;
  77628. this._dragEnterHandler = function (e) { _this.drag(e); };
  77629. this._dragOverHandler = function (e) { _this.drag(e); };
  77630. this._dropHandler = function (e) { _this.drop(e); };
  77631. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  77632. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  77633. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  77634. }
  77635. };
  77636. /**
  77637. * Release all associated resources
  77638. */
  77639. FilesInput.prototype.dispose = function () {
  77640. if (!this._elementToMonitor) {
  77641. return;
  77642. }
  77643. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  77644. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  77645. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  77646. };
  77647. FilesInput.prototype.renderFunction = function () {
  77648. if (this._additionalRenderLoopLogicCallback) {
  77649. this._additionalRenderLoopLogicCallback();
  77650. }
  77651. if (this._currentScene) {
  77652. if (this._textureLoadingCallback) {
  77653. var remaining = this._currentScene.getWaitingItemsCount();
  77654. if (remaining > 0) {
  77655. this._textureLoadingCallback(remaining);
  77656. }
  77657. }
  77658. this._currentScene.render();
  77659. }
  77660. };
  77661. FilesInput.prototype.drag = function (e) {
  77662. e.stopPropagation();
  77663. e.preventDefault();
  77664. };
  77665. FilesInput.prototype.drop = function (eventDrop) {
  77666. eventDrop.stopPropagation();
  77667. eventDrop.preventDefault();
  77668. this.loadFiles(eventDrop);
  77669. };
  77670. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  77671. var _this = this;
  77672. var reader = folder.createReader();
  77673. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  77674. reader.readEntries(function (entries) {
  77675. remaining.count += entries.length;
  77676. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  77677. var entry = entries_1[_i];
  77678. if (entry.isFile) {
  77679. entry.file(function (file) {
  77680. file.correctName = relativePath + file.name;
  77681. files.push(file);
  77682. if (--remaining.count === 0) {
  77683. callback();
  77684. }
  77685. });
  77686. }
  77687. else if (entry.isDirectory) {
  77688. _this._traverseFolder(entry, files, remaining, callback);
  77689. }
  77690. }
  77691. if (--remaining.count) {
  77692. callback();
  77693. }
  77694. });
  77695. };
  77696. FilesInput.prototype._processFiles = function (files) {
  77697. for (var i = 0; i < files.length; i++) {
  77698. var name = files[i].correctName.toLowerCase();
  77699. var extension = name.split('.').pop();
  77700. if (!this.onProcessFileCallback(files[i], name, extension)) {
  77701. continue;
  77702. }
  77703. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  77704. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  77705. this._sceneFileToLoad = files[i];
  77706. }
  77707. FilesInput.FilesToLoad[name] = files[i];
  77708. }
  77709. };
  77710. /**
  77711. * Load files from a drop event
  77712. * @param event defines the drop event to use as source
  77713. */
  77714. FilesInput.prototype.loadFiles = function (event) {
  77715. var _this = this;
  77716. // Handling data transfer via drag'n'drop
  77717. if (event && event.dataTransfer && event.dataTransfer.files) {
  77718. this._filesToLoad = event.dataTransfer.files;
  77719. }
  77720. // Handling files from input files
  77721. if (event && event.target && event.target.files) {
  77722. this._filesToLoad = event.target.files;
  77723. }
  77724. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  77725. return;
  77726. }
  77727. if (this._startingProcessingFilesCallback) {
  77728. this._startingProcessingFilesCallback(this._filesToLoad);
  77729. }
  77730. if (this._filesToLoad && this._filesToLoad.length > 0) {
  77731. var files_1 = new Array();
  77732. var folders = [];
  77733. var items = event.dataTransfer ? event.dataTransfer.items : null;
  77734. for (var i = 0; i < this._filesToLoad.length; i++) {
  77735. var fileToLoad = this._filesToLoad[i];
  77736. var name_1 = fileToLoad.name.toLowerCase();
  77737. var entry = void 0;
  77738. fileToLoad.correctName = name_1;
  77739. if (items) {
  77740. var item = items[i];
  77741. if (item.getAsEntry) {
  77742. entry = item.getAsEntry();
  77743. }
  77744. else if (item.webkitGetAsEntry) {
  77745. entry = item.webkitGetAsEntry();
  77746. }
  77747. }
  77748. if (!entry) {
  77749. files_1.push(fileToLoad);
  77750. }
  77751. else {
  77752. if (entry.isDirectory) {
  77753. folders.push(entry);
  77754. }
  77755. else {
  77756. files_1.push(fileToLoad);
  77757. }
  77758. }
  77759. }
  77760. if (folders.length === 0) {
  77761. this._processFiles(files_1);
  77762. this._processReload();
  77763. }
  77764. else {
  77765. var remaining = { count: folders.length };
  77766. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  77767. var folder = folders_1[_i];
  77768. this._traverseFolder(folder, files_1, remaining, function () {
  77769. _this._processFiles(files_1);
  77770. if (remaining.count === 0) {
  77771. _this._processReload();
  77772. }
  77773. });
  77774. }
  77775. }
  77776. }
  77777. };
  77778. FilesInput.prototype._processReload = function () {
  77779. if (this._onReloadCallback) {
  77780. this._onReloadCallback(this._sceneFileToLoad);
  77781. }
  77782. else {
  77783. this.reload();
  77784. }
  77785. };
  77786. /**
  77787. * Reload the current scene from the loaded files
  77788. */
  77789. FilesInput.prototype.reload = function () {
  77790. var _this = this;
  77791. // If a scene file has been provided
  77792. if (this._sceneFileToLoad) {
  77793. if (this._currentScene) {
  77794. if (BABYLON.Tools.errorsCount > 0) {
  77795. BABYLON.Tools.ClearLogCache();
  77796. }
  77797. this._engine.stopRenderLoop();
  77798. }
  77799. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  77800. if (_this._progressCallback) {
  77801. _this._progressCallback(progress);
  77802. }
  77803. }).then(function (scene) {
  77804. if (_this._currentScene) {
  77805. _this._currentScene.dispose();
  77806. }
  77807. _this._currentScene = scene;
  77808. if (_this._sceneLoadedCallback) {
  77809. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  77810. }
  77811. // Wait for textures and shaders to be ready
  77812. _this._currentScene.executeWhenReady(function () {
  77813. _this._engine.runRenderLoop(function () {
  77814. _this.renderFunction();
  77815. });
  77816. });
  77817. }).catch(function (error) {
  77818. if (_this._errorCallback) {
  77819. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  77820. }
  77821. });
  77822. }
  77823. else {
  77824. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  77825. }
  77826. };
  77827. /**
  77828. * List of files ready to be loaded
  77829. */
  77830. FilesInput.FilesToLoad = {};
  77831. return FilesInput;
  77832. }());
  77833. BABYLON.FilesInput = FilesInput;
  77834. })(BABYLON || (BABYLON = {}));
  77835. //# sourceMappingURL=babylon.filesInput.js.map
  77836. var BABYLON;
  77837. (function (BABYLON) {
  77838. /**
  77839. * Class used to store custom tags
  77840. */
  77841. var Tags = /** @class */ (function () {
  77842. function Tags() {
  77843. }
  77844. /**
  77845. * Adds support for tags on the given object
  77846. * @param obj defines the object to use
  77847. */
  77848. Tags.EnableFor = function (obj) {
  77849. obj._tags = obj._tags || {};
  77850. obj.hasTags = function () {
  77851. return Tags.HasTags(obj);
  77852. };
  77853. obj.addTags = function (tagsString) {
  77854. return Tags.AddTagsTo(obj, tagsString);
  77855. };
  77856. obj.removeTags = function (tagsString) {
  77857. return Tags.RemoveTagsFrom(obj, tagsString);
  77858. };
  77859. obj.matchesTagsQuery = function (tagsQuery) {
  77860. return Tags.MatchesQuery(obj, tagsQuery);
  77861. };
  77862. };
  77863. /**
  77864. * Removes tags support
  77865. * @param obj defines the object to use
  77866. */
  77867. Tags.DisableFor = function (obj) {
  77868. delete obj._tags;
  77869. delete obj.hasTags;
  77870. delete obj.addTags;
  77871. delete obj.removeTags;
  77872. delete obj.matchesTagsQuery;
  77873. };
  77874. /**
  77875. * Gets a boolean indicating if the given object has tags
  77876. * @param obj defines the object to use
  77877. * @returns a boolean
  77878. */
  77879. Tags.HasTags = function (obj) {
  77880. if (!obj._tags) {
  77881. return false;
  77882. }
  77883. return !BABYLON.Tools.IsEmpty(obj._tags);
  77884. };
  77885. /**
  77886. * Gets the tags available on a given object
  77887. * @param obj defines the object to use
  77888. * @param asString defines if the tags must be returned as a string instead of an array of strings
  77889. * @returns the tags
  77890. */
  77891. Tags.GetTags = function (obj, asString) {
  77892. if (asString === void 0) { asString = true; }
  77893. if (!obj._tags) {
  77894. return null;
  77895. }
  77896. if (asString) {
  77897. var tagsArray = [];
  77898. for (var tag in obj._tags) {
  77899. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  77900. tagsArray.push(tag);
  77901. }
  77902. }
  77903. return tagsArray.join(" ");
  77904. }
  77905. else {
  77906. return obj._tags;
  77907. }
  77908. };
  77909. /**
  77910. * Adds tags to an object
  77911. * @param obj defines the object to use
  77912. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  77913. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  77914. */
  77915. Tags.AddTagsTo = function (obj, tagsString) {
  77916. if (!tagsString) {
  77917. return;
  77918. }
  77919. if (typeof tagsString !== "string") {
  77920. return;
  77921. }
  77922. var tags = tagsString.split(" ");
  77923. tags.forEach(function (tag, index, array) {
  77924. Tags._AddTagTo(obj, tag);
  77925. });
  77926. };
  77927. /**
  77928. * @hidden
  77929. */
  77930. Tags._AddTagTo = function (obj, tag) {
  77931. tag = tag.trim();
  77932. if (tag === "" || tag === "true" || tag === "false") {
  77933. return;
  77934. }
  77935. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  77936. return;
  77937. }
  77938. Tags.EnableFor(obj);
  77939. obj._tags[tag] = true;
  77940. };
  77941. /**
  77942. * Removes specific tags from a specific object
  77943. * @param obj defines the object to use
  77944. * @param tagsString defines the tags to remove
  77945. */
  77946. Tags.RemoveTagsFrom = function (obj, tagsString) {
  77947. if (!Tags.HasTags(obj)) {
  77948. return;
  77949. }
  77950. var tags = tagsString.split(" ");
  77951. for (var t in tags) {
  77952. Tags._RemoveTagFrom(obj, tags[t]);
  77953. }
  77954. };
  77955. /**
  77956. * @hidden
  77957. */
  77958. Tags._RemoveTagFrom = function (obj, tag) {
  77959. delete obj._tags[tag];
  77960. };
  77961. /**
  77962. * Defines if tags hosted on an object match a given query
  77963. * @param obj defines the object to use
  77964. * @param tagsQuery defines the tag query
  77965. * @returns a boolean
  77966. */
  77967. Tags.MatchesQuery = function (obj, tagsQuery) {
  77968. if (tagsQuery === undefined) {
  77969. return true;
  77970. }
  77971. if (tagsQuery === "") {
  77972. return Tags.HasTags(obj);
  77973. }
  77974. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  77975. };
  77976. return Tags;
  77977. }());
  77978. BABYLON.Tags = Tags;
  77979. })(BABYLON || (BABYLON = {}));
  77980. //# sourceMappingURL=babylon.tags.js.map
  77981. var BABYLON;
  77982. (function (BABYLON) {
  77983. /**
  77984. * Class used to evalaute queries containing `and` and `or` operators
  77985. */
  77986. var AndOrNotEvaluator = /** @class */ (function () {
  77987. function AndOrNotEvaluator() {
  77988. }
  77989. /**
  77990. * Evaluate a query
  77991. * @param query defines the query to evaluate
  77992. * @param evaluateCallback defines the callback used to filter result
  77993. * @returns true if the query matches
  77994. */
  77995. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  77996. if (!query.match(/\([^\(\)]*\)/g)) {
  77997. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  77998. }
  77999. else {
  78000. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  78001. // remove parenthesis
  78002. r = r.slice(1, r.length - 1);
  78003. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  78004. });
  78005. }
  78006. if (query === "true") {
  78007. return true;
  78008. }
  78009. if (query === "false") {
  78010. return false;
  78011. }
  78012. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  78013. };
  78014. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  78015. evaluateCallback = evaluateCallback || (function (r) {
  78016. return r === "true" ? true : false;
  78017. });
  78018. var result;
  78019. var or = parenthesisContent.split("||");
  78020. for (var i in or) {
  78021. if (or.hasOwnProperty(i)) {
  78022. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  78023. var and = ori.split("&&");
  78024. if (and.length > 1) {
  78025. for (var j = 0; j < and.length; ++j) {
  78026. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  78027. if (andj !== "true" && andj !== "false") {
  78028. if (andj[0] === "!") {
  78029. result = !evaluateCallback(andj.substring(1));
  78030. }
  78031. else {
  78032. result = evaluateCallback(andj);
  78033. }
  78034. }
  78035. else {
  78036. result = andj === "true" ? true : false;
  78037. }
  78038. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  78039. ori = "false";
  78040. break;
  78041. }
  78042. }
  78043. }
  78044. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  78045. result = true;
  78046. break;
  78047. }
  78048. // result equals false (or undefined)
  78049. if (ori !== "true" && ori !== "false") {
  78050. if (ori[0] === "!") {
  78051. result = !evaluateCallback(ori.substring(1));
  78052. }
  78053. else {
  78054. result = evaluateCallback(ori);
  78055. }
  78056. }
  78057. else {
  78058. result = ori === "true" ? true : false;
  78059. }
  78060. }
  78061. }
  78062. // the whole parenthesis scope is replaced by 'true' or 'false'
  78063. return result ? "true" : "false";
  78064. };
  78065. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  78066. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  78067. // remove whitespaces
  78068. r = r.replace(/[\s]/g, function () { return ""; });
  78069. return r.length % 2 ? "!" : "";
  78070. });
  78071. booleanString = booleanString.trim();
  78072. if (booleanString === "!true") {
  78073. booleanString = "false";
  78074. }
  78075. else if (booleanString === "!false") {
  78076. booleanString = "true";
  78077. }
  78078. return booleanString;
  78079. };
  78080. return AndOrNotEvaluator;
  78081. }());
  78082. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  78083. })(BABYLON || (BABYLON = {}));
  78084. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  78085. var BABYLON;
  78086. (function (BABYLON) {
  78087. /**
  78088. * Class used to enable access to IndexedDB
  78089. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  78090. */
  78091. var Database = /** @class */ (function () {
  78092. /**
  78093. * Creates a new Database
  78094. * @param urlToScene defines the url to load the scene
  78095. * @param callbackManifestChecked defines the callback to use when manifest is checked
  78096. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  78097. */
  78098. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  78099. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  78100. var _this = this;
  78101. // Handling various flavors of prefixed version of IndexedDB
  78102. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  78103. this.callbackManifestChecked = callbackManifestChecked;
  78104. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  78105. this.db = null;
  78106. this._enableSceneOffline = false;
  78107. this._enableTexturesOffline = false;
  78108. this.manifestVersionFound = 0;
  78109. this.mustUpdateRessources = false;
  78110. this.hasReachedQuota = false;
  78111. if (!Database.IDBStorageEnabled) {
  78112. this.callbackManifestChecked(true);
  78113. }
  78114. else {
  78115. if (disableManifestCheck) {
  78116. this._enableSceneOffline = true;
  78117. this._enableTexturesOffline = true;
  78118. this.manifestVersionFound = 1;
  78119. BABYLON.Tools.SetImmediate(function () {
  78120. _this.callbackManifestChecked(true);
  78121. });
  78122. }
  78123. else {
  78124. this._checkManifestFile();
  78125. }
  78126. }
  78127. }
  78128. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  78129. /**
  78130. * Gets a boolean indicating if scene must be saved in the database
  78131. */
  78132. get: function () {
  78133. return this._enableSceneOffline;
  78134. },
  78135. enumerable: true,
  78136. configurable: true
  78137. });
  78138. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  78139. /**
  78140. * Gets a boolean indicating if textures must be saved in the database
  78141. */
  78142. get: function () {
  78143. return this._enableTexturesOffline;
  78144. },
  78145. enumerable: true,
  78146. configurable: true
  78147. });
  78148. Database.prototype._checkManifestFile = function () {
  78149. var _this = this;
  78150. var noManifestFile = function () {
  78151. _this._enableSceneOffline = false;
  78152. _this._enableTexturesOffline = false;
  78153. _this.callbackManifestChecked(false);
  78154. };
  78155. var timeStampUsed = false;
  78156. var manifestURL = this.currentSceneUrl + ".manifest";
  78157. var xhr = new XMLHttpRequest();
  78158. if (navigator.onLine) {
  78159. // Adding a timestamp to by-pass browsers' cache
  78160. timeStampUsed = true;
  78161. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  78162. }
  78163. xhr.open("GET", manifestURL, true);
  78164. xhr.addEventListener("load", function () {
  78165. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  78166. try {
  78167. var manifestFile = JSON.parse(xhr.response);
  78168. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  78169. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  78170. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  78171. _this.manifestVersionFound = manifestFile.version;
  78172. }
  78173. if (_this.callbackManifestChecked) {
  78174. _this.callbackManifestChecked(true);
  78175. }
  78176. }
  78177. catch (ex) {
  78178. noManifestFile();
  78179. }
  78180. }
  78181. else {
  78182. noManifestFile();
  78183. }
  78184. }, false);
  78185. xhr.addEventListener("error", function (event) {
  78186. if (timeStampUsed) {
  78187. timeStampUsed = false;
  78188. // Let's retry without the timeStamp
  78189. // It could fail when coupled with HTML5 Offline API
  78190. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  78191. xhr.open("GET", retryManifestURL, true);
  78192. xhr.send();
  78193. }
  78194. else {
  78195. noManifestFile();
  78196. }
  78197. }, false);
  78198. try {
  78199. xhr.send();
  78200. }
  78201. catch (ex) {
  78202. BABYLON.Tools.Error("Error on XHR send request.");
  78203. this.callbackManifestChecked(false);
  78204. }
  78205. };
  78206. /**
  78207. * Open the database and make it available
  78208. * @param successCallback defines the callback to call on success
  78209. * @param errorCallback defines the callback to call on error
  78210. */
  78211. Database.prototype.openAsync = function (successCallback, errorCallback) {
  78212. var _this = this;
  78213. var handleError = function () {
  78214. _this.isSupported = false;
  78215. if (errorCallback) {
  78216. errorCallback();
  78217. }
  78218. };
  78219. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  78220. // Your browser doesn't support IndexedDB
  78221. this.isSupported = false;
  78222. if (errorCallback) {
  78223. errorCallback();
  78224. }
  78225. }
  78226. else {
  78227. // If the DB hasn't been opened or created yet
  78228. if (!this.db) {
  78229. this.hasReachedQuota = false;
  78230. this.isSupported = true;
  78231. var request = this.idbFactory.open("babylonjs", 1);
  78232. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  78233. request.onerror = function (event) {
  78234. handleError();
  78235. };
  78236. // executes when a version change transaction cannot complete due to other active transactions
  78237. request.onblocked = function (event) {
  78238. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  78239. handleError();
  78240. };
  78241. // DB has been opened successfully
  78242. request.onsuccess = function (event) {
  78243. _this.db = request.result;
  78244. successCallback();
  78245. };
  78246. // Initialization of the DB. Creating Scenes & Textures stores
  78247. request.onupgradeneeded = function (event) {
  78248. _this.db = (event.target).result;
  78249. if (_this.db) {
  78250. try {
  78251. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  78252. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  78253. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  78254. }
  78255. catch (ex) {
  78256. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  78257. handleError();
  78258. }
  78259. }
  78260. };
  78261. }
  78262. // DB has already been created and opened
  78263. else {
  78264. if (successCallback) {
  78265. successCallback();
  78266. }
  78267. }
  78268. }
  78269. };
  78270. /**
  78271. * Loads an image from the database
  78272. * @param url defines the url to load from
  78273. * @param image defines the target DOM image
  78274. */
  78275. Database.prototype.loadImageFromDB = function (url, image) {
  78276. var _this = this;
  78277. var completeURL = Database._ReturnFullUrlLocation(url);
  78278. var saveAndLoadImage = function () {
  78279. if (!_this.hasReachedQuota && _this.db !== null) {
  78280. // the texture is not yet in the DB, let's try to save it
  78281. _this._saveImageIntoDBAsync(completeURL, image);
  78282. }
  78283. // If the texture is not in the DB and we've reached the DB quota limit
  78284. // let's load it directly from the web
  78285. else {
  78286. image.src = url;
  78287. }
  78288. };
  78289. if (!this.mustUpdateRessources) {
  78290. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  78291. }
  78292. // First time we're download the images or update requested in the manifest file by a version change
  78293. else {
  78294. saveAndLoadImage();
  78295. }
  78296. };
  78297. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  78298. if (this.isSupported && this.db !== null) {
  78299. var texture;
  78300. var transaction = this.db.transaction(["textures"]);
  78301. transaction.onabort = function (event) {
  78302. image.src = url;
  78303. };
  78304. transaction.oncomplete = function (event) {
  78305. var blobTextureURL;
  78306. if (texture) {
  78307. var URL = window.URL || window.webkitURL;
  78308. blobTextureURL = URL.createObjectURL(texture.data);
  78309. image.onerror = function () {
  78310. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  78311. image.src = url;
  78312. };
  78313. image.src = blobTextureURL;
  78314. }
  78315. else {
  78316. notInDBCallback();
  78317. }
  78318. };
  78319. var getRequest = transaction.objectStore("textures").get(url);
  78320. getRequest.onsuccess = function (event) {
  78321. texture = (event.target).result;
  78322. };
  78323. getRequest.onerror = function (event) {
  78324. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  78325. image.src = url;
  78326. };
  78327. }
  78328. else {
  78329. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78330. image.src = url;
  78331. }
  78332. };
  78333. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  78334. var _this = this;
  78335. if (this.isSupported) {
  78336. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  78337. var generateBlobUrl = function () {
  78338. var blobTextureURL;
  78339. if (blob) {
  78340. var URL = window.URL || window.webkitURL;
  78341. try {
  78342. blobTextureURL = URL.createObjectURL(blob);
  78343. }
  78344. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  78345. catch (ex) {
  78346. blobTextureURL = URL.createObjectURL(blob);
  78347. }
  78348. }
  78349. if (blobTextureURL) {
  78350. image.src = blobTextureURL;
  78351. }
  78352. };
  78353. if (Database.IsUASupportingBlobStorage) { // Create XHR
  78354. var xhr = new XMLHttpRequest(), blob;
  78355. xhr.open("GET", url, true);
  78356. xhr.responseType = "blob";
  78357. xhr.addEventListener("load", function () {
  78358. if (xhr.status === 200 && _this.db) {
  78359. // Blob as response (XHR2)
  78360. blob = xhr.response;
  78361. var transaction = _this.db.transaction(["textures"], "readwrite");
  78362. // the transaction could abort because of a QuotaExceededError error
  78363. transaction.onabort = function (event) {
  78364. try {
  78365. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78366. var srcElement = (event.srcElement || event.target);
  78367. var error = srcElement.error;
  78368. if (error && error.name === "QuotaExceededError") {
  78369. _this.hasReachedQuota = true;
  78370. }
  78371. }
  78372. catch (ex) { }
  78373. generateBlobUrl();
  78374. };
  78375. transaction.oncomplete = function (event) {
  78376. generateBlobUrl();
  78377. };
  78378. var newTexture = { textureUrl: url, data: blob };
  78379. try {
  78380. // Put the blob into the dabase
  78381. var addRequest = transaction.objectStore("textures").put(newTexture);
  78382. addRequest.onsuccess = function (event) {
  78383. };
  78384. addRequest.onerror = function (event) {
  78385. generateBlobUrl();
  78386. };
  78387. }
  78388. catch (ex) {
  78389. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  78390. if (ex.code === 25) {
  78391. Database.IsUASupportingBlobStorage = false;
  78392. }
  78393. image.src = url;
  78394. }
  78395. }
  78396. else {
  78397. image.src = url;
  78398. }
  78399. }, false);
  78400. xhr.addEventListener("error", function (event) {
  78401. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  78402. image.src = url;
  78403. }, false);
  78404. xhr.send();
  78405. }
  78406. else {
  78407. image.src = url;
  78408. }
  78409. }
  78410. else {
  78411. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78412. image.src = url;
  78413. }
  78414. };
  78415. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  78416. var _this = this;
  78417. var updateVersion = function () {
  78418. // the version is not yet in the DB or we need to update it
  78419. _this._saveVersionIntoDBAsync(url, versionLoaded);
  78420. };
  78421. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  78422. };
  78423. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  78424. var _this = this;
  78425. if (this.isSupported && this.db) {
  78426. var version;
  78427. try {
  78428. var transaction = this.db.transaction(["versions"]);
  78429. transaction.oncomplete = function (event) {
  78430. if (version) {
  78431. // If the version in the JSON file is different from the version in DB
  78432. if (_this.manifestVersionFound !== version.data) {
  78433. _this.mustUpdateRessources = true;
  78434. updateInDBCallback();
  78435. }
  78436. else {
  78437. callback(version.data);
  78438. }
  78439. }
  78440. // version was not found in DB
  78441. else {
  78442. _this.mustUpdateRessources = true;
  78443. updateInDBCallback();
  78444. }
  78445. };
  78446. transaction.onabort = function (event) {
  78447. callback(-1);
  78448. };
  78449. var getRequest = transaction.objectStore("versions").get(url);
  78450. getRequest.onsuccess = function (event) {
  78451. version = (event.target).result;
  78452. };
  78453. getRequest.onerror = function (event) {
  78454. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  78455. callback(-1);
  78456. };
  78457. }
  78458. catch (ex) {
  78459. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  78460. callback(-1);
  78461. }
  78462. }
  78463. else {
  78464. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78465. callback(-1);
  78466. }
  78467. };
  78468. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  78469. var _this = this;
  78470. if (this.isSupported && !this.hasReachedQuota && this.db) {
  78471. try {
  78472. // Open a transaction to the database
  78473. var transaction = this.db.transaction(["versions"], "readwrite");
  78474. // the transaction could abort because of a QuotaExceededError error
  78475. transaction.onabort = function (event) {
  78476. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78477. var error = event.srcElement['error'];
  78478. if (error && error.name === "QuotaExceededError") {
  78479. _this.hasReachedQuota = true;
  78480. }
  78481. }
  78482. catch (ex) { }
  78483. callback(-1);
  78484. };
  78485. transaction.oncomplete = function (event) {
  78486. callback(_this.manifestVersionFound);
  78487. };
  78488. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  78489. // Put the scene into the database
  78490. var addRequest = transaction.objectStore("versions").put(newVersion);
  78491. addRequest.onsuccess = function (event) {
  78492. };
  78493. addRequest.onerror = function (event) {
  78494. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  78495. };
  78496. }
  78497. catch (ex) {
  78498. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  78499. callback(-1);
  78500. }
  78501. }
  78502. else {
  78503. callback(-1);
  78504. }
  78505. };
  78506. /**
  78507. * Loads a file from database
  78508. * @param url defines the URL to load from
  78509. * @param sceneLoaded defines a callback to call on success
  78510. * @param progressCallBack defines a callback to call when progress changed
  78511. * @param errorCallback defines a callback to call on error
  78512. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  78513. */
  78514. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  78515. var _this = this;
  78516. var completeUrl = Database._ReturnFullUrlLocation(url);
  78517. var saveAndLoadFile = function () {
  78518. // the scene is not yet in the DB, let's try to save it
  78519. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78520. };
  78521. this._checkVersionFromDB(completeUrl, function (version) {
  78522. if (version !== -1) {
  78523. if (!_this.mustUpdateRessources) {
  78524. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  78525. }
  78526. else {
  78527. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78528. }
  78529. }
  78530. else {
  78531. if (errorCallback) {
  78532. errorCallback();
  78533. }
  78534. }
  78535. });
  78536. };
  78537. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  78538. if (this.isSupported && this.db) {
  78539. var targetStore;
  78540. if (url.indexOf(".babylon") !== -1) {
  78541. targetStore = "scenes";
  78542. }
  78543. else {
  78544. targetStore = "textures";
  78545. }
  78546. var file;
  78547. var transaction = this.db.transaction([targetStore]);
  78548. transaction.oncomplete = function (event) {
  78549. if (file) {
  78550. callback(file.data);
  78551. }
  78552. // file was not found in DB
  78553. else {
  78554. notInDBCallback();
  78555. }
  78556. };
  78557. transaction.onabort = function (event) {
  78558. notInDBCallback();
  78559. };
  78560. var getRequest = transaction.objectStore(targetStore).get(url);
  78561. getRequest.onsuccess = function (event) {
  78562. file = (event.target).result;
  78563. };
  78564. getRequest.onerror = function (event) {
  78565. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  78566. notInDBCallback();
  78567. };
  78568. }
  78569. else {
  78570. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78571. callback();
  78572. }
  78573. };
  78574. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  78575. var _this = this;
  78576. if (this.isSupported) {
  78577. var targetStore;
  78578. if (url.indexOf(".babylon") !== -1) {
  78579. targetStore = "scenes";
  78580. }
  78581. else {
  78582. targetStore = "textures";
  78583. }
  78584. // Create XHR
  78585. var xhr = new XMLHttpRequest();
  78586. var fileData;
  78587. xhr.open("GET", url + "?" + Date.now(), true);
  78588. if (useArrayBuffer) {
  78589. xhr.responseType = "arraybuffer";
  78590. }
  78591. if (progressCallback) {
  78592. xhr.onprogress = progressCallback;
  78593. }
  78594. xhr.addEventListener("load", function () {
  78595. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  78596. // Blob as response (XHR2)
  78597. //fileData = xhr.responseText;
  78598. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  78599. if (!_this.hasReachedQuota && _this.db) {
  78600. // Open a transaction to the database
  78601. var transaction = _this.db.transaction([targetStore], "readwrite");
  78602. // the transaction could abort because of a QuotaExceededError error
  78603. transaction.onabort = function (event) {
  78604. try {
  78605. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78606. var error = event.srcElement['error'];
  78607. if (error && error.name === "QuotaExceededError") {
  78608. _this.hasReachedQuota = true;
  78609. }
  78610. }
  78611. catch (ex) { }
  78612. callback(fileData);
  78613. };
  78614. transaction.oncomplete = function (event) {
  78615. callback(fileData);
  78616. };
  78617. var newFile;
  78618. if (targetStore === "scenes") {
  78619. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  78620. }
  78621. else {
  78622. newFile = { textureUrl: url, data: fileData };
  78623. }
  78624. try {
  78625. // Put the scene into the database
  78626. var addRequest = transaction.objectStore(targetStore).put(newFile);
  78627. addRequest.onsuccess = function (event) {
  78628. };
  78629. addRequest.onerror = function (event) {
  78630. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  78631. };
  78632. }
  78633. catch (ex) {
  78634. callback(fileData);
  78635. }
  78636. }
  78637. else {
  78638. callback(fileData);
  78639. }
  78640. }
  78641. else {
  78642. if (xhr.status >= 400 && errorCallback) {
  78643. errorCallback(xhr);
  78644. }
  78645. else {
  78646. callback();
  78647. }
  78648. }
  78649. }, false);
  78650. xhr.addEventListener("error", function (event) {
  78651. BABYLON.Tools.Error("error on XHR request.");
  78652. callback();
  78653. }, false);
  78654. xhr.send();
  78655. }
  78656. else {
  78657. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78658. callback();
  78659. }
  78660. };
  78661. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  78662. Database.IsUASupportingBlobStorage = true;
  78663. /** Gets a boolean indicating if Database storate is enabled */
  78664. Database.IDBStorageEnabled = true;
  78665. Database._ParseURL = function (url) {
  78666. var a = document.createElement('a');
  78667. a.href = url;
  78668. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  78669. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  78670. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  78671. return absLocation;
  78672. };
  78673. Database._ReturnFullUrlLocation = function (url) {
  78674. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  78675. return (Database._ParseURL(window.location.href) + url);
  78676. }
  78677. else {
  78678. return url;
  78679. }
  78680. };
  78681. return Database;
  78682. }());
  78683. BABYLON.Database = Database;
  78684. })(BABYLON || (BABYLON = {}));
  78685. //# sourceMappingURL=babylon.database.js.map
  78686. var BABYLON;
  78687. (function (BABYLON) {
  78688. /**
  78689. * This represents all the required information to add a fresnel effect on a material:
  78690. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  78691. */
  78692. var FresnelParameters = /** @class */ (function () {
  78693. function FresnelParameters() {
  78694. this._isEnabled = true;
  78695. /**
  78696. * Define the color used on edges (grazing angle)
  78697. */
  78698. this.leftColor = BABYLON.Color3.White();
  78699. /**
  78700. * Define the color used on center
  78701. */
  78702. this.rightColor = BABYLON.Color3.Black();
  78703. /**
  78704. * Define bias applied to computed fresnel term
  78705. */
  78706. this.bias = 0;
  78707. /**
  78708. * Defined the power exponent applied to fresnel term
  78709. */
  78710. this.power = 1;
  78711. }
  78712. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  78713. /**
  78714. * Define if the fresnel effect is enable or not.
  78715. */
  78716. get: function () {
  78717. return this._isEnabled;
  78718. },
  78719. set: function (value) {
  78720. if (this._isEnabled === value) {
  78721. return;
  78722. }
  78723. this._isEnabled = value;
  78724. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  78725. },
  78726. enumerable: true,
  78727. configurable: true
  78728. });
  78729. /**
  78730. * Clones the current fresnel and its valuues
  78731. * @returns a clone fresnel configuration
  78732. */
  78733. FresnelParameters.prototype.clone = function () {
  78734. var newFresnelParameters = new FresnelParameters();
  78735. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  78736. return newFresnelParameters;
  78737. };
  78738. /**
  78739. * Serializes the current fresnel parameters to a JSON representation.
  78740. * @return the JSON serialization
  78741. */
  78742. FresnelParameters.prototype.serialize = function () {
  78743. var serializationObject = {};
  78744. serializationObject.isEnabled = this.isEnabled;
  78745. serializationObject.leftColor = this.leftColor.asArray();
  78746. serializationObject.rightColor = this.rightColor.asArray();
  78747. serializationObject.bias = this.bias;
  78748. serializationObject.power = this.power;
  78749. return serializationObject;
  78750. };
  78751. /**
  78752. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  78753. * @param parsedFresnelParameters Define the JSON representation
  78754. * @returns the parsed parameters
  78755. */
  78756. FresnelParameters.Parse = function (parsedFresnelParameters) {
  78757. var fresnelParameters = new FresnelParameters();
  78758. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  78759. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  78760. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  78761. fresnelParameters.bias = parsedFresnelParameters.bias;
  78762. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  78763. return fresnelParameters;
  78764. };
  78765. return FresnelParameters;
  78766. }());
  78767. BABYLON.FresnelParameters = FresnelParameters;
  78768. })(BABYLON || (BABYLON = {}));
  78769. //# sourceMappingURL=babylon.fresnelParameters.js.map
  78770. var BABYLON;
  78771. (function (BABYLON) {
  78772. /**
  78773. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78774. * separate meshes. This can be use to improve performances.
  78775. * @see http://doc.babylonjs.com/how_to/multi_materials
  78776. */
  78777. var MultiMaterial = /** @class */ (function (_super) {
  78778. __extends(MultiMaterial, _super);
  78779. /**
  78780. * Instantiates a new Multi Material
  78781. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78782. * separate meshes. This can be use to improve performances.
  78783. * @see http://doc.babylonjs.com/how_to/multi_materials
  78784. * @param name Define the name in the scene
  78785. * @param scene Define the scene the material belongs to
  78786. */
  78787. function MultiMaterial(name, scene) {
  78788. var _this = _super.call(this, name, scene, true) || this;
  78789. scene.multiMaterials.push(_this);
  78790. _this.subMaterials = new Array();
  78791. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  78792. return _this;
  78793. }
  78794. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  78795. /**
  78796. * Gets or Sets the list of Materials used within the multi material.
  78797. * They need to be ordered according to the submeshes order in the associated mesh
  78798. */
  78799. get: function () {
  78800. return this._subMaterials;
  78801. },
  78802. set: function (value) {
  78803. this._subMaterials = value;
  78804. this._hookArray(value);
  78805. },
  78806. enumerable: true,
  78807. configurable: true
  78808. });
  78809. MultiMaterial.prototype._hookArray = function (array) {
  78810. var _this = this;
  78811. var oldPush = array.push;
  78812. array.push = function () {
  78813. var items = [];
  78814. for (var _i = 0; _i < arguments.length; _i++) {
  78815. items[_i] = arguments[_i];
  78816. }
  78817. var result = oldPush.apply(array, items);
  78818. _this._markAllSubMeshesAsTexturesDirty();
  78819. return result;
  78820. };
  78821. var oldSplice = array.splice;
  78822. array.splice = function (index, deleteCount) {
  78823. var deleted = oldSplice.apply(array, [index, deleteCount]);
  78824. _this._markAllSubMeshesAsTexturesDirty();
  78825. return deleted;
  78826. };
  78827. };
  78828. /**
  78829. * Get one of the submaterial by its index in the submaterials array
  78830. * @param index The index to look the sub material at
  78831. * @returns The Material if the index has been defined
  78832. */
  78833. MultiMaterial.prototype.getSubMaterial = function (index) {
  78834. if (index < 0 || index >= this.subMaterials.length) {
  78835. return this.getScene().defaultMaterial;
  78836. }
  78837. return this.subMaterials[index];
  78838. };
  78839. /**
  78840. * Get the list of active textures for the whole sub materials list.
  78841. * @returns All the textures that will be used during the rendering
  78842. */
  78843. MultiMaterial.prototype.getActiveTextures = function () {
  78844. var _a;
  78845. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  78846. if (subMaterial) {
  78847. return subMaterial.getActiveTextures();
  78848. }
  78849. else {
  78850. return [];
  78851. }
  78852. }));
  78853. };
  78854. /**
  78855. * Gets the current class name of the material e.g. "MultiMaterial"
  78856. * Mainly use in serialization.
  78857. * @returns the class name
  78858. */
  78859. MultiMaterial.prototype.getClassName = function () {
  78860. return "MultiMaterial";
  78861. };
  78862. /**
  78863. * Checks if the material is ready to render the requested sub mesh
  78864. * @param mesh Define the mesh the submesh belongs to
  78865. * @param subMesh Define the sub mesh to look readyness for
  78866. * @param useInstances Define whether or not the material is used with instances
  78867. * @returns true if ready, otherwise false
  78868. */
  78869. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78870. for (var index = 0; index < this.subMaterials.length; index++) {
  78871. var subMaterial = this.subMaterials[index];
  78872. if (subMaterial) {
  78873. if (subMaterial.storeEffectOnSubMeshes) {
  78874. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  78875. return false;
  78876. }
  78877. continue;
  78878. }
  78879. if (!subMaterial.isReady(mesh)) {
  78880. return false;
  78881. }
  78882. }
  78883. }
  78884. return true;
  78885. };
  78886. /**
  78887. * Clones the current material and its related sub materials
  78888. * @param name Define the name of the newly cloned material
  78889. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  78890. * @returns the cloned material
  78891. */
  78892. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  78893. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  78894. for (var index = 0; index < this.subMaterials.length; index++) {
  78895. var subMaterial = null;
  78896. var current = this.subMaterials[index];
  78897. if (cloneChildren && current) {
  78898. subMaterial = current.clone(name + "-" + current.name);
  78899. }
  78900. else {
  78901. subMaterial = this.subMaterials[index];
  78902. }
  78903. newMultiMaterial.subMaterials.push(subMaterial);
  78904. }
  78905. return newMultiMaterial;
  78906. };
  78907. /**
  78908. * Serializes the materials into a JSON representation.
  78909. * @returns the JSON representation
  78910. */
  78911. MultiMaterial.prototype.serialize = function () {
  78912. var serializationObject = {};
  78913. serializationObject.name = this.name;
  78914. serializationObject.id = this.id;
  78915. if (BABYLON.Tags) {
  78916. serializationObject.tags = BABYLON.Tags.GetTags(this);
  78917. }
  78918. serializationObject.materials = [];
  78919. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  78920. var subMat = this.subMaterials[matIndex];
  78921. if (subMat) {
  78922. serializationObject.materials.push(subMat.id);
  78923. }
  78924. else {
  78925. serializationObject.materials.push(null);
  78926. }
  78927. }
  78928. return serializationObject;
  78929. };
  78930. /**
  78931. * Dispose the material and release its associated resources
  78932. * @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)
  78933. * @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)
  78934. */
  78935. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  78936. var scene = this.getScene();
  78937. if (!scene) {
  78938. return;
  78939. }
  78940. var index = scene.multiMaterials.indexOf(this);
  78941. if (index >= 0) {
  78942. scene.multiMaterials.splice(index, 1);
  78943. }
  78944. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  78945. };
  78946. return MultiMaterial;
  78947. }(BABYLON.Material));
  78948. BABYLON.MultiMaterial = MultiMaterial;
  78949. })(BABYLON || (BABYLON = {}));
  78950. //# sourceMappingURL=babylon.multiMaterial.js.map
  78951. var BABYLON;
  78952. (function (BABYLON) {
  78953. /**
  78954. * Manage the touch inputs to control the movement of a free camera.
  78955. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78956. */
  78957. var FreeCameraTouchInput = /** @class */ (function () {
  78958. function FreeCameraTouchInput() {
  78959. /**
  78960. * Defines the touch sensibility for rotation.
  78961. * The higher the faster.
  78962. */
  78963. this.touchAngularSensibility = 200000.0;
  78964. /**
  78965. * Defines the touch sensibility for move.
  78966. * The higher the faster.
  78967. */
  78968. this.touchMoveSensibility = 250.0;
  78969. this._offsetX = null;
  78970. this._offsetY = null;
  78971. this._pointerPressed = new Array();
  78972. }
  78973. /**
  78974. * Attach the input controls to a specific dom element to get the input from.
  78975. * @param element Defines the element the controls should be listened from
  78976. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78977. */
  78978. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  78979. var _this = this;
  78980. var previousPosition = null;
  78981. if (this._pointerInput === undefined) {
  78982. this._onLostFocus = function (evt) {
  78983. _this._offsetX = null;
  78984. _this._offsetY = null;
  78985. };
  78986. this._pointerInput = function (p, s) {
  78987. var evt = p.event;
  78988. if (evt.pointerType === "mouse") {
  78989. return;
  78990. }
  78991. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78992. if (!noPreventDefault) {
  78993. evt.preventDefault();
  78994. }
  78995. _this._pointerPressed.push(evt.pointerId);
  78996. if (_this._pointerPressed.length !== 1) {
  78997. return;
  78998. }
  78999. previousPosition = {
  79000. x: evt.clientX,
  79001. y: evt.clientY
  79002. };
  79003. }
  79004. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  79005. if (!noPreventDefault) {
  79006. evt.preventDefault();
  79007. }
  79008. var index = _this._pointerPressed.indexOf(evt.pointerId);
  79009. if (index === -1) {
  79010. return;
  79011. }
  79012. _this._pointerPressed.splice(index, 1);
  79013. if (index != 0) {
  79014. return;
  79015. }
  79016. previousPosition = null;
  79017. _this._offsetX = null;
  79018. _this._offsetY = null;
  79019. }
  79020. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  79021. if (!noPreventDefault) {
  79022. evt.preventDefault();
  79023. }
  79024. if (!previousPosition) {
  79025. return;
  79026. }
  79027. var index = _this._pointerPressed.indexOf(evt.pointerId);
  79028. if (index != 0) {
  79029. return;
  79030. }
  79031. _this._offsetX = evt.clientX - previousPosition.x;
  79032. _this._offsetY = -(evt.clientY - previousPosition.y);
  79033. }
  79034. };
  79035. }
  79036. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  79037. if (this._onLostFocus) {
  79038. element.addEventListener("blur", this._onLostFocus);
  79039. }
  79040. };
  79041. /**
  79042. * Detach the current controls from the specified dom element.
  79043. * @param element Defines the element to stop listening the inputs from
  79044. */
  79045. FreeCameraTouchInput.prototype.detachControl = function (element) {
  79046. if (this._pointerInput && element) {
  79047. if (this._observer) {
  79048. this.camera.getScene().onPointerObservable.remove(this._observer);
  79049. this._observer = null;
  79050. }
  79051. if (this._onLostFocus) {
  79052. element.removeEventListener("blur", this._onLostFocus);
  79053. this._onLostFocus = null;
  79054. }
  79055. this._pointerPressed = [];
  79056. this._offsetX = null;
  79057. this._offsetY = null;
  79058. }
  79059. };
  79060. /**
  79061. * Update the current camera state depending on the inputs that have been used this frame.
  79062. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79063. */
  79064. FreeCameraTouchInput.prototype.checkInputs = function () {
  79065. if (this._offsetX && this._offsetY) {
  79066. var camera = this.camera;
  79067. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  79068. if (this._pointerPressed.length > 1) {
  79069. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  79070. }
  79071. else {
  79072. var speed = camera._computeLocalCameraSpeed();
  79073. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  79074. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  79075. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  79076. }
  79077. }
  79078. };
  79079. /**
  79080. * Gets the class name of the current intput.
  79081. * @returns the class name
  79082. */
  79083. FreeCameraTouchInput.prototype.getClassName = function () {
  79084. return "FreeCameraTouchInput";
  79085. };
  79086. /**
  79087. * Get the friendly name associated with the input class.
  79088. * @returns the input friendly name
  79089. */
  79090. FreeCameraTouchInput.prototype.getSimpleName = function () {
  79091. return "touch";
  79092. };
  79093. __decorate([
  79094. BABYLON.serialize()
  79095. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  79096. __decorate([
  79097. BABYLON.serialize()
  79098. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  79099. return FreeCameraTouchInput;
  79100. }());
  79101. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  79102. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  79103. })(BABYLON || (BABYLON = {}));
  79104. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  79105. var BABYLON;
  79106. (function (BABYLON) {
  79107. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  79108. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  79109. });
  79110. /**
  79111. * This represents a FPS type of camera controlled by touch.
  79112. * This is like a universal camera minus the Gamepad controls.
  79113. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79114. */
  79115. var TouchCamera = /** @class */ (function (_super) {
  79116. __extends(TouchCamera, _super);
  79117. /**
  79118. * Instantiates a new touch camera.
  79119. * This represents a FPS type of camera controlled by touch.
  79120. * This is like a universal camera minus the Gamepad controls.
  79121. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79122. * @param name Define the name of the camera in the scene
  79123. * @param position Define the start position of the camera in the scene
  79124. * @param scene Define the scene the camera belongs to
  79125. */
  79126. function TouchCamera(name, position, scene) {
  79127. var _this = _super.call(this, name, position, scene) || this;
  79128. _this.inputs.addTouch();
  79129. _this._setupInputs();
  79130. return _this;
  79131. }
  79132. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  79133. /**
  79134. * Defines the touch sensibility for rotation.
  79135. * The higher the faster.
  79136. */
  79137. get: function () {
  79138. var touch = this.inputs.attached["touch"];
  79139. if (touch) {
  79140. return touch.touchAngularSensibility;
  79141. }
  79142. return 0;
  79143. },
  79144. set: function (value) {
  79145. var touch = this.inputs.attached["touch"];
  79146. if (touch) {
  79147. touch.touchAngularSensibility = value;
  79148. }
  79149. },
  79150. enumerable: true,
  79151. configurable: true
  79152. });
  79153. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  79154. /**
  79155. * Defines the touch sensibility for move.
  79156. * The higher the faster.
  79157. */
  79158. get: function () {
  79159. var touch = this.inputs.attached["touch"];
  79160. if (touch) {
  79161. return touch.touchMoveSensibility;
  79162. }
  79163. return 0;
  79164. },
  79165. set: function (value) {
  79166. var touch = this.inputs.attached["touch"];
  79167. if (touch) {
  79168. touch.touchMoveSensibility = value;
  79169. }
  79170. },
  79171. enumerable: true,
  79172. configurable: true
  79173. });
  79174. /**
  79175. * Gets the current object class name.
  79176. * @return the class name
  79177. */
  79178. TouchCamera.prototype.getClassName = function () {
  79179. return "TouchCamera";
  79180. };
  79181. /** @hidden */
  79182. TouchCamera.prototype._setupInputs = function () {
  79183. var mouse = this.inputs.attached["mouse"];
  79184. if (mouse) {
  79185. mouse.touchEnabled = false;
  79186. }
  79187. };
  79188. return TouchCamera;
  79189. }(BABYLON.FreeCamera));
  79190. BABYLON.TouchCamera = TouchCamera;
  79191. })(BABYLON || (BABYLON = {}));
  79192. //# sourceMappingURL=babylon.touchCamera.js.map
  79193. var BABYLON;
  79194. (function (BABYLON) {
  79195. /**
  79196. * 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.
  79197. * This is the base class of any Procedural texture and contains most of the shareable code.
  79198. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  79199. */
  79200. var ProceduralTexture = /** @class */ (function (_super) {
  79201. __extends(ProceduralTexture, _super);
  79202. /**
  79203. * Instantiates a new procedural texture.
  79204. * 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.
  79205. * This is the base class of any Procedural texture and contains most of the shareable code.
  79206. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  79207. * @param name Define the name of the texture
  79208. * @param size Define the size of the texture to create
  79209. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  79210. * @param scene Define the scene the texture belongs to
  79211. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79212. * @param generateMipMaps Define if the texture should creates mip maps or not
  79213. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  79214. */
  79215. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  79216. if (fallbackTexture === void 0) { fallbackTexture = null; }
  79217. if (generateMipMaps === void 0) { generateMipMaps = true; }
  79218. if (isCube === void 0) { isCube = false; }
  79219. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  79220. _this.isCube = isCube;
  79221. /**
  79222. * Define if the texture is enabled or not (disabled texture will not render)
  79223. */
  79224. _this.isEnabled = true;
  79225. /**
  79226. * Event raised when the texture is generated
  79227. */
  79228. _this.onGeneratedObservable = new BABYLON.Observable();
  79229. /** @hidden */
  79230. _this._textures = {};
  79231. _this._currentRefreshId = -1;
  79232. _this._refreshRate = 1;
  79233. _this._vertexBuffers = {};
  79234. _this._uniforms = new Array();
  79235. _this._samplers = new Array();
  79236. _this._floats = {};
  79237. _this._ints = {};
  79238. _this._floatsArrays = {};
  79239. _this._colors3 = {};
  79240. _this._colors4 = {};
  79241. _this._vectors2 = {};
  79242. _this._vectors3 = {};
  79243. _this._matrices = {};
  79244. _this._fallbackTextureUsed = false;
  79245. _this._cachedDefines = "";
  79246. _this._contentUpdateId = -1;
  79247. scene = _this.getScene();
  79248. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  79249. if (!component) {
  79250. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  79251. scene._addComponent(component);
  79252. }
  79253. scene.proceduralTextures.push(_this);
  79254. _this._engine = scene.getEngine();
  79255. _this.name = name;
  79256. _this.isRenderTarget = true;
  79257. _this._size = size;
  79258. _this._generateMipMaps = generateMipMaps;
  79259. _this.setFragment(fragment);
  79260. _this._fallbackTexture = fallbackTexture;
  79261. if (isCube) {
  79262. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  79263. _this.setFloat("face", 0);
  79264. }
  79265. else {
  79266. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  79267. }
  79268. // VBO
  79269. var vertices = [];
  79270. vertices.push(1, 1);
  79271. vertices.push(-1, 1);
  79272. vertices.push(-1, -1);
  79273. vertices.push(1, -1);
  79274. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79275. _this._createIndexBuffer();
  79276. return _this;
  79277. }
  79278. /**
  79279. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  79280. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  79281. */
  79282. ProceduralTexture.prototype.getContent = function () {
  79283. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  79284. return this._contentData;
  79285. }
  79286. this._contentData = this.readPixels(0, 0, this._contentData);
  79287. this._contentUpdateId = this._currentRefreshId;
  79288. return this._contentData;
  79289. };
  79290. ProceduralTexture.prototype._createIndexBuffer = function () {
  79291. var engine = this._engine;
  79292. // Indices
  79293. var indices = [];
  79294. indices.push(0);
  79295. indices.push(1);
  79296. indices.push(2);
  79297. indices.push(0);
  79298. indices.push(2);
  79299. indices.push(3);
  79300. this._indexBuffer = engine.createIndexBuffer(indices);
  79301. };
  79302. /** @hidden */
  79303. ProceduralTexture.prototype._rebuild = function () {
  79304. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79305. if (vb) {
  79306. vb._rebuild();
  79307. }
  79308. this._createIndexBuffer();
  79309. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  79310. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  79311. }
  79312. };
  79313. /**
  79314. * Resets the texture in order to recreate its associated resources.
  79315. * This can be called in case of context loss
  79316. */
  79317. ProceduralTexture.prototype.reset = function () {
  79318. if (this._effect === undefined) {
  79319. return;
  79320. }
  79321. var engine = this._engine;
  79322. engine._releaseEffect(this._effect);
  79323. };
  79324. ProceduralTexture.prototype._getDefines = function () {
  79325. return "";
  79326. };
  79327. /**
  79328. * Is the texture ready to be used ? (rendered at least once)
  79329. * @returns true if ready, otherwise, false.
  79330. */
  79331. ProceduralTexture.prototype.isReady = function () {
  79332. var _this = this;
  79333. var engine = this._engine;
  79334. var shaders;
  79335. if (!this._fragment) {
  79336. return false;
  79337. }
  79338. if (this._fallbackTextureUsed) {
  79339. return true;
  79340. }
  79341. var defines = this._getDefines();
  79342. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  79343. return true;
  79344. }
  79345. if (this._fragment.fragmentElement !== undefined) {
  79346. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  79347. }
  79348. else {
  79349. shaders = { vertex: "procedural", fragment: this._fragment };
  79350. }
  79351. this._cachedDefines = defines;
  79352. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  79353. _this.releaseInternalTexture();
  79354. if (_this._fallbackTexture) {
  79355. _this._texture = _this._fallbackTexture._texture;
  79356. if (_this._texture) {
  79357. _this._texture.incrementReferences();
  79358. }
  79359. }
  79360. _this._fallbackTextureUsed = true;
  79361. });
  79362. return this._effect.isReady();
  79363. };
  79364. /**
  79365. * Resets the refresh counter of the texture and start bak from scratch.
  79366. * Could be usefull to regenerate the texture if it is setup to render only once.
  79367. */
  79368. ProceduralTexture.prototype.resetRefreshCounter = function () {
  79369. this._currentRefreshId = -1;
  79370. };
  79371. /**
  79372. * Set the fragment shader to use in order to render the texture.
  79373. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  79374. */
  79375. ProceduralTexture.prototype.setFragment = function (fragment) {
  79376. this._fragment = fragment;
  79377. };
  79378. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  79379. /**
  79380. * Define the refresh rate of the texture or the rendering frequency.
  79381. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  79382. */
  79383. get: function () {
  79384. return this._refreshRate;
  79385. },
  79386. set: function (value) {
  79387. this._refreshRate = value;
  79388. this.resetRefreshCounter();
  79389. },
  79390. enumerable: true,
  79391. configurable: true
  79392. });
  79393. /** @hidden */
  79394. ProceduralTexture.prototype._shouldRender = function () {
  79395. if (!this.isEnabled || !this.isReady() || !this._texture) {
  79396. if (this._texture) {
  79397. this._texture.isReady = false;
  79398. }
  79399. return false;
  79400. }
  79401. if (this._fallbackTextureUsed) {
  79402. return false;
  79403. }
  79404. if (this._currentRefreshId === -1) { // At least render once
  79405. this._currentRefreshId = 1;
  79406. return true;
  79407. }
  79408. if (this.refreshRate === this._currentRefreshId) {
  79409. this._currentRefreshId = 1;
  79410. return true;
  79411. }
  79412. this._currentRefreshId++;
  79413. return false;
  79414. };
  79415. /**
  79416. * Get the size the texture is rendering at.
  79417. * @returns the size (texture is always squared)
  79418. */
  79419. ProceduralTexture.prototype.getRenderSize = function () {
  79420. return this._size;
  79421. };
  79422. /**
  79423. * Resize the texture to new value.
  79424. * @param size Define the new size the texture should have
  79425. * @param generateMipMaps Define whether the new texture should create mip maps
  79426. */
  79427. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  79428. if (this._fallbackTextureUsed) {
  79429. return;
  79430. }
  79431. this.releaseInternalTexture();
  79432. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  79433. // Update properties
  79434. this._size = size;
  79435. this._generateMipMaps = generateMipMaps;
  79436. };
  79437. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  79438. if (this._uniforms.indexOf(uniformName) === -1) {
  79439. this._uniforms.push(uniformName);
  79440. }
  79441. };
  79442. /**
  79443. * Set a texture in the shader program used to render.
  79444. * @param name Define the name of the uniform samplers as defined in the shader
  79445. * @param texture Define the texture to bind to this sampler
  79446. * @return the texture itself allowing "fluent" like uniform updates
  79447. */
  79448. ProceduralTexture.prototype.setTexture = function (name, texture) {
  79449. if (this._samplers.indexOf(name) === -1) {
  79450. this._samplers.push(name);
  79451. }
  79452. this._textures[name] = texture;
  79453. return this;
  79454. };
  79455. /**
  79456. * Set a float in the shader.
  79457. * @param name Define the name of the uniform as defined in the shader
  79458. * @param value Define the value to give to the uniform
  79459. * @return the texture itself allowing "fluent" like uniform updates
  79460. */
  79461. ProceduralTexture.prototype.setFloat = function (name, value) {
  79462. this._checkUniform(name);
  79463. this._floats[name] = value;
  79464. return this;
  79465. };
  79466. /**
  79467. * Set a int in the shader.
  79468. * @param name Define the name of the uniform as defined in the shader
  79469. * @param value Define the value to give to the uniform
  79470. * @return the texture itself allowing "fluent" like uniform updates
  79471. */
  79472. ProceduralTexture.prototype.setInt = function (name, value) {
  79473. this._checkUniform(name);
  79474. this._ints[name] = value;
  79475. return this;
  79476. };
  79477. /**
  79478. * Set an array of floats in the shader.
  79479. * @param name Define the name of the uniform as defined in the shader
  79480. * @param value Define the value to give to the uniform
  79481. * @return the texture itself allowing "fluent" like uniform updates
  79482. */
  79483. ProceduralTexture.prototype.setFloats = function (name, value) {
  79484. this._checkUniform(name);
  79485. this._floatsArrays[name] = value;
  79486. return this;
  79487. };
  79488. /**
  79489. * Set a vec3 in the shader from a Color3.
  79490. * @param name Define the name of the uniform as defined in the shader
  79491. * @param value Define the value to give to the uniform
  79492. * @return the texture itself allowing "fluent" like uniform updates
  79493. */
  79494. ProceduralTexture.prototype.setColor3 = function (name, value) {
  79495. this._checkUniform(name);
  79496. this._colors3[name] = value;
  79497. return this;
  79498. };
  79499. /**
  79500. * Set a vec4 in the shader from a Color4.
  79501. * @param name Define the name of the uniform as defined in the shader
  79502. * @param value Define the value to give to the uniform
  79503. * @return the texture itself allowing "fluent" like uniform updates
  79504. */
  79505. ProceduralTexture.prototype.setColor4 = function (name, value) {
  79506. this._checkUniform(name);
  79507. this._colors4[name] = value;
  79508. return this;
  79509. };
  79510. /**
  79511. * Set a vec2 in the shader from a Vector2.
  79512. * @param name Define the name of the uniform as defined in the shader
  79513. * @param value Define the value to give to the uniform
  79514. * @return the texture itself allowing "fluent" like uniform updates
  79515. */
  79516. ProceduralTexture.prototype.setVector2 = function (name, value) {
  79517. this._checkUniform(name);
  79518. this._vectors2[name] = value;
  79519. return this;
  79520. };
  79521. /**
  79522. * Set a vec3 in the shader from a Vector3.
  79523. * @param name Define the name of the uniform as defined in the shader
  79524. * @param value Define the value to give to the uniform
  79525. * @return the texture itself allowing "fluent" like uniform updates
  79526. */
  79527. ProceduralTexture.prototype.setVector3 = function (name, value) {
  79528. this._checkUniform(name);
  79529. this._vectors3[name] = value;
  79530. return this;
  79531. };
  79532. /**
  79533. * Set a mat4 in the shader from a MAtrix.
  79534. * @param name Define the name of the uniform as defined in the shader
  79535. * @param value Define the value to give to the uniform
  79536. * @return the texture itself allowing "fluent" like uniform updates
  79537. */
  79538. ProceduralTexture.prototype.setMatrix = function (name, value) {
  79539. this._checkUniform(name);
  79540. this._matrices[name] = value;
  79541. return this;
  79542. };
  79543. /**
  79544. * Render the texture to its associated render target.
  79545. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79546. */
  79547. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79548. var scene = this.getScene();
  79549. if (!scene) {
  79550. return;
  79551. }
  79552. var engine = this._engine;
  79553. // Render
  79554. engine.enableEffect(this._effect);
  79555. engine.setState(false);
  79556. // Texture
  79557. for (var name in this._textures) {
  79558. this._effect.setTexture(name, this._textures[name]);
  79559. }
  79560. // Float
  79561. for (name in this._ints) {
  79562. this._effect.setInt(name, this._ints[name]);
  79563. }
  79564. // Float
  79565. for (name in this._floats) {
  79566. this._effect.setFloat(name, this._floats[name]);
  79567. }
  79568. // Floats
  79569. for (name in this._floatsArrays) {
  79570. this._effect.setArray(name, this._floatsArrays[name]);
  79571. }
  79572. // Color3
  79573. for (name in this._colors3) {
  79574. this._effect.setColor3(name, this._colors3[name]);
  79575. }
  79576. // Color4
  79577. for (name in this._colors4) {
  79578. var color = this._colors4[name];
  79579. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  79580. }
  79581. // Vector2
  79582. for (name in this._vectors2) {
  79583. this._effect.setVector2(name, this._vectors2[name]);
  79584. }
  79585. // Vector3
  79586. for (name in this._vectors3) {
  79587. this._effect.setVector3(name, this._vectors3[name]);
  79588. }
  79589. // Matrix
  79590. for (name in this._matrices) {
  79591. this._effect.setMatrix(name, this._matrices[name]);
  79592. }
  79593. if (!this._texture) {
  79594. return;
  79595. }
  79596. if (this.isCube) {
  79597. for (var face = 0; face < 6; face++) {
  79598. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  79599. // VBOs
  79600. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79601. this._effect.setFloat("face", face);
  79602. // Clear
  79603. engine.clear(scene.clearColor, true, true, true);
  79604. // Draw order
  79605. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79606. // Mipmaps
  79607. if (face === 5) {
  79608. engine.generateMipMapsForCubemap(this._texture);
  79609. }
  79610. }
  79611. }
  79612. else {
  79613. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  79614. // VBOs
  79615. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79616. // Clear
  79617. engine.clear(scene.clearColor, true, true, true);
  79618. // Draw order
  79619. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79620. }
  79621. // Unbind
  79622. engine.unBindFramebuffer(this._texture, this.isCube);
  79623. if (this.onGenerated) {
  79624. this.onGenerated();
  79625. }
  79626. this.onGeneratedObservable.notifyObservers(this);
  79627. };
  79628. /**
  79629. * Clone the texture.
  79630. * @returns the cloned texture
  79631. */
  79632. ProceduralTexture.prototype.clone = function () {
  79633. var textureSize = this.getSize();
  79634. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  79635. // Base texture
  79636. newTexture.hasAlpha = this.hasAlpha;
  79637. newTexture.level = this.level;
  79638. // RenderTarget Texture
  79639. newTexture.coordinatesMode = this.coordinatesMode;
  79640. return newTexture;
  79641. };
  79642. /**
  79643. * Dispose the texture and release its asoociated resources.
  79644. */
  79645. ProceduralTexture.prototype.dispose = function () {
  79646. var scene = this.getScene();
  79647. if (!scene) {
  79648. return;
  79649. }
  79650. var index = scene.proceduralTextures.indexOf(this);
  79651. if (index >= 0) {
  79652. scene.proceduralTextures.splice(index, 1);
  79653. }
  79654. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79655. if (vertexBuffer) {
  79656. vertexBuffer.dispose();
  79657. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79658. }
  79659. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  79660. this._indexBuffer = null;
  79661. }
  79662. _super.prototype.dispose.call(this);
  79663. };
  79664. __decorate([
  79665. BABYLON.serialize()
  79666. ], ProceduralTexture.prototype, "isEnabled", void 0);
  79667. __decorate([
  79668. BABYLON.serialize()
  79669. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  79670. __decorate([
  79671. BABYLON.serialize()
  79672. ], ProceduralTexture.prototype, "_size", void 0);
  79673. __decorate([
  79674. BABYLON.serialize()
  79675. ], ProceduralTexture.prototype, "refreshRate", null);
  79676. return ProceduralTexture;
  79677. }(BABYLON.Texture));
  79678. BABYLON.ProceduralTexture = ProceduralTexture;
  79679. })(BABYLON || (BABYLON = {}));
  79680. //# sourceMappingURL=babylon.proceduralTexture.js.map
  79681. var BABYLON;
  79682. (function (BABYLON) {
  79683. /**
  79684. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  79685. * in a given scene.
  79686. */
  79687. var ProceduralTextureSceneComponent = /** @class */ (function () {
  79688. /**
  79689. * Creates a new instance of the component for the given scene
  79690. * @param scene Defines the scene to register the component in
  79691. */
  79692. function ProceduralTextureSceneComponent(scene) {
  79693. /**
  79694. * The component name helpfull to identify the component in the list of scene components.
  79695. */
  79696. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  79697. this.scene = scene;
  79698. this.scene.proceduralTextures = new Array();
  79699. scene.layers = new Array();
  79700. }
  79701. /**
  79702. * Registers the component in a given scene
  79703. */
  79704. ProceduralTextureSceneComponent.prototype.register = function () {
  79705. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  79706. };
  79707. /**
  79708. * Rebuilds the elements related to this component in case of
  79709. * context lost for instance.
  79710. */
  79711. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  79712. // Nothing to do here.
  79713. };
  79714. /**
  79715. * Disposes the component and the associated ressources.
  79716. */
  79717. ProceduralTextureSceneComponent.prototype.dispose = function () {
  79718. // Nothing to do here.
  79719. };
  79720. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  79721. if (this.scene.proceduralTexturesEnabled) {
  79722. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79723. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  79724. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  79725. if (proceduralTexture._shouldRender()) {
  79726. proceduralTexture.render();
  79727. }
  79728. }
  79729. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79730. }
  79731. };
  79732. return ProceduralTextureSceneComponent;
  79733. }());
  79734. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  79735. })(BABYLON || (BABYLON = {}));
  79736. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  79737. var BABYLON;
  79738. (function (BABYLON) {
  79739. /**
  79740. * 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.
  79741. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79742. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79743. */
  79744. var CustomProceduralTexture = /** @class */ (function (_super) {
  79745. __extends(CustomProceduralTexture, _super);
  79746. /**
  79747. * Instantiates a new Custom Procedural Texture.
  79748. * 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.
  79749. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79750. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79751. * @param name Define the name of the texture
  79752. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  79753. * @param size Define the size of the texture to create
  79754. * @param scene Define the scene the texture belongs to
  79755. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79756. * @param generateMipMaps Define if the texture should creates mip maps or not
  79757. */
  79758. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  79759. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  79760. _this._animate = true;
  79761. _this._time = 0;
  79762. _this._texturePath = texturePath;
  79763. //Try to load json
  79764. _this._loadJson(texturePath);
  79765. _this.refreshRate = 1;
  79766. return _this;
  79767. }
  79768. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  79769. var _this = this;
  79770. var noConfigFile = function () {
  79771. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  79772. try {
  79773. _this.setFragment(_this._texturePath);
  79774. }
  79775. catch (ex) {
  79776. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  79777. }
  79778. };
  79779. var configFileUrl = jsonUrl + "/config.json";
  79780. var xhr = new XMLHttpRequest();
  79781. xhr.open("GET", configFileUrl, true);
  79782. xhr.addEventListener("load", function () {
  79783. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79784. try {
  79785. _this._config = JSON.parse(xhr.response);
  79786. _this.updateShaderUniforms();
  79787. _this.updateTextures();
  79788. _this.setFragment(_this._texturePath + "/custom");
  79789. _this._animate = _this._config.animate;
  79790. _this.refreshRate = _this._config.refreshrate;
  79791. }
  79792. catch (ex) {
  79793. noConfigFile();
  79794. }
  79795. }
  79796. else {
  79797. noConfigFile();
  79798. }
  79799. }, false);
  79800. xhr.addEventListener("error", function () {
  79801. noConfigFile();
  79802. }, false);
  79803. try {
  79804. xhr.send();
  79805. }
  79806. catch (ex) {
  79807. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  79808. }
  79809. };
  79810. /**
  79811. * Is the texture ready to be used ? (rendered at least once)
  79812. * @returns true if ready, otherwise, false.
  79813. */
  79814. CustomProceduralTexture.prototype.isReady = function () {
  79815. if (!_super.prototype.isReady.call(this)) {
  79816. return false;
  79817. }
  79818. for (var name in this._textures) {
  79819. var texture = this._textures[name];
  79820. if (!texture.isReady()) {
  79821. return false;
  79822. }
  79823. }
  79824. return true;
  79825. };
  79826. /**
  79827. * Render the texture to its associated render target.
  79828. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79829. */
  79830. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79831. var scene = this.getScene();
  79832. if (this._animate && scene) {
  79833. this._time += scene.getAnimationRatio() * 0.03;
  79834. this.updateShaderUniforms();
  79835. }
  79836. _super.prototype.render.call(this, useCameraPostProcess);
  79837. };
  79838. /**
  79839. * Update the list of dependant textures samplers in the shader.
  79840. */
  79841. CustomProceduralTexture.prototype.updateTextures = function () {
  79842. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  79843. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  79844. }
  79845. };
  79846. /**
  79847. * Update the uniform values of the procedural texture in the shader.
  79848. */
  79849. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  79850. if (this._config) {
  79851. for (var j = 0; j < this._config.uniforms.length; j++) {
  79852. var uniform = this._config.uniforms[j];
  79853. switch (uniform.type) {
  79854. case "float":
  79855. this.setFloat(uniform.name, uniform.value);
  79856. break;
  79857. case "color3":
  79858. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  79859. break;
  79860. case "color4":
  79861. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  79862. break;
  79863. case "vector2":
  79864. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  79865. break;
  79866. case "vector3":
  79867. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  79868. break;
  79869. }
  79870. }
  79871. }
  79872. this.setFloat("time", this._time);
  79873. };
  79874. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  79875. /**
  79876. * Define if the texture animates or not.
  79877. */
  79878. get: function () {
  79879. return this._animate;
  79880. },
  79881. set: function (value) {
  79882. this._animate = value;
  79883. },
  79884. enumerable: true,
  79885. configurable: true
  79886. });
  79887. return CustomProceduralTexture;
  79888. }(BABYLON.ProceduralTexture));
  79889. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  79890. })(BABYLON || (BABYLON = {}));
  79891. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  79892. var BABYLON;
  79893. (function (BABYLON) {
  79894. /**
  79895. * Manage the gamepad inputs to control a free camera.
  79896. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79897. */
  79898. var FreeCameraGamepadInput = /** @class */ (function () {
  79899. function FreeCameraGamepadInput() {
  79900. /**
  79901. * Defines the gamepad rotation sensiblity.
  79902. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79903. */
  79904. this.gamepadAngularSensibility = 200;
  79905. /**
  79906. * Defines the gamepad move sensiblity.
  79907. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79908. */
  79909. this.gamepadMoveSensibility = 40;
  79910. this._cameraTransform = BABYLON.Matrix.Identity();
  79911. this._deltaTransform = BABYLON.Vector3.Zero();
  79912. this._vector3 = BABYLON.Vector3.Zero();
  79913. this._vector2 = BABYLON.Vector2.Zero();
  79914. }
  79915. /**
  79916. * Attach the input controls to a specific dom element to get the input from.
  79917. * @param element Defines the element the controls should be listened from
  79918. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79919. */
  79920. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  79921. var _this = this;
  79922. var manager = this.camera.getScene().gamepadManager;
  79923. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79924. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79925. // prioritize XBOX gamepads.
  79926. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  79927. _this.gamepad = gamepad;
  79928. }
  79929. }
  79930. });
  79931. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79932. if (_this.gamepad === gamepad) {
  79933. _this.gamepad = null;
  79934. }
  79935. });
  79936. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  79937. };
  79938. /**
  79939. * Detach the current controls from the specified dom element.
  79940. * @param element Defines the element to stop listening the inputs from
  79941. */
  79942. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  79943. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79944. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79945. this.gamepad = null;
  79946. };
  79947. /**
  79948. * Update the current camera state depending on the inputs that have been used this frame.
  79949. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79950. */
  79951. FreeCameraGamepadInput.prototype.checkInputs = function () {
  79952. if (this.gamepad && this.gamepad.leftStick) {
  79953. var camera = this.camera;
  79954. var LSValues = this.gamepad.leftStick;
  79955. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  79956. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  79957. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  79958. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  79959. var RSValues = this.gamepad.rightStick;
  79960. if (RSValues) {
  79961. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  79962. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  79963. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  79964. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  79965. }
  79966. else {
  79967. RSValues = { x: 0, y: 0 };
  79968. }
  79969. if (!camera.rotationQuaternion) {
  79970. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  79971. }
  79972. else {
  79973. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  79974. }
  79975. var speed = camera._computeLocalCameraSpeed() * 50.0;
  79976. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  79977. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  79978. camera.cameraDirection.addInPlace(this._deltaTransform);
  79979. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  79980. camera.cameraRotation.addInPlace(this._vector2);
  79981. }
  79982. };
  79983. /**
  79984. * Gets the class name of the current intput.
  79985. * @returns the class name
  79986. */
  79987. FreeCameraGamepadInput.prototype.getClassName = function () {
  79988. return "FreeCameraGamepadInput";
  79989. };
  79990. /**
  79991. * Get the friendly name associated with the input class.
  79992. * @returns the input friendly name
  79993. */
  79994. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  79995. return "gamepad";
  79996. };
  79997. __decorate([
  79998. BABYLON.serialize()
  79999. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  80000. __decorate([
  80001. BABYLON.serialize()
  80002. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  80003. return FreeCameraGamepadInput;
  80004. }());
  80005. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  80006. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  80007. })(BABYLON || (BABYLON = {}));
  80008. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  80009. var BABYLON;
  80010. (function (BABYLON) {
  80011. /**
  80012. * Manage the gamepad inputs to control an arc rotate camera.
  80013. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80014. */
  80015. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  80016. function ArcRotateCameraGamepadInput() {
  80017. /**
  80018. * Defines the gamepad rotation sensiblity.
  80019. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  80020. */
  80021. this.gamepadRotationSensibility = 80;
  80022. /**
  80023. * Defines the gamepad move sensiblity.
  80024. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  80025. */
  80026. this.gamepadMoveSensibility = 40;
  80027. }
  80028. /**
  80029. * Attach the input controls to a specific dom element to get the input from.
  80030. * @param element Defines the element the controls should be listened from
  80031. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80032. */
  80033. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  80034. var _this = this;
  80035. var manager = this.camera.getScene().gamepadManager;
  80036. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80037. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80038. // prioritize XBOX gamepads.
  80039. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  80040. _this.gamepad = gamepad;
  80041. }
  80042. }
  80043. });
  80044. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80045. if (_this.gamepad === gamepad) {
  80046. _this.gamepad = null;
  80047. }
  80048. });
  80049. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  80050. };
  80051. /**
  80052. * Detach the current controls from the specified dom element.
  80053. * @param element Defines the element to stop listening the inputs from
  80054. */
  80055. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  80056. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80057. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80058. this.gamepad = null;
  80059. };
  80060. /**
  80061. * Update the current camera state depending on the inputs that have been used this frame.
  80062. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80063. */
  80064. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  80065. if (this.gamepad) {
  80066. var camera = this.camera;
  80067. var RSValues = this.gamepad.rightStick;
  80068. if (RSValues) {
  80069. if (RSValues.x != 0) {
  80070. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  80071. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  80072. camera.inertialAlphaOffset += normalizedRX;
  80073. }
  80074. }
  80075. if (RSValues.y != 0) {
  80076. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  80077. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  80078. camera.inertialBetaOffset += normalizedRY;
  80079. }
  80080. }
  80081. }
  80082. var LSValues = this.gamepad.leftStick;
  80083. if (LSValues && LSValues.y != 0) {
  80084. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  80085. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  80086. this.camera.inertialRadiusOffset -= normalizedLY;
  80087. }
  80088. }
  80089. }
  80090. };
  80091. /**
  80092. * Gets the class name of the current intput.
  80093. * @returns the class name
  80094. */
  80095. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  80096. return "ArcRotateCameraGamepadInput";
  80097. };
  80098. /**
  80099. * Get the friendly name associated with the input class.
  80100. * @returns the input friendly name
  80101. */
  80102. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  80103. return "gamepad";
  80104. };
  80105. __decorate([
  80106. BABYLON.serialize()
  80107. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  80108. __decorate([
  80109. BABYLON.serialize()
  80110. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  80111. return ArcRotateCameraGamepadInput;
  80112. }());
  80113. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  80114. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  80115. })(BABYLON || (BABYLON = {}));
  80116. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  80117. var BABYLON;
  80118. (function (BABYLON) {
  80119. /**
  80120. * Manager for handling gamepads
  80121. */
  80122. var GamepadManager = /** @class */ (function () {
  80123. /**
  80124. * Initializes the gamepad manager
  80125. * @param _scene BabylonJS scene
  80126. */
  80127. function GamepadManager(_scene) {
  80128. var _this = this;
  80129. this._scene = _scene;
  80130. this._babylonGamepads = [];
  80131. this._oneGamepadConnected = false;
  80132. /** @hidden */
  80133. this._isMonitoring = false;
  80134. /**
  80135. * observable to be triggered when the gamepad controller has been disconnected
  80136. */
  80137. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  80138. if (!BABYLON.Tools.IsWindowObjectExist()) {
  80139. this._gamepadEventSupported = false;
  80140. }
  80141. else {
  80142. this._gamepadEventSupported = 'GamepadEvent' in window;
  80143. this._gamepadSupport = (navigator.getGamepads ||
  80144. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  80145. }
  80146. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  80147. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  80148. for (var i in _this._babylonGamepads) {
  80149. var gamepad = _this._babylonGamepads[i];
  80150. if (gamepad && gamepad._isConnected) {
  80151. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  80152. }
  80153. }
  80154. });
  80155. this._onGamepadConnectedEvent = function (evt) {
  80156. var gamepad = evt.gamepad;
  80157. if (gamepad.index in _this._babylonGamepads) {
  80158. if (_this._babylonGamepads[gamepad.index].isConnected) {
  80159. return;
  80160. }
  80161. }
  80162. var newGamepad;
  80163. if (_this._babylonGamepads[gamepad.index]) {
  80164. newGamepad = _this._babylonGamepads[gamepad.index];
  80165. newGamepad.browserGamepad = gamepad;
  80166. newGamepad._isConnected = true;
  80167. }
  80168. else {
  80169. newGamepad = _this._addNewGamepad(gamepad);
  80170. }
  80171. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80172. _this._startMonitoringGamepads();
  80173. };
  80174. this._onGamepadDisconnectedEvent = function (evt) {
  80175. var gamepad = evt.gamepad;
  80176. // Remove the gamepad from the list of gamepads to monitor.
  80177. for (var i in _this._babylonGamepads) {
  80178. if (_this._babylonGamepads[i].index === gamepad.index) {
  80179. var disconnectedGamepad = _this._babylonGamepads[i];
  80180. disconnectedGamepad._isConnected = false;
  80181. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  80182. break;
  80183. }
  80184. }
  80185. };
  80186. if (this._gamepadSupport) {
  80187. //first add already-connected gamepads
  80188. this._updateGamepadObjects();
  80189. if (this._babylonGamepads.length) {
  80190. this._startMonitoringGamepads();
  80191. }
  80192. // Checking if the gamepad connected event is supported (like in Firefox)
  80193. if (this._gamepadEventSupported) {
  80194. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  80195. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  80196. }
  80197. else {
  80198. this._startMonitoringGamepads();
  80199. }
  80200. }
  80201. }
  80202. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  80203. /**
  80204. * The gamepads in the game pad manager
  80205. */
  80206. get: function () {
  80207. return this._babylonGamepads;
  80208. },
  80209. enumerable: true,
  80210. configurable: true
  80211. });
  80212. /**
  80213. * Get the gamepad controllers based on type
  80214. * @param type The type of gamepad controller
  80215. * @returns Nullable gamepad
  80216. */
  80217. GamepadManager.prototype.getGamepadByType = function (type) {
  80218. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  80219. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  80220. var gamepad = _a[_i];
  80221. if (gamepad && gamepad.type === type) {
  80222. return gamepad;
  80223. }
  80224. }
  80225. return null;
  80226. };
  80227. /**
  80228. * Disposes the gamepad manager
  80229. */
  80230. GamepadManager.prototype.dispose = function () {
  80231. if (this._gamepadEventSupported) {
  80232. if (this._onGamepadConnectedEvent) {
  80233. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  80234. }
  80235. if (this._onGamepadDisconnectedEvent) {
  80236. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  80237. }
  80238. this._onGamepadConnectedEvent = null;
  80239. this._onGamepadDisconnectedEvent = null;
  80240. }
  80241. this._babylonGamepads.forEach(function (gamepad) {
  80242. gamepad.dispose();
  80243. });
  80244. this.onGamepadConnectedObservable.clear();
  80245. this.onGamepadDisconnectedObservable.clear();
  80246. this._oneGamepadConnected = false;
  80247. this._stopMonitoringGamepads();
  80248. this._babylonGamepads = [];
  80249. };
  80250. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  80251. if (!this._oneGamepadConnected) {
  80252. this._oneGamepadConnected = true;
  80253. }
  80254. var newGamepad;
  80255. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  80256. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  80257. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  80258. }
  80259. // if pose is supported, use the (WebVR) pose enabled controller
  80260. else if (gamepad.pose) {
  80261. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  80262. }
  80263. else {
  80264. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  80265. }
  80266. this._babylonGamepads[newGamepad.index] = newGamepad;
  80267. return newGamepad;
  80268. };
  80269. GamepadManager.prototype._startMonitoringGamepads = function () {
  80270. if (!this._isMonitoring) {
  80271. this._isMonitoring = true;
  80272. //back-comp
  80273. if (!this._scene) {
  80274. this._checkGamepadsStatus();
  80275. }
  80276. }
  80277. };
  80278. GamepadManager.prototype._stopMonitoringGamepads = function () {
  80279. this._isMonitoring = false;
  80280. };
  80281. /** @hidden */
  80282. GamepadManager.prototype._checkGamepadsStatus = function () {
  80283. var _this = this;
  80284. // Hack to be compatible Chrome
  80285. this._updateGamepadObjects();
  80286. for (var i in this._babylonGamepads) {
  80287. var gamepad = this._babylonGamepads[i];
  80288. if (!gamepad || !gamepad.isConnected) {
  80289. continue;
  80290. }
  80291. gamepad.update();
  80292. }
  80293. if (this._isMonitoring && !this._scene) {
  80294. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  80295. }
  80296. };
  80297. // This function is called only on Chrome, which does not properly support
  80298. // connection/disconnection events and forces you to recopy again the gamepad object
  80299. GamepadManager.prototype._updateGamepadObjects = function () {
  80300. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  80301. for (var i = 0; i < gamepads.length; i++) {
  80302. var gamepad = gamepads[i];
  80303. if (gamepad) {
  80304. if (!this._babylonGamepads[gamepad.index]) {
  80305. var newGamepad = this._addNewGamepad(gamepad);
  80306. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80307. }
  80308. else {
  80309. // Forced to copy again this object for Chrome for unknown reason
  80310. this._babylonGamepads[i].browserGamepad = gamepad;
  80311. if (!this._babylonGamepads[i].isConnected) {
  80312. this._babylonGamepads[i]._isConnected = true;
  80313. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  80314. }
  80315. }
  80316. }
  80317. }
  80318. };
  80319. return GamepadManager;
  80320. }());
  80321. BABYLON.GamepadManager = GamepadManager;
  80322. })(BABYLON || (BABYLON = {}));
  80323. //# sourceMappingURL=babylon.gamepadManager.js.map
  80324. var BABYLON;
  80325. (function (BABYLON) {
  80326. /**
  80327. * Represents a gamepad control stick position
  80328. */
  80329. var StickValues = /** @class */ (function () {
  80330. /**
  80331. * Initializes the gamepad x and y control stick values
  80332. * @param x The x component of the gamepad control stick value
  80333. * @param y The y component of the gamepad control stick value
  80334. */
  80335. function StickValues(
  80336. /**
  80337. * The x component of the control stick
  80338. */
  80339. x,
  80340. /**
  80341. * The y component of the control stick
  80342. */
  80343. y) {
  80344. this.x = x;
  80345. this.y = y;
  80346. }
  80347. return StickValues;
  80348. }());
  80349. BABYLON.StickValues = StickValues;
  80350. /**
  80351. * Represents a gamepad
  80352. */
  80353. var Gamepad = /** @class */ (function () {
  80354. /**
  80355. * Initializes the gamepad
  80356. * @param id The id of the gamepad
  80357. * @param index The index of the gamepad
  80358. * @param browserGamepad The browser gamepad
  80359. * @param leftStickX The x component of the left joystick
  80360. * @param leftStickY The y component of the left joystick
  80361. * @param rightStickX The x component of the right joystick
  80362. * @param rightStickY The y component of the right joystick
  80363. */
  80364. function Gamepad(
  80365. /**
  80366. * The id of the gamepad
  80367. */
  80368. id,
  80369. /**
  80370. * The index of the gamepad
  80371. */
  80372. index,
  80373. /**
  80374. * The browser gamepad
  80375. */
  80376. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  80377. if (leftStickX === void 0) { leftStickX = 0; }
  80378. if (leftStickY === void 0) { leftStickY = 1; }
  80379. if (rightStickX === void 0) { rightStickX = 2; }
  80380. if (rightStickY === void 0) { rightStickY = 3; }
  80381. this.id = id;
  80382. this.index = index;
  80383. this.browserGamepad = browserGamepad;
  80384. this._leftStick = { x: 0, y: 0 };
  80385. this._rightStick = { x: 0, y: 0 };
  80386. /** @hidden */
  80387. this._isConnected = true;
  80388. /**
  80389. * Specifies whether the left control stick should be Y-inverted
  80390. */
  80391. this._invertLeftStickY = false;
  80392. this.type = Gamepad.GAMEPAD;
  80393. this._leftStickAxisX = leftStickX;
  80394. this._leftStickAxisY = leftStickY;
  80395. this._rightStickAxisX = rightStickX;
  80396. this._rightStickAxisY = rightStickY;
  80397. if (this.browserGamepad.axes.length >= 2) {
  80398. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80399. }
  80400. if (this.browserGamepad.axes.length >= 4) {
  80401. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80402. }
  80403. }
  80404. Object.defineProperty(Gamepad.prototype, "isConnected", {
  80405. /**
  80406. * Specifies if the gamepad has been connected
  80407. */
  80408. get: function () {
  80409. return this._isConnected;
  80410. },
  80411. enumerable: true,
  80412. configurable: true
  80413. });
  80414. /**
  80415. * Callback triggered when the left joystick has changed
  80416. * @param callback
  80417. */
  80418. Gamepad.prototype.onleftstickchanged = function (callback) {
  80419. this._onleftstickchanged = callback;
  80420. };
  80421. /**
  80422. * Callback triggered when the right joystick has changed
  80423. * @param callback
  80424. */
  80425. Gamepad.prototype.onrightstickchanged = function (callback) {
  80426. this._onrightstickchanged = callback;
  80427. };
  80428. Object.defineProperty(Gamepad.prototype, "leftStick", {
  80429. /**
  80430. * Gets the left joystick
  80431. */
  80432. get: function () {
  80433. return this._leftStick;
  80434. },
  80435. /**
  80436. * Sets the left joystick values
  80437. */
  80438. set: function (newValues) {
  80439. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  80440. this._onleftstickchanged(newValues);
  80441. }
  80442. this._leftStick = newValues;
  80443. },
  80444. enumerable: true,
  80445. configurable: true
  80446. });
  80447. Object.defineProperty(Gamepad.prototype, "rightStick", {
  80448. /**
  80449. * Gets the right joystick
  80450. */
  80451. get: function () {
  80452. return this._rightStick;
  80453. },
  80454. /**
  80455. * Sets the right joystick value
  80456. */
  80457. set: function (newValues) {
  80458. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  80459. this._onrightstickchanged(newValues);
  80460. }
  80461. this._rightStick = newValues;
  80462. },
  80463. enumerable: true,
  80464. configurable: true
  80465. });
  80466. /**
  80467. * Updates the gamepad joystick positions
  80468. */
  80469. Gamepad.prototype.update = function () {
  80470. if (this._leftStick) {
  80471. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80472. if (this._invertLeftStickY) {
  80473. this.leftStick.y *= -1;
  80474. }
  80475. }
  80476. if (this._rightStick) {
  80477. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80478. }
  80479. };
  80480. /**
  80481. * Disposes the gamepad
  80482. */
  80483. Gamepad.prototype.dispose = function () {
  80484. };
  80485. /**
  80486. * Represents a gamepad controller
  80487. */
  80488. Gamepad.GAMEPAD = 0;
  80489. /**
  80490. * Represents a generic controller
  80491. */
  80492. Gamepad.GENERIC = 1;
  80493. /**
  80494. * Represents an XBox controller
  80495. */
  80496. Gamepad.XBOX = 2;
  80497. /**
  80498. * Represents a pose-enabled controller
  80499. */
  80500. Gamepad.POSE_ENABLED = 3;
  80501. return Gamepad;
  80502. }());
  80503. BABYLON.Gamepad = Gamepad;
  80504. /**
  80505. * Represents a generic gamepad
  80506. */
  80507. var GenericPad = /** @class */ (function (_super) {
  80508. __extends(GenericPad, _super);
  80509. /**
  80510. * Initializes the generic gamepad
  80511. * @param id The id of the generic gamepad
  80512. * @param index The index of the generic gamepad
  80513. * @param browserGamepad The browser gamepad
  80514. */
  80515. function GenericPad(id, index, browserGamepad) {
  80516. var _this = _super.call(this, id, index, browserGamepad) || this;
  80517. /**
  80518. * Observable triggered when a button has been pressed
  80519. */
  80520. _this.onButtonDownObservable = new BABYLON.Observable();
  80521. /**
  80522. * Observable triggered when a button has been released
  80523. */
  80524. _this.onButtonUpObservable = new BABYLON.Observable();
  80525. _this.type = Gamepad.GENERIC;
  80526. _this._buttons = new Array(browserGamepad.buttons.length);
  80527. return _this;
  80528. }
  80529. /**
  80530. * Callback triggered when a button has been pressed
  80531. * @param callback Called when a button has been pressed
  80532. */
  80533. GenericPad.prototype.onbuttondown = function (callback) {
  80534. this._onbuttondown = callback;
  80535. };
  80536. /**
  80537. * Callback triggered when a button has been released
  80538. * @param callback Called when a button has been released
  80539. */
  80540. GenericPad.prototype.onbuttonup = function (callback) {
  80541. this._onbuttonup = callback;
  80542. };
  80543. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  80544. if (newValue !== currentValue) {
  80545. if (newValue === 1) {
  80546. if (this._onbuttondown) {
  80547. this._onbuttondown(buttonIndex);
  80548. }
  80549. this.onButtonDownObservable.notifyObservers(buttonIndex);
  80550. }
  80551. if (newValue === 0) {
  80552. if (this._onbuttonup) {
  80553. this._onbuttonup(buttonIndex);
  80554. }
  80555. this.onButtonUpObservable.notifyObservers(buttonIndex);
  80556. }
  80557. }
  80558. return newValue;
  80559. };
  80560. /**
  80561. * Updates the generic gamepad
  80562. */
  80563. GenericPad.prototype.update = function () {
  80564. _super.prototype.update.call(this);
  80565. for (var index = 0; index < this._buttons.length; index++) {
  80566. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  80567. }
  80568. };
  80569. /**
  80570. * Disposes the generic gamepad
  80571. */
  80572. GenericPad.prototype.dispose = function () {
  80573. _super.prototype.dispose.call(this);
  80574. this.onButtonDownObservable.clear();
  80575. this.onButtonUpObservable.clear();
  80576. };
  80577. return GenericPad;
  80578. }(Gamepad));
  80579. BABYLON.GenericPad = GenericPad;
  80580. })(BABYLON || (BABYLON = {}));
  80581. //# sourceMappingURL=babylon.gamepad.js.map
  80582. var BABYLON;
  80583. (function (BABYLON) {
  80584. /**
  80585. * Defines supported buttons for XBox360 compatible gamepads
  80586. */
  80587. var Xbox360Button;
  80588. (function (Xbox360Button) {
  80589. /** A */
  80590. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  80591. /** B */
  80592. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  80593. /** X */
  80594. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  80595. /** Y */
  80596. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  80597. /** Start */
  80598. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  80599. /** Back */
  80600. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  80601. /** Left button */
  80602. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  80603. /** Right button */
  80604. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  80605. /** Left stick */
  80606. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  80607. /** Right stick */
  80608. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  80609. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  80610. /** Defines values for XBox360 DPad */
  80611. var Xbox360Dpad;
  80612. (function (Xbox360Dpad) {
  80613. /** Up */
  80614. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  80615. /** Down */
  80616. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  80617. /** Left */
  80618. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  80619. /** Right */
  80620. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  80621. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  80622. /**
  80623. * Defines a XBox360 gamepad
  80624. */
  80625. var Xbox360Pad = /** @class */ (function (_super) {
  80626. __extends(Xbox360Pad, _super);
  80627. /**
  80628. * Creates a new XBox360 gamepad object
  80629. * @param id defines the id of this gamepad
  80630. * @param index defines its index
  80631. * @param gamepad defines the internal HTML gamepad object
  80632. * @param xboxOne defines if it is a XBox One gamepad
  80633. */
  80634. function Xbox360Pad(id, index, gamepad, xboxOne) {
  80635. if (xboxOne === void 0) { xboxOne = false; }
  80636. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  80637. _this._leftTrigger = 0;
  80638. _this._rightTrigger = 0;
  80639. /** Observable raised when a button is pressed */
  80640. _this.onButtonDownObservable = new BABYLON.Observable();
  80641. /** Observable raised when a button is released */
  80642. _this.onButtonUpObservable = new BABYLON.Observable();
  80643. /** Observable raised when a pad is pressed */
  80644. _this.onPadDownObservable = new BABYLON.Observable();
  80645. /** Observable raised when a pad is released */
  80646. _this.onPadUpObservable = new BABYLON.Observable();
  80647. _this._buttonA = 0;
  80648. _this._buttonB = 0;
  80649. _this._buttonX = 0;
  80650. _this._buttonY = 0;
  80651. _this._buttonBack = 0;
  80652. _this._buttonStart = 0;
  80653. _this._buttonLB = 0;
  80654. _this._buttonRB = 0;
  80655. _this._buttonLeftStick = 0;
  80656. _this._buttonRightStick = 0;
  80657. _this._dPadUp = 0;
  80658. _this._dPadDown = 0;
  80659. _this._dPadLeft = 0;
  80660. _this._dPadRight = 0;
  80661. _this._isXboxOnePad = false;
  80662. _this.type = BABYLON.Gamepad.XBOX;
  80663. _this._isXboxOnePad = xboxOne;
  80664. return _this;
  80665. }
  80666. /**
  80667. * Defines the callback to call when left trigger is pressed
  80668. * @param callback defines the callback to use
  80669. */
  80670. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  80671. this._onlefttriggerchanged = callback;
  80672. };
  80673. /**
  80674. * Defines the callback to call when right trigger is pressed
  80675. * @param callback defines the callback to use
  80676. */
  80677. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  80678. this._onrighttriggerchanged = callback;
  80679. };
  80680. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  80681. /**
  80682. * Gets the left trigger value
  80683. */
  80684. get: function () {
  80685. return this._leftTrigger;
  80686. },
  80687. /**
  80688. * Sets the left trigger value
  80689. */
  80690. set: function (newValue) {
  80691. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  80692. this._onlefttriggerchanged(newValue);
  80693. }
  80694. this._leftTrigger = newValue;
  80695. },
  80696. enumerable: true,
  80697. configurable: true
  80698. });
  80699. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  80700. /**
  80701. * Gets the right trigger value
  80702. */
  80703. get: function () {
  80704. return this._rightTrigger;
  80705. },
  80706. /**
  80707. * Sets the right trigger value
  80708. */
  80709. set: function (newValue) {
  80710. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  80711. this._onrighttriggerchanged(newValue);
  80712. }
  80713. this._rightTrigger = newValue;
  80714. },
  80715. enumerable: true,
  80716. configurable: true
  80717. });
  80718. /**
  80719. * Defines the callback to call when a button is pressed
  80720. * @param callback defines the callback to use
  80721. */
  80722. Xbox360Pad.prototype.onbuttondown = function (callback) {
  80723. this._onbuttondown = callback;
  80724. };
  80725. /**
  80726. * Defines the callback to call when a button is released
  80727. * @param callback defines the callback to use
  80728. */
  80729. Xbox360Pad.prototype.onbuttonup = function (callback) {
  80730. this._onbuttonup = callback;
  80731. };
  80732. /**
  80733. * Defines the callback to call when a pad is pressed
  80734. * @param callback defines the callback to use
  80735. */
  80736. Xbox360Pad.prototype.ondpaddown = function (callback) {
  80737. this._ondpaddown = callback;
  80738. };
  80739. /**
  80740. * Defines the callback to call when a pad is released
  80741. * @param callback defines the callback to use
  80742. */
  80743. Xbox360Pad.prototype.ondpadup = function (callback) {
  80744. this._ondpadup = callback;
  80745. };
  80746. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  80747. if (newValue !== currentValue) {
  80748. if (newValue === 1) {
  80749. if (this._onbuttondown) {
  80750. this._onbuttondown(buttonType);
  80751. }
  80752. this.onButtonDownObservable.notifyObservers(buttonType);
  80753. }
  80754. if (newValue === 0) {
  80755. if (this._onbuttonup) {
  80756. this._onbuttonup(buttonType);
  80757. }
  80758. this.onButtonUpObservable.notifyObservers(buttonType);
  80759. }
  80760. }
  80761. return newValue;
  80762. };
  80763. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  80764. if (newValue !== currentValue) {
  80765. if (newValue === 1) {
  80766. if (this._ondpaddown) {
  80767. this._ondpaddown(buttonType);
  80768. }
  80769. this.onPadDownObservable.notifyObservers(buttonType);
  80770. }
  80771. if (newValue === 0) {
  80772. if (this._ondpadup) {
  80773. this._ondpadup(buttonType);
  80774. }
  80775. this.onPadUpObservable.notifyObservers(buttonType);
  80776. }
  80777. }
  80778. return newValue;
  80779. };
  80780. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  80781. /**
  80782. * Gets the value of the `A` button
  80783. */
  80784. get: function () {
  80785. return this._buttonA;
  80786. },
  80787. /**
  80788. * Sets the value of the `A` button
  80789. */
  80790. set: function (value) {
  80791. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  80792. },
  80793. enumerable: true,
  80794. configurable: true
  80795. });
  80796. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  80797. /**
  80798. * Gets the value of the `B` button
  80799. */
  80800. get: function () {
  80801. return this._buttonB;
  80802. },
  80803. /**
  80804. * Sets the value of the `B` button
  80805. */
  80806. set: function (value) {
  80807. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  80808. },
  80809. enumerable: true,
  80810. configurable: true
  80811. });
  80812. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  80813. /**
  80814. * Gets the value of the `X` button
  80815. */
  80816. get: function () {
  80817. return this._buttonX;
  80818. },
  80819. /**
  80820. * Sets the value of the `X` button
  80821. */
  80822. set: function (value) {
  80823. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  80824. },
  80825. enumerable: true,
  80826. configurable: true
  80827. });
  80828. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  80829. /**
  80830. * Gets the value of the `Y` button
  80831. */
  80832. get: function () {
  80833. return this._buttonY;
  80834. },
  80835. /**
  80836. * Sets the value of the `Y` button
  80837. */
  80838. set: function (value) {
  80839. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  80840. },
  80841. enumerable: true,
  80842. configurable: true
  80843. });
  80844. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  80845. /**
  80846. * Gets the value of the `Start` button
  80847. */
  80848. get: function () {
  80849. return this._buttonStart;
  80850. },
  80851. /**
  80852. * Sets the value of the `Start` button
  80853. */
  80854. set: function (value) {
  80855. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  80856. },
  80857. enumerable: true,
  80858. configurable: true
  80859. });
  80860. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  80861. /**
  80862. * Gets the value of the `Back` button
  80863. */
  80864. get: function () {
  80865. return this._buttonBack;
  80866. },
  80867. /**
  80868. * Sets the value of the `Back` button
  80869. */
  80870. set: function (value) {
  80871. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  80872. },
  80873. enumerable: true,
  80874. configurable: true
  80875. });
  80876. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  80877. /**
  80878. * Gets the value of the `Left` button
  80879. */
  80880. get: function () {
  80881. return this._buttonLB;
  80882. },
  80883. /**
  80884. * Sets the value of the `Left` button
  80885. */
  80886. set: function (value) {
  80887. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  80888. },
  80889. enumerable: true,
  80890. configurable: true
  80891. });
  80892. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  80893. /**
  80894. * Gets the value of the `Right` button
  80895. */
  80896. get: function () {
  80897. return this._buttonRB;
  80898. },
  80899. /**
  80900. * Sets the value of the `Right` button
  80901. */
  80902. set: function (value) {
  80903. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  80904. },
  80905. enumerable: true,
  80906. configurable: true
  80907. });
  80908. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  80909. /**
  80910. * Gets the value of the Left joystick
  80911. */
  80912. get: function () {
  80913. return this._buttonLeftStick;
  80914. },
  80915. /**
  80916. * Sets the value of the Left joystick
  80917. */
  80918. set: function (value) {
  80919. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  80920. },
  80921. enumerable: true,
  80922. configurable: true
  80923. });
  80924. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  80925. /**
  80926. * Gets the value of the Right joystick
  80927. */
  80928. get: function () {
  80929. return this._buttonRightStick;
  80930. },
  80931. /**
  80932. * Sets the value of the Right joystick
  80933. */
  80934. set: function (value) {
  80935. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  80936. },
  80937. enumerable: true,
  80938. configurable: true
  80939. });
  80940. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  80941. /**
  80942. * Gets the value of D-pad up
  80943. */
  80944. get: function () {
  80945. return this._dPadUp;
  80946. },
  80947. /**
  80948. * Sets the value of D-pad up
  80949. */
  80950. set: function (value) {
  80951. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  80952. },
  80953. enumerable: true,
  80954. configurable: true
  80955. });
  80956. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  80957. /**
  80958. * Gets the value of D-pad down
  80959. */
  80960. get: function () {
  80961. return this._dPadDown;
  80962. },
  80963. /**
  80964. * Sets the value of D-pad down
  80965. */
  80966. set: function (value) {
  80967. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  80968. },
  80969. enumerable: true,
  80970. configurable: true
  80971. });
  80972. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  80973. /**
  80974. * Gets the value of D-pad left
  80975. */
  80976. get: function () {
  80977. return this._dPadLeft;
  80978. },
  80979. /**
  80980. * Sets the value of D-pad left
  80981. */
  80982. set: function (value) {
  80983. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  80984. },
  80985. enumerable: true,
  80986. configurable: true
  80987. });
  80988. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  80989. /**
  80990. * Gets the value of D-pad right
  80991. */
  80992. get: function () {
  80993. return this._dPadRight;
  80994. },
  80995. /**
  80996. * Sets the value of D-pad right
  80997. */
  80998. set: function (value) {
  80999. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  81000. },
  81001. enumerable: true,
  81002. configurable: true
  81003. });
  81004. /**
  81005. * Force the gamepad to synchronize with device values
  81006. */
  81007. Xbox360Pad.prototype.update = function () {
  81008. _super.prototype.update.call(this);
  81009. if (this._isXboxOnePad) {
  81010. this.buttonA = this.browserGamepad.buttons[0].value;
  81011. this.buttonB = this.browserGamepad.buttons[1].value;
  81012. this.buttonX = this.browserGamepad.buttons[2].value;
  81013. this.buttonY = this.browserGamepad.buttons[3].value;
  81014. this.buttonLB = this.browserGamepad.buttons[4].value;
  81015. this.buttonRB = this.browserGamepad.buttons[5].value;
  81016. this.leftTrigger = this.browserGamepad.axes[2];
  81017. this.rightTrigger = this.browserGamepad.axes[5];
  81018. this.buttonBack = this.browserGamepad.buttons[9].value;
  81019. this.buttonStart = this.browserGamepad.buttons[8].value;
  81020. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  81021. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  81022. this.dPadUp = this.browserGamepad.buttons[11].value;
  81023. this.dPadDown = this.browserGamepad.buttons[12].value;
  81024. this.dPadLeft = this.browserGamepad.buttons[13].value;
  81025. this.dPadRight = this.browserGamepad.buttons[14].value;
  81026. }
  81027. else {
  81028. this.buttonA = this.browserGamepad.buttons[0].value;
  81029. this.buttonB = this.browserGamepad.buttons[1].value;
  81030. this.buttonX = this.browserGamepad.buttons[2].value;
  81031. this.buttonY = this.browserGamepad.buttons[3].value;
  81032. this.buttonLB = this.browserGamepad.buttons[4].value;
  81033. this.buttonRB = this.browserGamepad.buttons[5].value;
  81034. this.leftTrigger = this.browserGamepad.buttons[6].value;
  81035. this.rightTrigger = this.browserGamepad.buttons[7].value;
  81036. this.buttonBack = this.browserGamepad.buttons[8].value;
  81037. this.buttonStart = this.browserGamepad.buttons[9].value;
  81038. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  81039. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  81040. this.dPadUp = this.browserGamepad.buttons[12].value;
  81041. this.dPadDown = this.browserGamepad.buttons[13].value;
  81042. this.dPadLeft = this.browserGamepad.buttons[14].value;
  81043. this.dPadRight = this.browserGamepad.buttons[15].value;
  81044. }
  81045. };
  81046. /**
  81047. * Disposes the gamepad
  81048. */
  81049. Xbox360Pad.prototype.dispose = function () {
  81050. _super.prototype.dispose.call(this);
  81051. this.onButtonDownObservable.clear();
  81052. this.onButtonUpObservable.clear();
  81053. this.onPadDownObservable.clear();
  81054. this.onPadUpObservable.clear();
  81055. };
  81056. return Xbox360Pad;
  81057. }(BABYLON.Gamepad));
  81058. BABYLON.Xbox360Pad = Xbox360Pad;
  81059. })(BABYLON || (BABYLON = {}));
  81060. //# sourceMappingURL=babylon.xboxGamepad.js.map
  81061. var BABYLON;
  81062. (function (BABYLON) {
  81063. /**
  81064. * Defines the types of pose enabled controllers that are supported
  81065. */
  81066. var PoseEnabledControllerType;
  81067. (function (PoseEnabledControllerType) {
  81068. /**
  81069. * HTC Vive
  81070. */
  81071. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  81072. /**
  81073. * Oculus Rift
  81074. */
  81075. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  81076. /**
  81077. * Windows mixed reality
  81078. */
  81079. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  81080. /**
  81081. * Samsung gear VR
  81082. */
  81083. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  81084. /**
  81085. * Google Daydream
  81086. */
  81087. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  81088. /**
  81089. * Generic
  81090. */
  81091. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  81092. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  81093. /**
  81094. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  81095. */
  81096. var PoseEnabledControllerHelper = /** @class */ (function () {
  81097. function PoseEnabledControllerHelper() {
  81098. }
  81099. /**
  81100. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  81101. * @param vrGamepad the gamepad to initialized
  81102. * @returns a vr controller of the type the gamepad identified as
  81103. */
  81104. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  81105. // Oculus Touch
  81106. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  81107. return new BABYLON.OculusTouchController(vrGamepad);
  81108. }
  81109. // Windows Mixed Reality controllers
  81110. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  81111. return new BABYLON.WindowsMotionController(vrGamepad);
  81112. }
  81113. // HTC Vive
  81114. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  81115. return new BABYLON.ViveController(vrGamepad);
  81116. }
  81117. // Samsung/Oculus Gear VR or Oculus Go
  81118. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  81119. return new BABYLON.GearVRController(vrGamepad);
  81120. }
  81121. // Google Daydream
  81122. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  81123. return new BABYLON.DaydreamController(vrGamepad);
  81124. }
  81125. // Generic
  81126. else {
  81127. return new BABYLON.GenericController(vrGamepad);
  81128. }
  81129. };
  81130. return PoseEnabledControllerHelper;
  81131. }());
  81132. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  81133. /**
  81134. * Defines the PoseEnabledController object that contains state of a vr capable controller
  81135. */
  81136. var PoseEnabledController = /** @class */ (function (_super) {
  81137. __extends(PoseEnabledController, _super);
  81138. /**
  81139. * Creates a new PoseEnabledController from a gamepad
  81140. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  81141. */
  81142. function PoseEnabledController(browserGamepad) {
  81143. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  81144. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81145. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81146. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  81147. /**
  81148. * The device position in babylon space
  81149. */
  81150. _this.devicePosition = BABYLON.Vector3.Zero();
  81151. /**
  81152. * The device rotation in babylon space
  81153. */
  81154. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  81155. /**
  81156. * The scale factor of the device in babylon space
  81157. */
  81158. _this.deviceScaleFactor = 1;
  81159. // Used to convert 6dof controllers to 3dof
  81160. _this._trackPosition = true;
  81161. _this._maxRotationDistFromHeadset = Math.PI / 5;
  81162. _this._draggedRoomRotation = 0;
  81163. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  81164. /**
  81165. * Internal, matrix used to convert room space to babylon space
  81166. * @hidden
  81167. */
  81168. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81169. /**
  81170. * Node to be used when casting a ray from the controller
  81171. * @hidden
  81172. */
  81173. _this._pointingPoseNode = null;
  81174. _this._workingMatrix = BABYLON.Matrix.Identity();
  81175. /**
  81176. * @hidden
  81177. */
  81178. _this._meshAttachedObservable = new BABYLON.Observable();
  81179. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  81180. _this.controllerType = PoseEnabledControllerType.GENERIC;
  81181. _this.position = BABYLON.Vector3.Zero();
  81182. _this.rotationQuaternion = new BABYLON.Quaternion();
  81183. _this._calculatedPosition = BABYLON.Vector3.Zero();
  81184. _this._calculatedRotation = new BABYLON.Quaternion();
  81185. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  81186. return _this;
  81187. }
  81188. /**
  81189. * @hidden
  81190. */
  81191. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  81192. if (this._trackPosition) {
  81193. this._calculatedPosition.copyFrom(fixedPosition);
  81194. this._trackPosition = false;
  81195. }
  81196. };
  81197. /**
  81198. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  81199. */
  81200. PoseEnabledController.prototype.update = function () {
  81201. _super.prototype.update.call(this);
  81202. this._updatePoseAndMesh();
  81203. };
  81204. /**
  81205. * Updates only the pose device and mesh without doing any button event checking
  81206. */
  81207. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  81208. var pose = this.browserGamepad.pose;
  81209. this.updateFromDevice(pose);
  81210. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  81211. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  81212. camera._computeDevicePosition();
  81213. this._deviceToWorld.setTranslation(camera.devicePosition);
  81214. if (camera.deviceRotationQuaternion) {
  81215. var camera = camera;
  81216. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  81217. // Find the radian distance away that the headset is from the controllers rotation
  81218. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  81219. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  81220. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  81221. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  81222. this._draggedRoomRotation += rotationAmount;
  81223. // Rotate controller around headset
  81224. var sin = Math.sin(-rotationAmount);
  81225. var cos = Math.cos(-rotationAmount);
  81226. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  81227. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  81228. }
  81229. }
  81230. }
  81231. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  81232. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  81233. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81234. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  81235. if (this._mesh) {
  81236. this._mesh.position.copyFrom(this.devicePosition);
  81237. if (this._mesh.rotationQuaternion) {
  81238. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  81239. }
  81240. }
  81241. };
  81242. /**
  81243. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  81244. * @param poseData raw pose fromthe device
  81245. */
  81246. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  81247. if (poseData) {
  81248. this.rawPose = poseData;
  81249. if (poseData.position) {
  81250. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  81251. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  81252. this._deviceRoomPosition.z *= -1;
  81253. }
  81254. if (this._trackPosition) {
  81255. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  81256. }
  81257. this._calculatedPosition.addInPlace(this.position);
  81258. }
  81259. var pose = this.rawPose;
  81260. if (poseData.orientation && pose.orientation) {
  81261. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  81262. if (this._mesh) {
  81263. if (this._mesh.getScene().useRightHandedSystem) {
  81264. this._deviceRoomRotationQuaternion.z *= -1;
  81265. this._deviceRoomRotationQuaternion.w *= -1;
  81266. }
  81267. else {
  81268. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  81269. }
  81270. }
  81271. // if the camera is set, rotate to the camera's rotation
  81272. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  81273. }
  81274. }
  81275. };
  81276. /**
  81277. * Attaches a mesh to the controller
  81278. * @param mesh the mesh to be attached
  81279. */
  81280. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  81281. if (this._mesh) {
  81282. this._mesh.parent = null;
  81283. }
  81284. this._mesh = mesh;
  81285. if (this._poseControlledCamera) {
  81286. this._mesh.parent = this._poseControlledCamera;
  81287. }
  81288. if (!this._mesh.rotationQuaternion) {
  81289. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  81290. }
  81291. // 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
  81292. this._updatePoseAndMesh();
  81293. if (this._pointingPoseNode) {
  81294. var parents = [];
  81295. var obj = this._pointingPoseNode;
  81296. while (obj.parent) {
  81297. parents.push(obj.parent);
  81298. obj = obj.parent;
  81299. }
  81300. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  81301. }
  81302. this._meshAttachedObservable.notifyObservers(mesh);
  81303. };
  81304. /**
  81305. * Attaches the controllers mesh to a camera
  81306. * @param camera the camera the mesh should be attached to
  81307. */
  81308. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  81309. this._poseControlledCamera = camera;
  81310. if (this._mesh) {
  81311. this._mesh.parent = this._poseControlledCamera;
  81312. }
  81313. };
  81314. /**
  81315. * Disposes of the controller
  81316. */
  81317. PoseEnabledController.prototype.dispose = function () {
  81318. if (this._mesh) {
  81319. this._mesh.dispose();
  81320. }
  81321. this._mesh = null;
  81322. _super.prototype.dispose.call(this);
  81323. };
  81324. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  81325. /**
  81326. * The mesh that is attached to the controller
  81327. */
  81328. get: function () {
  81329. return this._mesh;
  81330. },
  81331. enumerable: true,
  81332. configurable: true
  81333. });
  81334. /**
  81335. * Gets the ray of the controller in the direction the controller is pointing
  81336. * @param length the length the resulting ray should be
  81337. * @returns a ray in the direction the controller is pointing
  81338. */
  81339. PoseEnabledController.prototype.getForwardRay = function (length) {
  81340. if (length === void 0) { length = 100; }
  81341. if (!this.mesh) {
  81342. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  81343. }
  81344. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  81345. var origin = m.getTranslation();
  81346. var forward = new BABYLON.Vector3(0, 0, -1);
  81347. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81348. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81349. return new BABYLON.Ray(origin, direction, length);
  81350. };
  81351. /**
  81352. * Name of the child mesh that can be used to cast a ray from the controller
  81353. */
  81354. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  81355. return PoseEnabledController;
  81356. }(BABYLON.Gamepad));
  81357. BABYLON.PoseEnabledController = PoseEnabledController;
  81358. })(BABYLON || (BABYLON = {}));
  81359. //# sourceMappingURL=babylon.poseEnabledController.js.map
  81360. var BABYLON;
  81361. (function (BABYLON) {
  81362. /**
  81363. * Defines the WebVRController object that represents controllers tracked in 3D space
  81364. */
  81365. var WebVRController = /** @class */ (function (_super) {
  81366. __extends(WebVRController, _super);
  81367. /**
  81368. * Creates a new WebVRController from a gamepad
  81369. * @param vrGamepad the gamepad that the WebVRController should be created from
  81370. */
  81371. function WebVRController(vrGamepad) {
  81372. var _this = _super.call(this, vrGamepad) || this;
  81373. // Observables
  81374. /**
  81375. * Fired when the trigger state has changed
  81376. */
  81377. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  81378. /**
  81379. * Fired when the main button state has changed
  81380. */
  81381. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  81382. /**
  81383. * Fired when the secondary button state has changed
  81384. */
  81385. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  81386. /**
  81387. * Fired when the pad state has changed
  81388. */
  81389. _this.onPadStateChangedObservable = new BABYLON.Observable();
  81390. /**
  81391. * Fired when controllers stick values have changed
  81392. */
  81393. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  81394. /**
  81395. * X and Y axis corrisponding to the controllers joystick
  81396. */
  81397. _this.pad = { x: 0, y: 0 };
  81398. // avoid GC, store state in a tmp object
  81399. _this._changes = {
  81400. pressChanged: false,
  81401. touchChanged: false,
  81402. valueChanged: false,
  81403. changed: false
  81404. };
  81405. _this._buttons = new Array(vrGamepad.buttons.length);
  81406. _this.hand = vrGamepad.hand;
  81407. return _this;
  81408. }
  81409. /**
  81410. * Fired when a controller button's state has changed
  81411. * @param callback the callback containing the button that was modified
  81412. */
  81413. WebVRController.prototype.onButtonStateChange = function (callback) {
  81414. this._onButtonStateChange = callback;
  81415. };
  81416. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  81417. /**
  81418. * The default controller model for the controller
  81419. */
  81420. get: function () {
  81421. return this._defaultModel;
  81422. },
  81423. enumerable: true,
  81424. configurable: true
  81425. });
  81426. /**
  81427. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  81428. */
  81429. WebVRController.prototype.update = function () {
  81430. _super.prototype.update.call(this);
  81431. for (var index = 0; index < this._buttons.length; index++) {
  81432. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  81433. }
  81434. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  81435. this.pad.x = this.leftStick.x;
  81436. this.pad.y = this.leftStick.y;
  81437. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  81438. }
  81439. };
  81440. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  81441. if (!newState) {
  81442. newState = {
  81443. pressed: false,
  81444. touched: false,
  81445. value: 0
  81446. };
  81447. }
  81448. if (!currentState) {
  81449. this._buttons[buttonIndex] = {
  81450. pressed: newState.pressed,
  81451. touched: newState.touched,
  81452. value: newState.value
  81453. };
  81454. return;
  81455. }
  81456. this._checkChanges(newState, currentState);
  81457. if (this._changes.changed) {
  81458. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  81459. this._handleButtonChange(buttonIndex, newState, this._changes);
  81460. }
  81461. this._buttons[buttonIndex].pressed = newState.pressed;
  81462. this._buttons[buttonIndex].touched = newState.touched;
  81463. // oculus triggers are never 0, thou not touched.
  81464. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  81465. };
  81466. WebVRController.prototype._checkChanges = function (newState, currentState) {
  81467. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  81468. this._changes.touchChanged = newState.touched !== currentState.touched;
  81469. this._changes.valueChanged = newState.value !== currentState.value;
  81470. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  81471. return this._changes;
  81472. };
  81473. /**
  81474. * Disposes of th webVRCOntroller
  81475. */
  81476. WebVRController.prototype.dispose = function () {
  81477. _super.prototype.dispose.call(this);
  81478. this.onTriggerStateChangedObservable.clear();
  81479. this.onMainButtonStateChangedObservable.clear();
  81480. this.onSecondaryButtonStateChangedObservable.clear();
  81481. this.onPadStateChangedObservable.clear();
  81482. this.onPadValuesChangedObservable.clear();
  81483. };
  81484. return WebVRController;
  81485. }(BABYLON.PoseEnabledController));
  81486. BABYLON.WebVRController = WebVRController;
  81487. })(BABYLON || (BABYLON = {}));
  81488. //# sourceMappingURL=babylon.webVRController.js.map
  81489. var BABYLON;
  81490. (function (BABYLON) {
  81491. /**
  81492. * Oculus Touch Controller
  81493. */
  81494. var OculusTouchController = /** @class */ (function (_super) {
  81495. __extends(OculusTouchController, _super);
  81496. /**
  81497. * Creates a new OculusTouchController from a gamepad
  81498. * @param vrGamepad the gamepad that the controller should be created from
  81499. */
  81500. function OculusTouchController(vrGamepad) {
  81501. var _this = _super.call(this, vrGamepad) || this;
  81502. /**
  81503. * Fired when the secondary trigger on this controller is modified
  81504. */
  81505. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  81506. /**
  81507. * Fired when the thumb rest on this controller is modified
  81508. */
  81509. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  81510. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  81511. return _this;
  81512. }
  81513. /**
  81514. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81515. * @param scene scene in which to add meshes
  81516. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81517. */
  81518. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81519. var _this = this;
  81520. var meshName;
  81521. // Hand
  81522. if (this.hand === 'left') {
  81523. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  81524. }
  81525. else { // Right is the default if no hand is specified
  81526. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  81527. }
  81528. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  81529. /*
  81530. Parent Mesh name: oculus_touch_left
  81531. - body
  81532. - trigger
  81533. - thumbstick
  81534. - grip
  81535. - button_y
  81536. - button_x
  81537. - button_enter
  81538. */
  81539. _this._defaultModel = newMeshes[1];
  81540. _this.attachToMesh(_this._defaultModel);
  81541. if (meshLoaded) {
  81542. meshLoaded(_this._defaultModel);
  81543. }
  81544. });
  81545. };
  81546. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  81547. /**
  81548. * Fired when the A button on this controller is modified
  81549. */
  81550. get: function () {
  81551. if (this.hand === 'right') {
  81552. return this.onMainButtonStateChangedObservable;
  81553. }
  81554. else {
  81555. throw new Error('No A button on left hand');
  81556. }
  81557. },
  81558. enumerable: true,
  81559. configurable: true
  81560. });
  81561. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  81562. /**
  81563. * Fired when the B button on this controller is modified
  81564. */
  81565. get: function () {
  81566. if (this.hand === 'right') {
  81567. return this.onSecondaryButtonStateChangedObservable;
  81568. }
  81569. else {
  81570. throw new Error('No B button on left hand');
  81571. }
  81572. },
  81573. enumerable: true,
  81574. configurable: true
  81575. });
  81576. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  81577. /**
  81578. * Fired when the X button on this controller is modified
  81579. */
  81580. get: function () {
  81581. if (this.hand === 'left') {
  81582. return this.onMainButtonStateChangedObservable;
  81583. }
  81584. else {
  81585. throw new Error('No X button on right hand');
  81586. }
  81587. },
  81588. enumerable: true,
  81589. configurable: true
  81590. });
  81591. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  81592. /**
  81593. * Fired when the Y button on this controller is modified
  81594. */
  81595. get: function () {
  81596. if (this.hand === 'left') {
  81597. return this.onSecondaryButtonStateChangedObservable;
  81598. }
  81599. else {
  81600. throw new Error('No Y button on right hand');
  81601. }
  81602. },
  81603. enumerable: true,
  81604. configurable: true
  81605. });
  81606. /**
  81607. * Called once for each button that changed state since the last frame
  81608. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  81609. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  81610. * 2) secondary trigger (same)
  81611. * 3) A (right) X (left), touch, pressed = value
  81612. * 4) B / Y
  81613. * 5) thumb rest
  81614. * @param buttonIdx Which button index changed
  81615. * @param state New state of the button
  81616. * @param changes Which properties on the state changed since last frame
  81617. */
  81618. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81619. var notifyObject = state; //{ state: state, changes: changes };
  81620. var triggerDirection = this.hand === 'right' ? -1 : 1;
  81621. switch (buttonIdx) {
  81622. case 0:
  81623. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81624. return;
  81625. case 1: // index trigger
  81626. if (this._defaultModel) {
  81627. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  81628. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  81629. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  81630. }
  81631. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81632. return;
  81633. case 2: // secondary trigger
  81634. if (this._defaultModel) {
  81635. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  81636. }
  81637. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  81638. return;
  81639. case 3:
  81640. if (this._defaultModel) {
  81641. if (notifyObject.pressed) {
  81642. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  81643. }
  81644. else {
  81645. (this._defaultModel.getChildren()[1]).position.y = 0;
  81646. }
  81647. }
  81648. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81649. return;
  81650. case 4:
  81651. if (this._defaultModel) {
  81652. if (notifyObject.pressed) {
  81653. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81654. }
  81655. else {
  81656. (this._defaultModel.getChildren()[2]).position.y = 0;
  81657. }
  81658. }
  81659. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81660. return;
  81661. case 5:
  81662. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  81663. return;
  81664. }
  81665. };
  81666. /**
  81667. * Base Url for the controller model.
  81668. */
  81669. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  81670. /**
  81671. * File name for the left controller model.
  81672. */
  81673. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  81674. /**
  81675. * File name for the right controller model.
  81676. */
  81677. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  81678. return OculusTouchController;
  81679. }(BABYLON.WebVRController));
  81680. BABYLON.OculusTouchController = OculusTouchController;
  81681. })(BABYLON || (BABYLON = {}));
  81682. //# sourceMappingURL=babylon.oculusTouchController.js.map
  81683. var BABYLON;
  81684. (function (BABYLON) {
  81685. /**
  81686. * Vive Controller
  81687. */
  81688. var ViveController = /** @class */ (function (_super) {
  81689. __extends(ViveController, _super);
  81690. /**
  81691. * Creates a new ViveController from a gamepad
  81692. * @param vrGamepad the gamepad that the controller should be created from
  81693. */
  81694. function ViveController(vrGamepad) {
  81695. var _this = _super.call(this, vrGamepad) || this;
  81696. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  81697. _this._invertLeftStickY = true;
  81698. return _this;
  81699. }
  81700. /**
  81701. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81702. * @param scene scene in which to add meshes
  81703. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81704. */
  81705. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81706. var _this = this;
  81707. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  81708. /*
  81709. Parent Mesh name: ViveWand
  81710. - body
  81711. - r_gripper
  81712. - l_gripper
  81713. - menu_button
  81714. - system_button
  81715. - trackpad
  81716. - trigger
  81717. - LED
  81718. */
  81719. _this._defaultModel = newMeshes[1];
  81720. _this.attachToMesh(_this._defaultModel);
  81721. if (meshLoaded) {
  81722. meshLoaded(_this._defaultModel);
  81723. }
  81724. });
  81725. };
  81726. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  81727. /**
  81728. * Fired when the left button on this controller is modified
  81729. */
  81730. get: function () {
  81731. return this.onMainButtonStateChangedObservable;
  81732. },
  81733. enumerable: true,
  81734. configurable: true
  81735. });
  81736. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  81737. /**
  81738. * Fired when the right button on this controller is modified
  81739. */
  81740. get: function () {
  81741. return this.onMainButtonStateChangedObservable;
  81742. },
  81743. enumerable: true,
  81744. configurable: true
  81745. });
  81746. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  81747. /**
  81748. * Fired when the menu button on this controller is modified
  81749. */
  81750. get: function () {
  81751. return this.onSecondaryButtonStateChangedObservable;
  81752. },
  81753. enumerable: true,
  81754. configurable: true
  81755. });
  81756. /**
  81757. * Called once for each button that changed state since the last frame
  81758. * Vive mapping:
  81759. * 0: touchpad
  81760. * 1: trigger
  81761. * 2: left AND right buttons
  81762. * 3: menu button
  81763. * @param buttonIdx Which button index changed
  81764. * @param state New state of the button
  81765. * @param changes Which properties on the state changed since last frame
  81766. */
  81767. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81768. var notifyObject = state; //{ state: state, changes: changes };
  81769. switch (buttonIdx) {
  81770. case 0:
  81771. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81772. return;
  81773. case 1: // index trigger
  81774. if (this._defaultModel) {
  81775. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  81776. }
  81777. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81778. return;
  81779. case 2: // left AND right button
  81780. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81781. return;
  81782. case 3:
  81783. if (this._defaultModel) {
  81784. if (notifyObject.pressed) {
  81785. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81786. }
  81787. else {
  81788. (this._defaultModel.getChildren()[2]).position.y = 0;
  81789. }
  81790. }
  81791. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81792. return;
  81793. }
  81794. };
  81795. /**
  81796. * Base Url for the controller model.
  81797. */
  81798. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  81799. /**
  81800. * File name for the controller model.
  81801. */
  81802. ViveController.MODEL_FILENAME = 'wand.babylon';
  81803. return ViveController;
  81804. }(BABYLON.WebVRController));
  81805. BABYLON.ViveController = ViveController;
  81806. })(BABYLON || (BABYLON = {}));
  81807. //# sourceMappingURL=babylon.viveController.js.map
  81808. var BABYLON;
  81809. (function (BABYLON) {
  81810. /**
  81811. * Generic Controller
  81812. */
  81813. var GenericController = /** @class */ (function (_super) {
  81814. __extends(GenericController, _super);
  81815. /**
  81816. * Creates a new GenericController from a gamepad
  81817. * @param vrGamepad the gamepad that the controller should be created from
  81818. */
  81819. function GenericController(vrGamepad) {
  81820. return _super.call(this, vrGamepad) || this;
  81821. }
  81822. /**
  81823. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81824. * @param scene scene in which to add meshes
  81825. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81826. */
  81827. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81828. var _this = this;
  81829. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  81830. _this._defaultModel = newMeshes[1];
  81831. _this.attachToMesh(_this._defaultModel);
  81832. if (meshLoaded) {
  81833. meshLoaded(_this._defaultModel);
  81834. }
  81835. });
  81836. };
  81837. /**
  81838. * Called once for each button that changed state since the last frame
  81839. * @param buttonIdx Which button index changed
  81840. * @param state New state of the button
  81841. * @param changes Which properties on the state changed since last frame
  81842. */
  81843. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81844. console.log("Button id: " + buttonIdx + "state: ");
  81845. console.dir(state);
  81846. };
  81847. /**
  81848. * Base Url for the controller model.
  81849. */
  81850. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81851. /**
  81852. * File name for the controller model.
  81853. */
  81854. GenericController.MODEL_FILENAME = 'generic.babylon';
  81855. return GenericController;
  81856. }(BABYLON.WebVRController));
  81857. BABYLON.GenericController = GenericController;
  81858. })(BABYLON || (BABYLON = {}));
  81859. //# sourceMappingURL=babylon.genericController.js.map
  81860. var BABYLON;
  81861. (function (BABYLON) {
  81862. /**
  81863. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  81864. */
  81865. var LoadedMeshInfo = /** @class */ (function () {
  81866. function LoadedMeshInfo() {
  81867. /**
  81868. * Map of the button meshes contained in the controller
  81869. */
  81870. this.buttonMeshes = {};
  81871. /**
  81872. * Map of the axis meshes contained in the controller
  81873. */
  81874. this.axisMeshes = {};
  81875. }
  81876. return LoadedMeshInfo;
  81877. }());
  81878. /**
  81879. * Defines the WindowsMotionController object that the state of the windows motion controller
  81880. */
  81881. var WindowsMotionController = /** @class */ (function (_super) {
  81882. __extends(WindowsMotionController, _super);
  81883. /**
  81884. * Creates a new WindowsMotionController from a gamepad
  81885. * @param vrGamepad the gamepad that the controller should be created from
  81886. */
  81887. function WindowsMotionController(vrGamepad) {
  81888. var _this = _super.call(this, vrGamepad) || this;
  81889. _this._mapping = {
  81890. // Semantic button names
  81891. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  81892. // A mapping of the button name to glTF model node name
  81893. // that should be transformed by button value.
  81894. buttonMeshNames: {
  81895. 'trigger': 'SELECT',
  81896. 'menu': 'MENU',
  81897. 'grip': 'GRASP',
  81898. 'thumbstick': 'THUMBSTICK_PRESS',
  81899. 'trackpad': 'TOUCHPAD_PRESS'
  81900. },
  81901. // This mapping is used to translate from the Motion Controller to Babylon semantics
  81902. buttonObservableNames: {
  81903. 'trigger': 'onTriggerStateChangedObservable',
  81904. 'menu': 'onSecondaryButtonStateChangedObservable',
  81905. 'grip': 'onMainButtonStateChangedObservable',
  81906. 'thumbstick': 'onPadStateChangedObservable',
  81907. 'trackpad': 'onTrackpadChangedObservable'
  81908. },
  81909. // A mapping of the axis name to glTF model node name
  81910. // that should be transformed by axis value.
  81911. // This array mirrors the browserGamepad.axes array, such that
  81912. // the mesh corresponding to axis 0 is in this array index 0.
  81913. axisMeshNames: [
  81914. 'THUMBSTICK_X',
  81915. 'THUMBSTICK_Y',
  81916. 'TOUCHPAD_TOUCH_X',
  81917. 'TOUCHPAD_TOUCH_Y'
  81918. ],
  81919. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  81920. };
  81921. /**
  81922. * Fired when the trackpad on this controller is clicked
  81923. */
  81924. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  81925. /**
  81926. * Fired when the trackpad on this controller is modified
  81927. */
  81928. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  81929. /**
  81930. * The current x and y values of this controller's trackpad
  81931. */
  81932. _this.trackpad = { x: 0, y: 0 };
  81933. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  81934. _this._loadedMeshInfo = null;
  81935. return _this;
  81936. }
  81937. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  81938. /**
  81939. * Fired when the trigger on this controller is modified
  81940. */
  81941. get: function () {
  81942. return this.onTriggerStateChangedObservable;
  81943. },
  81944. enumerable: true,
  81945. configurable: true
  81946. });
  81947. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  81948. /**
  81949. * Fired when the menu button on this controller is modified
  81950. */
  81951. get: function () {
  81952. return this.onSecondaryButtonStateChangedObservable;
  81953. },
  81954. enumerable: true,
  81955. configurable: true
  81956. });
  81957. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  81958. /**
  81959. * Fired when the grip button on this controller is modified
  81960. */
  81961. get: function () {
  81962. return this.onMainButtonStateChangedObservable;
  81963. },
  81964. enumerable: true,
  81965. configurable: true
  81966. });
  81967. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  81968. /**
  81969. * Fired when the thumbstick button on this controller is modified
  81970. */
  81971. get: function () {
  81972. return this.onPadStateChangedObservable;
  81973. },
  81974. enumerable: true,
  81975. configurable: true
  81976. });
  81977. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  81978. /**
  81979. * Fired when the touchpad button on this controller is modified
  81980. */
  81981. get: function () {
  81982. return this.onTrackpadChangedObservable;
  81983. },
  81984. enumerable: true,
  81985. configurable: true
  81986. });
  81987. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  81988. /**
  81989. * Fired when the touchpad values on this controller are modified
  81990. */
  81991. get: function () {
  81992. return this.onTrackpadValuesChangedObservable;
  81993. },
  81994. enumerable: true,
  81995. configurable: true
  81996. });
  81997. WindowsMotionController.prototype._updateTrackpad = function () {
  81998. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  81999. this.trackpad.x = this.browserGamepad["axes"][2];
  82000. this.trackpad.y = this.browserGamepad["axes"][3];
  82001. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  82002. }
  82003. };
  82004. /**
  82005. * Called once per frame by the engine.
  82006. */
  82007. WindowsMotionController.prototype.update = function () {
  82008. _super.prototype.update.call(this);
  82009. if (this.browserGamepad.axes) {
  82010. this._updateTrackpad();
  82011. // Only need to animate axes if there is a loaded mesh
  82012. if (this._loadedMeshInfo) {
  82013. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  82014. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  82015. }
  82016. }
  82017. }
  82018. };
  82019. /**
  82020. * Called once for each button that changed state since the last frame
  82021. * @param buttonIdx Which button index changed
  82022. * @param state New state of the button
  82023. * @param changes Which properties on the state changed since last frame
  82024. */
  82025. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82026. var buttonName = this._mapping.buttons[buttonIdx];
  82027. if (!buttonName) {
  82028. return;
  82029. }
  82030. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  82031. this._updateTrackpad();
  82032. // Only emit events for buttons that we know how to map from index to name
  82033. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  82034. if (observable) {
  82035. observable.notifyObservers(state);
  82036. }
  82037. this._lerpButtonTransform(buttonName, state.value);
  82038. };
  82039. /**
  82040. * Moves the buttons on the controller mesh based on their current state
  82041. * @param buttonName the name of the button to move
  82042. * @param buttonValue the value of the button which determines the buttons new position
  82043. */
  82044. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  82045. // If there is no loaded mesh, there is nothing to transform.
  82046. if (!this._loadedMeshInfo) {
  82047. return;
  82048. }
  82049. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  82050. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  82051. return;
  82052. }
  82053. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  82054. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  82055. };
  82056. /**
  82057. * Moves the axis on the controller mesh based on its current state
  82058. * @param axis the index of the axis
  82059. * @param axisValue the value of the axis which determines the meshes new position
  82060. * @hidden
  82061. */
  82062. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  82063. if (!this._loadedMeshInfo) {
  82064. return;
  82065. }
  82066. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  82067. if (!meshInfo) {
  82068. return;
  82069. }
  82070. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  82071. return;
  82072. }
  82073. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  82074. var lerpValue = axisValue * 0.5 + 0.5;
  82075. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  82076. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  82077. };
  82078. /**
  82079. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82080. * @param scene scene in which to add meshes
  82081. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82082. */
  82083. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  82084. var _this = this;
  82085. if (forceDefault === void 0) { forceDefault = false; }
  82086. var path;
  82087. var filename;
  82088. // Checking if GLB loader is present
  82089. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  82090. // Determine the device specific folder based on the ID suffix
  82091. var device = 'default';
  82092. if (this.id && !forceDefault) {
  82093. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  82094. device = ((match && match[0]) || device);
  82095. }
  82096. // Hand
  82097. if (this.hand === 'left') {
  82098. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  82099. }
  82100. else { // Right is the default if no hand is specified
  82101. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  82102. }
  82103. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  82104. }
  82105. else {
  82106. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  82107. path = BABYLON.GenericController.MODEL_BASE_URL;
  82108. filename = BABYLON.GenericController.MODEL_FILENAME;
  82109. }
  82110. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  82111. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  82112. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  82113. if (!_this._loadedMeshInfo) {
  82114. return;
  82115. }
  82116. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  82117. _this.attachToMesh(_this._defaultModel);
  82118. if (meshLoaded) {
  82119. meshLoaded(_this._defaultModel);
  82120. }
  82121. }, null, function (scene, message) {
  82122. BABYLON.Tools.Log(message);
  82123. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  82124. if (!forceDefault) {
  82125. _this.initControllerMesh(scene, meshLoaded, true);
  82126. }
  82127. });
  82128. };
  82129. /**
  82130. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  82131. * can be transformed by button presses and axes values, based on this._mapping.
  82132. *
  82133. * @param scene scene in which the meshes exist
  82134. * @param meshes list of meshes that make up the controller model to process
  82135. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  82136. */
  82137. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  82138. var loadedMeshInfo = null;
  82139. // Create a new mesh to contain the glTF hierarchy
  82140. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  82141. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  82142. var childMesh = null;
  82143. for (var i = 0; i < meshes.length; i++) {
  82144. var mesh = meshes[i];
  82145. if (!mesh.parent) {
  82146. // Exclude controller meshes from picking results
  82147. mesh.isPickable = false;
  82148. // Handle root node, attach to the new parentMesh
  82149. childMesh = mesh;
  82150. break;
  82151. }
  82152. }
  82153. if (childMesh) {
  82154. childMesh.setParent(parentMesh);
  82155. // Create our mesh info. Note that this method will always return non-null.
  82156. loadedMeshInfo = this.createMeshInfo(parentMesh);
  82157. }
  82158. else {
  82159. BABYLON.Tools.Warn('Could not find root node in model file.');
  82160. }
  82161. return loadedMeshInfo;
  82162. };
  82163. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  82164. var loadedMeshInfo = new LoadedMeshInfo();
  82165. var i;
  82166. loadedMeshInfo.rootNode = rootNode;
  82167. // Reset the caches
  82168. loadedMeshInfo.buttonMeshes = {};
  82169. loadedMeshInfo.axisMeshes = {};
  82170. // Button Meshes
  82171. for (i = 0; i < this._mapping.buttons.length; i++) {
  82172. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  82173. if (!buttonMeshName) {
  82174. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  82175. continue;
  82176. }
  82177. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  82178. if (!buttonMesh) {
  82179. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  82180. continue;
  82181. }
  82182. var buttonMeshInfo = {
  82183. index: i,
  82184. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  82185. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  82186. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  82187. };
  82188. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  82189. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  82190. }
  82191. else {
  82192. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  82193. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  82194. '(VALUE: ' + !!buttonMeshInfo.value +
  82195. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  82196. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  82197. ')');
  82198. }
  82199. }
  82200. // Axis Meshes
  82201. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  82202. var axisMeshName = this._mapping.axisMeshNames[i];
  82203. if (!axisMeshName) {
  82204. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  82205. continue;
  82206. }
  82207. var axisMesh = getChildByName(rootNode, axisMeshName);
  82208. if (!axisMesh) {
  82209. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  82210. continue;
  82211. }
  82212. var axisMeshInfo = {
  82213. index: i,
  82214. value: getImmediateChildByName(axisMesh, 'VALUE'),
  82215. min: getImmediateChildByName(axisMesh, 'MIN'),
  82216. max: getImmediateChildByName(axisMesh, 'MAX')
  82217. };
  82218. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  82219. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  82220. }
  82221. else {
  82222. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  82223. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  82224. '(VALUE: ' + !!axisMeshInfo.value +
  82225. ', MIN: ' + !!axisMeshInfo.min +
  82226. ', MAX:' + !!axisMeshInfo.max +
  82227. ')');
  82228. }
  82229. }
  82230. // Pointing Ray
  82231. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  82232. if (!loadedMeshInfo.pointingPoseNode) {
  82233. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  82234. }
  82235. else {
  82236. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  82237. }
  82238. return loadedMeshInfo;
  82239. // Look through all children recursively. This will return null if no mesh exists with the given name.
  82240. function getChildByName(node, name) {
  82241. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  82242. }
  82243. // Look through only immediate children. This will return null if no mesh exists with the given name.
  82244. function getImmediateChildByName(node, name) {
  82245. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  82246. }
  82247. };
  82248. /**
  82249. * Gets the ray of the controller in the direction the controller is pointing
  82250. * @param length the length the resulting ray should be
  82251. * @returns a ray in the direction the controller is pointing
  82252. */
  82253. WindowsMotionController.prototype.getForwardRay = function (length) {
  82254. if (length === void 0) { length = 100; }
  82255. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  82256. return _super.prototype.getForwardRay.call(this, length);
  82257. }
  82258. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  82259. var origin = m.getTranslation();
  82260. var forward = new BABYLON.Vector3(0, 0, -1);
  82261. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82262. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82263. return new BABYLON.Ray(origin, direction, length);
  82264. };
  82265. /**
  82266. * Disposes of the controller
  82267. */
  82268. WindowsMotionController.prototype.dispose = function () {
  82269. _super.prototype.dispose.call(this);
  82270. this.onTrackpadChangedObservable.clear();
  82271. };
  82272. /**
  82273. * The base url used to load the left and right controller models
  82274. */
  82275. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  82276. /**
  82277. * The name of the left controller model file
  82278. */
  82279. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  82280. /**
  82281. * The name of the right controller model file
  82282. */
  82283. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  82284. /**
  82285. * The controller name prefix for this controller type
  82286. */
  82287. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  82288. /**
  82289. * The controller id pattern for this controller type
  82290. */
  82291. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  82292. return WindowsMotionController;
  82293. }(BABYLON.WebVRController));
  82294. BABYLON.WindowsMotionController = WindowsMotionController;
  82295. })(BABYLON || (BABYLON = {}));
  82296. //# sourceMappingURL=babylon.windowsMotionController.js.map
  82297. var BABYLON;
  82298. (function (BABYLON) {
  82299. /**
  82300. * Gear VR Controller
  82301. */
  82302. var GearVRController = /** @class */ (function (_super) {
  82303. __extends(GearVRController, _super);
  82304. /**
  82305. * Creates a new GearVRController from a gamepad
  82306. * @param vrGamepad the gamepad that the controller should be created from
  82307. */
  82308. function GearVRController(vrGamepad) {
  82309. var _this = _super.call(this, vrGamepad) || this;
  82310. _this._buttonIndexToObservableNameMap = [
  82311. 'onTrackpadChangedObservable',
  82312. 'onTriggerStateChangedObservable' // Trigger
  82313. ];
  82314. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  82315. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  82316. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  82317. _this._disableTrackPosition(_this._calculatedPosition);
  82318. return _this;
  82319. }
  82320. /**
  82321. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82322. * @param scene scene in which to add meshes
  82323. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82324. */
  82325. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82326. var _this = this;
  82327. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  82328. // Offset the controller so it will rotate around the users wrist
  82329. var mesh = new BABYLON.Mesh("", scene);
  82330. newMeshes[1].parent = mesh;
  82331. newMeshes[1].position.z = -0.15;
  82332. _this._defaultModel = mesh;
  82333. _this.attachToMesh(_this._defaultModel);
  82334. if (meshLoaded) {
  82335. meshLoaded(_this._defaultModel);
  82336. }
  82337. });
  82338. };
  82339. /**
  82340. * Called once for each button that changed state since the last frame
  82341. * @param buttonIdx Which button index changed
  82342. * @param state New state of the button
  82343. * @param changes Which properties on the state changed since last frame
  82344. */
  82345. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82346. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  82347. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  82348. // Only emit events for buttons that we know how to map from index to observable
  82349. var observable = this[observableName];
  82350. if (observable) {
  82351. observable.notifyObservers(state);
  82352. }
  82353. }
  82354. };
  82355. /**
  82356. * Base Url for the controller model.
  82357. */
  82358. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82359. /**
  82360. * File name for the controller model.
  82361. */
  82362. GearVRController.MODEL_FILENAME = 'generic.babylon';
  82363. /**
  82364. * Gamepad Id prefix used to identify this controller.
  82365. */
  82366. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  82367. return GearVRController;
  82368. }(BABYLON.WebVRController));
  82369. BABYLON.GearVRController = GearVRController;
  82370. })(BABYLON || (BABYLON = {}));
  82371. //# sourceMappingURL=babylon.gearVRController.js.map
  82372. var BABYLON;
  82373. (function (BABYLON) {
  82374. /**
  82375. * Google Daydream controller
  82376. */
  82377. var DaydreamController = /** @class */ (function (_super) {
  82378. __extends(DaydreamController, _super);
  82379. /**
  82380. * Creates a new DaydreamController from a gamepad
  82381. * @param vrGamepad the gamepad that the controller should be created from
  82382. */
  82383. function DaydreamController(vrGamepad) {
  82384. var _this = _super.call(this, vrGamepad) || this;
  82385. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  82386. return _this;
  82387. }
  82388. /**
  82389. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82390. * @param scene scene in which to add meshes
  82391. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82392. */
  82393. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82394. var _this = this;
  82395. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  82396. _this._defaultModel = newMeshes[1];
  82397. _this.attachToMesh(_this._defaultModel);
  82398. if (meshLoaded) {
  82399. meshLoaded(_this._defaultModel);
  82400. }
  82401. });
  82402. };
  82403. /**
  82404. * Called once for each button that changed state since the last frame
  82405. * @param buttonIdx Which button index changed
  82406. * @param state New state of the button
  82407. * @param changes Which properties on the state changed since last frame
  82408. */
  82409. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82410. // Daydream controller only has 1 GamepadButton (on the trackpad).
  82411. if (buttonIdx === 0) {
  82412. var observable = this.onTriggerStateChangedObservable;
  82413. if (observable) {
  82414. observable.notifyObservers(state);
  82415. }
  82416. }
  82417. else {
  82418. // If the app or home buttons are ever made available
  82419. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  82420. }
  82421. };
  82422. /**
  82423. * Base Url for the controller model.
  82424. */
  82425. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82426. /**
  82427. * File name for the controller model.
  82428. */
  82429. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  82430. /**
  82431. * Gamepad Id prefix used to identify Daydream Controller.
  82432. */
  82433. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  82434. return DaydreamController;
  82435. }(BABYLON.WebVRController));
  82436. BABYLON.DaydreamController = DaydreamController;
  82437. })(BABYLON || (BABYLON = {}));
  82438. //# sourceMappingURL=babylon.daydreamController.js.map
  82439. var BABYLON;
  82440. (function (BABYLON) {
  82441. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  82442. get: function () {
  82443. if (!this._gamepadManager) {
  82444. this._gamepadManager = new BABYLON.GamepadManager(this);
  82445. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  82446. if (!component) {
  82447. component = new GamepadSystemSceneComponent(this);
  82448. this._addComponent(component);
  82449. }
  82450. }
  82451. return this._gamepadManager;
  82452. },
  82453. enumerable: true,
  82454. configurable: true
  82455. });
  82456. /**
  82457. * Adds a gamepad to the free camera inputs manager
  82458. */
  82459. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  82460. this.add(new BABYLON.FreeCameraGamepadInput());
  82461. return this;
  82462. };
  82463. /**
  82464. * Adds a gamepad to the arc rotate camera inputs manager
  82465. */
  82466. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  82467. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  82468. return this;
  82469. };
  82470. /**
  82471. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  82472. */
  82473. var GamepadSystemSceneComponent = /** @class */ (function () {
  82474. /**
  82475. * Creates a new instance of the component for the given scene
  82476. * @param scene Defines the scene to register the component in
  82477. */
  82478. function GamepadSystemSceneComponent(scene) {
  82479. /**
  82480. * The component name helpfull to identify the component in the list of scene components.
  82481. */
  82482. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  82483. this.scene = scene;
  82484. }
  82485. /**
  82486. * Registers the component in a given scene
  82487. */
  82488. GamepadSystemSceneComponent.prototype.register = function () {
  82489. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  82490. };
  82491. /**
  82492. * Rebuilds the elements related to this component in case of
  82493. * context lost for instance.
  82494. */
  82495. GamepadSystemSceneComponent.prototype.rebuild = function () {
  82496. // Nothing to do for gamepads
  82497. };
  82498. /**
  82499. * Disposes the component and the associated ressources
  82500. */
  82501. GamepadSystemSceneComponent.prototype.dispose = function () {
  82502. var gamepadManager = this.scene._gamepadManager;
  82503. if (gamepadManager) {
  82504. gamepadManager.dispose();
  82505. this.scene._gamepadManager = null;
  82506. }
  82507. };
  82508. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  82509. var gamepadManager = this.scene._gamepadManager;
  82510. if (gamepadManager && gamepadManager._isMonitoring) {
  82511. gamepadManager._checkGamepadsStatus();
  82512. }
  82513. };
  82514. return GamepadSystemSceneComponent;
  82515. }());
  82516. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  82517. })(BABYLON || (BABYLON = {}));
  82518. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  82519. var BABYLON;
  82520. (function (BABYLON) {
  82521. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  82522. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  82523. });
  82524. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  82525. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  82526. });
  82527. /**
  82528. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  82529. * an arc rotate version arcFollowCamera are available.
  82530. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82531. */
  82532. var FollowCamera = /** @class */ (function (_super) {
  82533. __extends(FollowCamera, _super);
  82534. /**
  82535. * Instantiates the follow camera.
  82536. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82537. * @param name Define the name of the camera in the scene
  82538. * @param position Define the position of the camera
  82539. * @param scene Define the scene the camera belong to
  82540. * @param lockedTarget Define the target of the camera
  82541. */
  82542. function FollowCamera(name, position, scene, lockedTarget) {
  82543. if (lockedTarget === void 0) { lockedTarget = null; }
  82544. var _this = _super.call(this, name, position, scene) || this;
  82545. /**
  82546. * Distance the follow camera should follow an object at
  82547. */
  82548. _this.radius = 12;
  82549. /**
  82550. * Define a rotation offset between the camera and the object it follows
  82551. */
  82552. _this.rotationOffset = 0;
  82553. /**
  82554. * Define a height offset between the camera and the object it follows.
  82555. * It can help following an object from the top (like a car chaing a plane)
  82556. */
  82557. _this.heightOffset = 4;
  82558. /**
  82559. * Define how fast the camera can accelerate to follow it s target.
  82560. */
  82561. _this.cameraAcceleration = 0.05;
  82562. /**
  82563. * Define the speed limit of the camera following an object.
  82564. */
  82565. _this.maxCameraSpeed = 20;
  82566. _this.lockedTarget = lockedTarget;
  82567. return _this;
  82568. }
  82569. FollowCamera.prototype._follow = function (cameraTarget) {
  82570. if (!cameraTarget) {
  82571. return;
  82572. }
  82573. var yRotation;
  82574. if (cameraTarget.rotationQuaternion) {
  82575. var rotMatrix = new BABYLON.Matrix();
  82576. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  82577. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  82578. }
  82579. else {
  82580. yRotation = cameraTarget.rotation.y;
  82581. }
  82582. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  82583. var targetPosition = cameraTarget.getAbsolutePosition();
  82584. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  82585. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  82586. var dx = targetX - this.position.x;
  82587. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  82588. var dz = (targetZ) - this.position.z;
  82589. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  82590. var vy = dy * this.cameraAcceleration;
  82591. var vz = dz * this.cameraAcceleration * 2;
  82592. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  82593. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82594. }
  82595. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  82596. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82597. }
  82598. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  82599. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82600. }
  82601. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  82602. this.setTarget(targetPosition);
  82603. };
  82604. /** @hidden */
  82605. FollowCamera.prototype._checkInputs = function () {
  82606. _super.prototype._checkInputs.call(this);
  82607. if (this.lockedTarget) {
  82608. this._follow(this.lockedTarget);
  82609. }
  82610. };
  82611. /**
  82612. * Gets the camera class name.
  82613. * @returns the class name
  82614. */
  82615. FollowCamera.prototype.getClassName = function () {
  82616. return "FollowCamera";
  82617. };
  82618. __decorate([
  82619. BABYLON.serialize()
  82620. ], FollowCamera.prototype, "radius", void 0);
  82621. __decorate([
  82622. BABYLON.serialize()
  82623. ], FollowCamera.prototype, "rotationOffset", void 0);
  82624. __decorate([
  82625. BABYLON.serialize()
  82626. ], FollowCamera.prototype, "heightOffset", void 0);
  82627. __decorate([
  82628. BABYLON.serialize()
  82629. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  82630. __decorate([
  82631. BABYLON.serialize()
  82632. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  82633. __decorate([
  82634. BABYLON.serializeAsMeshReference("lockedTargetId")
  82635. ], FollowCamera.prototype, "lockedTarget", void 0);
  82636. return FollowCamera;
  82637. }(BABYLON.TargetCamera));
  82638. BABYLON.FollowCamera = FollowCamera;
  82639. /**
  82640. * Arc Rotate version of the follow camera.
  82641. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  82642. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82643. */
  82644. var ArcFollowCamera = /** @class */ (function (_super) {
  82645. __extends(ArcFollowCamera, _super);
  82646. /**
  82647. * Instantiates a new ArcFollowCamera
  82648. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82649. * @param name Define the name of the camera
  82650. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  82651. * @param beta Define the rotation angle of the camera around the elevation axis
  82652. * @param radius Define the radius of the camera from its target point
  82653. * @param target Define the target of the camera
  82654. * @param scene Define the scene the camera belongs to
  82655. */
  82656. function ArcFollowCamera(name,
  82657. /** The longitudinal angle of the camera */
  82658. alpha,
  82659. /** The latitudinal angle of the camera */
  82660. beta,
  82661. /** The radius of the camera from its target */
  82662. radius,
  82663. /** Define the camera target (the messh it should follow) */
  82664. target, scene) {
  82665. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  82666. _this.alpha = alpha;
  82667. _this.beta = beta;
  82668. _this.radius = radius;
  82669. _this.target = target;
  82670. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  82671. _this._follow();
  82672. return _this;
  82673. }
  82674. ArcFollowCamera.prototype._follow = function () {
  82675. if (!this.target) {
  82676. return;
  82677. }
  82678. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  82679. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  82680. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  82681. var targetPosition = this.target.getAbsolutePosition();
  82682. this.position = targetPosition.add(this._cartesianCoordinates);
  82683. this.setTarget(targetPosition);
  82684. };
  82685. /** @hidden */
  82686. ArcFollowCamera.prototype._checkInputs = function () {
  82687. _super.prototype._checkInputs.call(this);
  82688. this._follow();
  82689. };
  82690. /**
  82691. * Returns the class name of the object.
  82692. * It is mostly used internally for serialization purposes.
  82693. */
  82694. ArcFollowCamera.prototype.getClassName = function () {
  82695. return "ArcFollowCamera";
  82696. };
  82697. return ArcFollowCamera;
  82698. }(BABYLON.TargetCamera));
  82699. BABYLON.ArcFollowCamera = ArcFollowCamera;
  82700. })(BABYLON || (BABYLON = {}));
  82701. //# sourceMappingURL=babylon.followCamera.js.map
  82702. var BABYLON;
  82703. (function (BABYLON) {
  82704. /**
  82705. * 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,
  82706. * which still works and will still be found in many Playgrounds.
  82707. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82708. */
  82709. var UniversalCamera = /** @class */ (function (_super) {
  82710. __extends(UniversalCamera, _super);
  82711. /**
  82712. * 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,
  82713. * which still works and will still be found in many Playgrounds.
  82714. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82715. * @param name Define the name of the camera in the scene
  82716. * @param position Define the start position of the camera in the scene
  82717. * @param scene Define the scene the camera belongs to
  82718. */
  82719. function UniversalCamera(name, position, scene) {
  82720. var _this = _super.call(this, name, position, scene) || this;
  82721. _this.inputs.addGamepad();
  82722. return _this;
  82723. }
  82724. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  82725. /**
  82726. * Defines the gamepad rotation sensiblity.
  82727. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  82728. */
  82729. get: function () {
  82730. var gamepad = this.inputs.attached["gamepad"];
  82731. if (gamepad) {
  82732. return gamepad.gamepadAngularSensibility;
  82733. }
  82734. return 0;
  82735. },
  82736. set: function (value) {
  82737. var gamepad = this.inputs.attached["gamepad"];
  82738. if (gamepad) {
  82739. gamepad.gamepadAngularSensibility = value;
  82740. }
  82741. },
  82742. enumerable: true,
  82743. configurable: true
  82744. });
  82745. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  82746. /**
  82747. * Defines the gamepad move sensiblity.
  82748. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  82749. */
  82750. get: function () {
  82751. var gamepad = this.inputs.attached["gamepad"];
  82752. if (gamepad) {
  82753. return gamepad.gamepadMoveSensibility;
  82754. }
  82755. return 0;
  82756. },
  82757. set: function (value) {
  82758. var gamepad = this.inputs.attached["gamepad"];
  82759. if (gamepad) {
  82760. gamepad.gamepadMoveSensibility = value;
  82761. }
  82762. },
  82763. enumerable: true,
  82764. configurable: true
  82765. });
  82766. /**
  82767. * Gets the current object class name.
  82768. * @return the class name
  82769. */
  82770. UniversalCamera.prototype.getClassName = function () {
  82771. return "UniversalCamera";
  82772. };
  82773. return UniversalCamera;
  82774. }(BABYLON.TouchCamera));
  82775. BABYLON.UniversalCamera = UniversalCamera;
  82776. })(BABYLON || (BABYLON = {}));
  82777. //# sourceMappingURL=babylon.universalCamera.js.map
  82778. var BABYLON;
  82779. (function (BABYLON) {
  82780. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  82781. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  82782. });
  82783. /**
  82784. * This represents a FPS type of camera. This is only here for back compat purpose.
  82785. * Please use the UniversalCamera instead as both are identical.
  82786. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82787. */
  82788. var GamepadCamera = /** @class */ (function (_super) {
  82789. __extends(GamepadCamera, _super);
  82790. /**
  82791. * Instantiates a new Gamepad Camera
  82792. * This represents a FPS type of camera. This is only here for back compat purpose.
  82793. * Please use the UniversalCamera instead as both are identical.
  82794. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82795. * @param name Define the name of the camera in the scene
  82796. * @param position Define the start position of the camera in the scene
  82797. * @param scene Define the scene the camera belongs to
  82798. */
  82799. function GamepadCamera(name, position, scene) {
  82800. return _super.call(this, name, position, scene) || this;
  82801. }
  82802. /**
  82803. * Gets the current object class name.
  82804. * @return the class name
  82805. */
  82806. GamepadCamera.prototype.getClassName = function () {
  82807. return "GamepadCamera";
  82808. };
  82809. return GamepadCamera;
  82810. }(BABYLON.UniversalCamera));
  82811. BABYLON.GamepadCamera = GamepadCamera;
  82812. })(BABYLON || (BABYLON = {}));
  82813. //# sourceMappingURL=babylon.gamepadCamera.js.map
  82814. var BABYLON;
  82815. (function (BABYLON) {
  82816. /**
  82817. * PostProcessRenderPipelineManager class
  82818. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82819. */
  82820. var PostProcessRenderPipelineManager = /** @class */ (function () {
  82821. /**
  82822. * Initializes a PostProcessRenderPipelineManager
  82823. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82824. */
  82825. function PostProcessRenderPipelineManager() {
  82826. this._renderPipelines = {};
  82827. }
  82828. /**
  82829. * Adds a pipeline to the manager
  82830. * @param renderPipeline The pipeline to add
  82831. */
  82832. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  82833. this._renderPipelines[renderPipeline._name] = renderPipeline;
  82834. };
  82835. /**
  82836. * Attaches a camera to the pipeline
  82837. * @param renderPipelineName The name of the pipeline to attach to
  82838. * @param cameras the camera to attach
  82839. * @param unique if the camera can be attached multiple times to the pipeline
  82840. */
  82841. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  82842. if (unique === void 0) { unique = false; }
  82843. var renderPipeline = this._renderPipelines[renderPipelineName];
  82844. if (!renderPipeline) {
  82845. return;
  82846. }
  82847. renderPipeline._attachCameras(cameras, unique);
  82848. };
  82849. /**
  82850. * Detaches a camera from the pipeline
  82851. * @param renderPipelineName The name of the pipeline to detach from
  82852. * @param cameras the camera to detach
  82853. */
  82854. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  82855. var renderPipeline = this._renderPipelines[renderPipelineName];
  82856. if (!renderPipeline) {
  82857. return;
  82858. }
  82859. renderPipeline._detachCameras(cameras);
  82860. };
  82861. /**
  82862. * Enables an effect by name on a pipeline
  82863. * @param renderPipelineName the name of the pipeline to enable the effect in
  82864. * @param renderEffectName the name of the effect to enable
  82865. * @param cameras the cameras that the effect should be enabled on
  82866. */
  82867. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82868. var renderPipeline = this._renderPipelines[renderPipelineName];
  82869. if (!renderPipeline) {
  82870. return;
  82871. }
  82872. renderPipeline._enableEffect(renderEffectName, cameras);
  82873. };
  82874. /**
  82875. * Disables an effect by name on a pipeline
  82876. * @param renderPipelineName the name of the pipeline to disable the effect in
  82877. * @param renderEffectName the name of the effect to disable
  82878. * @param cameras the cameras that the effect should be disabled on
  82879. */
  82880. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82881. var renderPipeline = this._renderPipelines[renderPipelineName];
  82882. if (!renderPipeline) {
  82883. return;
  82884. }
  82885. renderPipeline._disableEffect(renderEffectName, cameras);
  82886. };
  82887. /**
  82888. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  82889. */
  82890. PostProcessRenderPipelineManager.prototype.update = function () {
  82891. for (var renderPipelineName in this._renderPipelines) {
  82892. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82893. var pipeline = this._renderPipelines[renderPipelineName];
  82894. if (!pipeline.isSupported) {
  82895. pipeline.dispose();
  82896. delete this._renderPipelines[renderPipelineName];
  82897. }
  82898. else {
  82899. pipeline._update();
  82900. }
  82901. }
  82902. }
  82903. };
  82904. /** @hidden */
  82905. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  82906. for (var renderPipelineName in this._renderPipelines) {
  82907. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82908. var pipeline = this._renderPipelines[renderPipelineName];
  82909. pipeline._rebuild();
  82910. }
  82911. }
  82912. };
  82913. /**
  82914. * Disposes of the manager and pipelines
  82915. */
  82916. PostProcessRenderPipelineManager.prototype.dispose = function () {
  82917. for (var renderPipelineName in this._renderPipelines) {
  82918. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82919. var pipeline = this._renderPipelines[renderPipelineName];
  82920. pipeline.dispose();
  82921. }
  82922. }
  82923. };
  82924. return PostProcessRenderPipelineManager;
  82925. }());
  82926. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  82927. })(BABYLON || (BABYLON = {}));
  82928. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  82929. var BABYLON;
  82930. (function (BABYLON) {
  82931. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  82932. get: function () {
  82933. if (!this._postProcessRenderPipelineManager) {
  82934. // Register the G Buffer component to the scene.
  82935. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  82936. if (!component) {
  82937. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  82938. this._addComponent(component);
  82939. }
  82940. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  82941. }
  82942. return this._postProcessRenderPipelineManager;
  82943. },
  82944. enumerable: true,
  82945. configurable: true
  82946. });
  82947. /**
  82948. * Defines the Render Pipeline scene component responsible to rendering pipelines
  82949. */
  82950. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  82951. /**
  82952. * Creates a new instance of the component for the given scene
  82953. * @param scene Defines the scene to register the component in
  82954. */
  82955. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  82956. /**
  82957. * The component name helpfull to identify the component in the list of scene components.
  82958. */
  82959. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  82960. this.scene = scene;
  82961. }
  82962. /**
  82963. * Registers the component in a given scene
  82964. */
  82965. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  82966. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  82967. };
  82968. /**
  82969. * Rebuilds the elements related to this component in case of
  82970. * context lost for instance.
  82971. */
  82972. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  82973. if (this.scene._postProcessRenderPipelineManager) {
  82974. this.scene._postProcessRenderPipelineManager._rebuild();
  82975. }
  82976. };
  82977. /**
  82978. * Disposes the component and the associated ressources
  82979. */
  82980. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  82981. if (this.scene._postProcessRenderPipelineManager) {
  82982. this.scene._postProcessRenderPipelineManager.dispose();
  82983. }
  82984. };
  82985. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82986. if (this.scene._postProcessRenderPipelineManager) {
  82987. this.scene._postProcessRenderPipelineManager.update();
  82988. }
  82989. };
  82990. return PostProcessRenderPipelineManagerSceneComponent;
  82991. }());
  82992. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  82993. })(BABYLON || (BABYLON = {}));
  82994. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  82995. var BABYLON;
  82996. (function (BABYLON) {
  82997. /**
  82998. * This represents a set of one or more post processes in Babylon.
  82999. * A post process can be used to apply a shader to a texture after it is rendered.
  83000. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83001. */
  83002. var PostProcessRenderEffect = /** @class */ (function () {
  83003. /**
  83004. * Instantiates a post process render effect.
  83005. * A post process can be used to apply a shader to a texture after it is rendered.
  83006. * @param engine The engine the effect is tied to
  83007. * @param name The name of the effect
  83008. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  83009. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  83010. */
  83011. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  83012. this._name = name;
  83013. this._singleInstance = singleInstance || true;
  83014. this._getPostProcesses = getPostProcesses;
  83015. this._cameras = {};
  83016. this._indicesForCamera = {};
  83017. this._postProcesses = {};
  83018. }
  83019. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  83020. /**
  83021. * Checks if all the post processes in the effect are supported.
  83022. */
  83023. get: function () {
  83024. for (var index in this._postProcesses) {
  83025. if (this._postProcesses.hasOwnProperty(index)) {
  83026. var pps = this._postProcesses[index];
  83027. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  83028. if (!pps[ppIndex].isSupported) {
  83029. return false;
  83030. }
  83031. }
  83032. }
  83033. }
  83034. return true;
  83035. },
  83036. enumerable: true,
  83037. configurable: true
  83038. });
  83039. /**
  83040. * Updates the current state of the effect
  83041. * @hidden
  83042. */
  83043. PostProcessRenderEffect.prototype._update = function () {
  83044. };
  83045. /**
  83046. * Attaches the effect on cameras
  83047. * @param cameras The camera to attach to.
  83048. * @hidden
  83049. */
  83050. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  83051. var _this = this;
  83052. var cameraKey;
  83053. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83054. if (!cams) {
  83055. return;
  83056. }
  83057. for (var i = 0; i < cams.length; i++) {
  83058. var camera = cams[i];
  83059. var cameraName = camera.name;
  83060. if (this._singleInstance) {
  83061. cameraKey = 0;
  83062. }
  83063. else {
  83064. cameraKey = cameraName;
  83065. }
  83066. if (!this._postProcesses[cameraKey]) {
  83067. var postProcess = this._getPostProcesses();
  83068. if (postProcess) {
  83069. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  83070. }
  83071. }
  83072. if (!this._indicesForCamera[cameraName]) {
  83073. this._indicesForCamera[cameraName] = [];
  83074. }
  83075. this._postProcesses[cameraKey].forEach(function (postProcess) {
  83076. var index = camera.attachPostProcess(postProcess);
  83077. _this._indicesForCamera[cameraName].push(index);
  83078. });
  83079. if (!this._cameras[cameraName]) {
  83080. this._cameras[cameraName] = camera;
  83081. }
  83082. }
  83083. };
  83084. /**
  83085. * Detatches the effect on cameras
  83086. * @param cameras The camera to detatch from.
  83087. * @hidden
  83088. */
  83089. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  83090. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83091. if (!cams) {
  83092. return;
  83093. }
  83094. for (var i = 0; i < cams.length; i++) {
  83095. var camera = cams[i];
  83096. var cameraName = camera.name;
  83097. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83098. camera.detachPostProcess(postProcess);
  83099. });
  83100. if (this._cameras[cameraName]) {
  83101. //this._indicesForCamera.splice(index, 1);
  83102. this._cameras[cameraName] = null;
  83103. }
  83104. }
  83105. };
  83106. /**
  83107. * Enables the effect on given cameras
  83108. * @param cameras The camera to enable.
  83109. * @hidden
  83110. */
  83111. PostProcessRenderEffect.prototype._enable = function (cameras) {
  83112. var _this = this;
  83113. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83114. if (!cams) {
  83115. return;
  83116. }
  83117. for (var i = 0; i < cams.length; i++) {
  83118. var camera = cams[i];
  83119. var cameraName = camera.name;
  83120. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  83121. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  83122. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83123. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  83124. });
  83125. }
  83126. }
  83127. }
  83128. };
  83129. /**
  83130. * Disables the effect on the given cameras
  83131. * @param cameras The camera to disable.
  83132. * @hidden
  83133. */
  83134. PostProcessRenderEffect.prototype._disable = function (cameras) {
  83135. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83136. if (!cams) {
  83137. return;
  83138. }
  83139. for (var i = 0; i < cams.length; i++) {
  83140. var camera = cams[i];
  83141. var cameraName = camera.name;
  83142. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83143. camera.detachPostProcess(postProcess);
  83144. });
  83145. }
  83146. };
  83147. /**
  83148. * Gets a list of the post processes contained in the effect.
  83149. * @param camera The camera to get the post processes on.
  83150. * @returns The list of the post processes in the effect.
  83151. */
  83152. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  83153. if (this._singleInstance) {
  83154. return this._postProcesses[0];
  83155. }
  83156. else {
  83157. if (!camera) {
  83158. return null;
  83159. }
  83160. return this._postProcesses[camera.name];
  83161. }
  83162. };
  83163. return PostProcessRenderEffect;
  83164. }());
  83165. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  83166. })(BABYLON || (BABYLON = {}));
  83167. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  83168. var BABYLON;
  83169. (function (BABYLON) {
  83170. /**
  83171. * PostProcessRenderPipeline
  83172. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83173. */
  83174. var PostProcessRenderPipeline = /** @class */ (function () {
  83175. /**
  83176. * Initializes a PostProcessRenderPipeline
  83177. * @param engine engine to add the pipeline to
  83178. * @param name name of the pipeline
  83179. */
  83180. function PostProcessRenderPipeline(engine, name) {
  83181. this.engine = engine;
  83182. this._name = name;
  83183. this._renderEffects = {};
  83184. this._renderEffectsForIsolatedPass = new Array();
  83185. this._cameras = [];
  83186. }
  83187. /**
  83188. * "PostProcessRenderPipeline"
  83189. * @returns "PostProcessRenderPipeline"
  83190. */
  83191. PostProcessRenderPipeline.prototype.getClassName = function () {
  83192. return "PostProcessRenderPipeline";
  83193. };
  83194. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  83195. /**
  83196. * If all the render effects in the pipeline are support
  83197. */
  83198. get: function () {
  83199. for (var renderEffectName in this._renderEffects) {
  83200. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83201. if (!this._renderEffects[renderEffectName].isSupported) {
  83202. return false;
  83203. }
  83204. }
  83205. }
  83206. return true;
  83207. },
  83208. enumerable: true,
  83209. configurable: true
  83210. });
  83211. /**
  83212. * Adds an effect to the pipeline
  83213. * @param renderEffect the effect to add
  83214. */
  83215. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  83216. this._renderEffects[renderEffect._name] = renderEffect;
  83217. };
  83218. // private
  83219. /** @hidden */
  83220. PostProcessRenderPipeline.prototype._rebuild = function () {
  83221. };
  83222. /** @hidden */
  83223. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  83224. var renderEffects = this._renderEffects[renderEffectName];
  83225. if (!renderEffects) {
  83226. return;
  83227. }
  83228. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  83229. };
  83230. /** @hidden */
  83231. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  83232. var renderEffects = this._renderEffects[renderEffectName];
  83233. if (!renderEffects) {
  83234. return;
  83235. }
  83236. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  83237. };
  83238. /** @hidden */
  83239. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  83240. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83241. if (!cams) {
  83242. return;
  83243. }
  83244. var indicesToDelete = [];
  83245. var i;
  83246. for (i = 0; i < cams.length; i++) {
  83247. var camera = cams[i];
  83248. var cameraName = camera.name;
  83249. if (this._cameras.indexOf(camera) === -1) {
  83250. this._cameras[cameraName] = camera;
  83251. }
  83252. else if (unique) {
  83253. indicesToDelete.push(i);
  83254. }
  83255. }
  83256. for (i = 0; i < indicesToDelete.length; i++) {
  83257. cameras.splice(indicesToDelete[i], 1);
  83258. }
  83259. for (var renderEffectName in this._renderEffects) {
  83260. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83261. this._renderEffects[renderEffectName]._attachCameras(cams);
  83262. }
  83263. }
  83264. };
  83265. /** @hidden */
  83266. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  83267. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83268. if (!cams) {
  83269. return;
  83270. }
  83271. for (var renderEffectName in this._renderEffects) {
  83272. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83273. this._renderEffects[renderEffectName]._detachCameras(cams);
  83274. }
  83275. }
  83276. for (var i = 0; i < cams.length; i++) {
  83277. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  83278. }
  83279. };
  83280. /** @hidden */
  83281. PostProcessRenderPipeline.prototype._update = function () {
  83282. for (var renderEffectName in this._renderEffects) {
  83283. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83284. this._renderEffects[renderEffectName]._update();
  83285. }
  83286. }
  83287. for (var i = 0; i < this._cameras.length; i++) {
  83288. var cameraName = this._cameras[i].name;
  83289. if (this._renderEffectsForIsolatedPass[cameraName]) {
  83290. this._renderEffectsForIsolatedPass[cameraName]._update();
  83291. }
  83292. }
  83293. };
  83294. /** @hidden */
  83295. PostProcessRenderPipeline.prototype._reset = function () {
  83296. this._renderEffects = {};
  83297. this._renderEffectsForIsolatedPass = new Array();
  83298. };
  83299. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  83300. // 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)
  83301. var effectKeys = Object.keys(this._renderEffects);
  83302. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  83303. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  83304. if (postProcesses) {
  83305. postProcesses[0].samples = sampleCount;
  83306. return true;
  83307. }
  83308. }
  83309. return false;
  83310. };
  83311. /**
  83312. * Disposes of the pipeline
  83313. */
  83314. PostProcessRenderPipeline.prototype.dispose = function () {
  83315. // Must be implemented by children
  83316. };
  83317. __decorate([
  83318. BABYLON.serialize()
  83319. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  83320. return PostProcessRenderPipeline;
  83321. }());
  83322. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  83323. })(BABYLON || (BABYLON = {}));
  83324. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  83325. var BABYLON;
  83326. (function (BABYLON) {
  83327. /**
  83328. * This represents a depth renderer in Babylon.
  83329. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  83330. */
  83331. var DepthRenderer = /** @class */ (function () {
  83332. /**
  83333. * Instantiates a depth renderer
  83334. * @param scene The scene the renderer belongs to
  83335. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  83336. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  83337. */
  83338. function DepthRenderer(scene, type, camera) {
  83339. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  83340. if (camera === void 0) { camera = null; }
  83341. var _this = this;
  83342. /**
  83343. * Specifiess that the depth renderer will only be used within
  83344. * the camera it is created for.
  83345. * This can help forcing its rendering during the camera processing.
  83346. */
  83347. this.useOnlyInActiveCamera = false;
  83348. this._scene = scene;
  83349. // Register the G Buffer component to the scene.
  83350. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  83351. if (!component) {
  83352. component = new BABYLON.DepthRendererSceneComponent(scene);
  83353. scene._addComponent(component);
  83354. }
  83355. this._camera = camera;
  83356. var engine = scene.getEngine();
  83357. // Render target
  83358. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  83359. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83360. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83361. this._depthMap.refreshRate = 1;
  83362. this._depthMap.renderParticles = false;
  83363. this._depthMap.renderList = null;
  83364. // Camera to get depth map from to support multiple concurrent cameras
  83365. this._depthMap.activeCamera = this._camera;
  83366. this._depthMap.ignoreCameraViewport = true;
  83367. this._depthMap.useCameraPostProcesses = false;
  83368. // set default depth value to 1.0 (far away)
  83369. this._depthMap.onClearObservable.add(function (engine) {
  83370. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  83371. });
  83372. // Custom render function
  83373. var renderSubMesh = function (subMesh) {
  83374. var mesh = subMesh.getRenderingMesh();
  83375. var scene = _this._scene;
  83376. var engine = scene.getEngine();
  83377. var material = subMesh.getMaterial();
  83378. if (!material) {
  83379. return;
  83380. }
  83381. // Culling and reverse (right handed system)
  83382. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83383. // Managing instances
  83384. var batch = mesh._getInstancesRenderList(subMesh._id);
  83385. if (batch.mustReturn) {
  83386. return;
  83387. }
  83388. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83389. var camera = _this._camera || scene.activeCamera;
  83390. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  83391. engine.enableEffect(_this._effect);
  83392. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83393. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83394. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  83395. // Alpha test
  83396. if (material && material.needAlphaTesting()) {
  83397. var alphaTexture = material.getAlphaTestTexture();
  83398. if (alphaTexture) {
  83399. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83400. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83401. }
  83402. }
  83403. // Bones
  83404. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83405. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83406. }
  83407. // Draw
  83408. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83409. }
  83410. };
  83411. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83412. var index;
  83413. if (depthOnlySubMeshes.length) {
  83414. engine.setColorWrite(false);
  83415. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83416. renderSubMesh(depthOnlySubMeshes.data[index]);
  83417. }
  83418. engine.setColorWrite(true);
  83419. }
  83420. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83421. renderSubMesh(opaqueSubMeshes.data[index]);
  83422. }
  83423. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83424. renderSubMesh(alphaTestSubMeshes.data[index]);
  83425. }
  83426. };
  83427. }
  83428. /**
  83429. * Creates the depth rendering effect and checks if the effect is ready.
  83430. * @param subMesh The submesh to be used to render the depth map of
  83431. * @param useInstances If multiple world instances should be used
  83432. * @returns if the depth renderer is ready to render the depth map
  83433. */
  83434. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  83435. var material = subMesh.getMaterial();
  83436. if (material.disableDepthWrite) {
  83437. return false;
  83438. }
  83439. var defines = [];
  83440. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83441. var mesh = subMesh.getMesh();
  83442. // Alpha test
  83443. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  83444. defines.push("#define ALPHATEST");
  83445. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83446. attribs.push(BABYLON.VertexBuffer.UVKind);
  83447. defines.push("#define UV1");
  83448. }
  83449. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83450. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83451. defines.push("#define UV2");
  83452. }
  83453. }
  83454. // Bones
  83455. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83456. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83457. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83458. if (mesh.numBoneInfluencers > 4) {
  83459. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83460. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83461. }
  83462. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83463. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83464. }
  83465. else {
  83466. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83467. }
  83468. // Instances
  83469. if (useInstances) {
  83470. defines.push("#define INSTANCES");
  83471. attribs.push("world0");
  83472. attribs.push("world1");
  83473. attribs.push("world2");
  83474. attribs.push("world3");
  83475. }
  83476. // Get correct effect
  83477. var join = defines.join("\n");
  83478. if (this._cachedDefines !== join) {
  83479. this._cachedDefines = join;
  83480. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  83481. }
  83482. return this._effect.isReady();
  83483. };
  83484. /**
  83485. * Gets the texture which the depth map will be written to.
  83486. * @returns The depth map texture
  83487. */
  83488. DepthRenderer.prototype.getDepthMap = function () {
  83489. return this._depthMap;
  83490. };
  83491. /**
  83492. * Disposes of the depth renderer.
  83493. */
  83494. DepthRenderer.prototype.dispose = function () {
  83495. this._depthMap.dispose();
  83496. };
  83497. return DepthRenderer;
  83498. }());
  83499. BABYLON.DepthRenderer = DepthRenderer;
  83500. })(BABYLON || (BABYLON = {}));
  83501. //# sourceMappingURL=babylon.depthRenderer.js.map
  83502. var BABYLON;
  83503. (function (BABYLON) {
  83504. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  83505. camera = camera || this.activeCamera;
  83506. if (!camera) {
  83507. throw "No camera available to enable depth renderer";
  83508. }
  83509. if (!this._depthRenderer) {
  83510. this._depthRenderer = {};
  83511. }
  83512. if (!this._depthRenderer[camera.id]) {
  83513. var textureType = 0;
  83514. if (this.getEngine().getCaps().textureHalfFloatRender) {
  83515. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83516. }
  83517. else if (this.getEngine().getCaps().textureFloatRender) {
  83518. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83519. }
  83520. else {
  83521. throw "Depth renderer does not support int texture type";
  83522. }
  83523. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  83524. }
  83525. return this._depthRenderer[camera.id];
  83526. };
  83527. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  83528. camera = camera || this.activeCamera;
  83529. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  83530. return;
  83531. }
  83532. this._depthRenderer[camera.id].dispose();
  83533. delete this._depthRenderer[camera.id];
  83534. };
  83535. /**
  83536. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  83537. * in several rendering techniques.
  83538. */
  83539. var DepthRendererSceneComponent = /** @class */ (function () {
  83540. /**
  83541. * Creates a new instance of the component for the given scene
  83542. * @param scene Defines the scene to register the component in
  83543. */
  83544. function DepthRendererSceneComponent(scene) {
  83545. /**
  83546. * The component name helpfull to identify the component in the list of scene components.
  83547. */
  83548. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  83549. this.scene = scene;
  83550. }
  83551. /**
  83552. * Registers the component in a given scene
  83553. */
  83554. DepthRendererSceneComponent.prototype.register = function () {
  83555. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  83556. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  83557. };
  83558. /**
  83559. * Rebuilds the elements related to this component in case of
  83560. * context lost for instance.
  83561. */
  83562. DepthRendererSceneComponent.prototype.rebuild = function () {
  83563. // Nothing to do for this component
  83564. };
  83565. /**
  83566. * Disposes the component and the associated ressources
  83567. */
  83568. DepthRendererSceneComponent.prototype.dispose = function () {
  83569. for (var key in this.scene._depthRenderer) {
  83570. this.scene._depthRenderer[key].dispose();
  83571. }
  83572. };
  83573. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83574. if (this.scene._depthRenderer) {
  83575. for (var key in this.scene._depthRenderer) {
  83576. var depthRenderer = this.scene._depthRenderer[key];
  83577. if (!depthRenderer.useOnlyInActiveCamera) {
  83578. renderTargets.push(depthRenderer.getDepthMap());
  83579. }
  83580. }
  83581. }
  83582. };
  83583. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  83584. if (this.scene._depthRenderer) {
  83585. for (var key in this.scene._depthRenderer) {
  83586. var depthRenderer = this.scene._depthRenderer[key];
  83587. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  83588. renderTargets.push(depthRenderer.getDepthMap());
  83589. }
  83590. }
  83591. }
  83592. };
  83593. return DepthRendererSceneComponent;
  83594. }());
  83595. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  83596. })(BABYLON || (BABYLON = {}));
  83597. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  83598. var BABYLON;
  83599. (function (BABYLON) {
  83600. /**
  83601. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  83602. */
  83603. var GeometryBufferRenderer = /** @class */ (function () {
  83604. /**
  83605. * Creates a new G Buffer for the scene
  83606. * @param scene The scene the buffer belongs to
  83607. * @param ratio How big is the buffer related to the main canvas.
  83608. */
  83609. function GeometryBufferRenderer(scene, ratio) {
  83610. if (ratio === void 0) { ratio = 1; }
  83611. this._enablePosition = false;
  83612. this._scene = scene;
  83613. this._ratio = ratio;
  83614. // Register the G Buffer component to the scene.
  83615. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  83616. if (!component) {
  83617. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  83618. scene._addComponent(component);
  83619. }
  83620. // Render target
  83621. this._createRenderTargets();
  83622. }
  83623. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  83624. /**
  83625. * Set the render list (meshes to be rendered) used in the G buffer.
  83626. */
  83627. set: function (meshes) {
  83628. this._multiRenderTarget.renderList = meshes;
  83629. },
  83630. enumerable: true,
  83631. configurable: true
  83632. });
  83633. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  83634. /**
  83635. * Gets wether or not G buffer are supported by the running hardware.
  83636. * This requires draw buffer supports
  83637. */
  83638. get: function () {
  83639. return this._multiRenderTarget.isSupported;
  83640. },
  83641. enumerable: true,
  83642. configurable: true
  83643. });
  83644. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  83645. /**
  83646. * Gets wether or not position are enabled for the G buffer.
  83647. */
  83648. get: function () {
  83649. return this._enablePosition;
  83650. },
  83651. /**
  83652. * Sets wether or not position are enabled for the G buffer.
  83653. */
  83654. set: function (enable) {
  83655. this._enablePosition = enable;
  83656. this.dispose();
  83657. this._createRenderTargets();
  83658. },
  83659. enumerable: true,
  83660. configurable: true
  83661. });
  83662. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  83663. /**
  83664. * Gets the scene associated with the buffer.
  83665. */
  83666. get: function () {
  83667. return this._scene;
  83668. },
  83669. enumerable: true,
  83670. configurable: true
  83671. });
  83672. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  83673. /**
  83674. * Gets the ratio used by the buffer during its creation.
  83675. * How big is the buffer related to the main canvas.
  83676. */
  83677. get: function () {
  83678. return this._ratio;
  83679. },
  83680. enumerable: true,
  83681. configurable: true
  83682. });
  83683. /**
  83684. * Checks wether everything is ready to render a submesh to the G buffer.
  83685. * @param subMesh the submesh to check readiness for
  83686. * @param useInstances is the mesh drawn using instance or not
  83687. * @returns true if ready otherwise false
  83688. */
  83689. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  83690. var material = subMesh.getMaterial();
  83691. if (material && material.disableDepthWrite) {
  83692. return false;
  83693. }
  83694. var defines = [];
  83695. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83696. var mesh = subMesh.getMesh();
  83697. // Alpha test
  83698. if (material && material.needAlphaTesting()) {
  83699. defines.push("#define ALPHATEST");
  83700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83701. attribs.push(BABYLON.VertexBuffer.UVKind);
  83702. defines.push("#define UV1");
  83703. }
  83704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83705. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83706. defines.push("#define UV2");
  83707. }
  83708. }
  83709. // Buffers
  83710. if (this._enablePosition) {
  83711. defines.push("#define POSITION");
  83712. }
  83713. // Bones
  83714. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83717. if (mesh.numBoneInfluencers > 4) {
  83718. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83719. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83720. }
  83721. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83722. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83723. }
  83724. else {
  83725. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83726. }
  83727. // Instances
  83728. if (useInstances) {
  83729. defines.push("#define INSTANCES");
  83730. attribs.push("world0");
  83731. attribs.push("world1");
  83732. attribs.push("world2");
  83733. attribs.push("world3");
  83734. }
  83735. // Get correct effect
  83736. var join = defines.join("\n");
  83737. if (this._cachedDefines !== join) {
  83738. this._cachedDefines = join;
  83739. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  83740. }
  83741. return this._effect.isReady();
  83742. };
  83743. /**
  83744. * Gets the current underlying G Buffer.
  83745. * @returns the buffer
  83746. */
  83747. GeometryBufferRenderer.prototype.getGBuffer = function () {
  83748. return this._multiRenderTarget;
  83749. };
  83750. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  83751. /**
  83752. * Gets the number of samples used to render the buffer (anti aliasing).
  83753. */
  83754. get: function () {
  83755. return this._multiRenderTarget.samples;
  83756. },
  83757. /**
  83758. * Sets the number of samples used to render the buffer (anti aliasing).
  83759. */
  83760. set: function (value) {
  83761. this._multiRenderTarget.samples = value;
  83762. },
  83763. enumerable: true,
  83764. configurable: true
  83765. });
  83766. /**
  83767. * Disposes the renderer and frees up associated resources.
  83768. */
  83769. GeometryBufferRenderer.prototype.dispose = function () {
  83770. this.getGBuffer().dispose();
  83771. };
  83772. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  83773. var _this = this;
  83774. var engine = this._scene.getEngine();
  83775. var count = this._enablePosition ? 3 : 2;
  83776. 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 });
  83777. if (!this.isSupported) {
  83778. return;
  83779. }
  83780. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83781. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83782. this._multiRenderTarget.refreshRate = 1;
  83783. this._multiRenderTarget.renderParticles = false;
  83784. this._multiRenderTarget.renderList = null;
  83785. // set default depth value to 1.0 (far away)
  83786. this._multiRenderTarget.onClearObservable.add(function (engine) {
  83787. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  83788. });
  83789. // Custom render function
  83790. var renderSubMesh = function (subMesh) {
  83791. var mesh = subMesh.getRenderingMesh();
  83792. var scene = _this._scene;
  83793. var engine = scene.getEngine();
  83794. var material = subMesh.getMaterial();
  83795. if (!material) {
  83796. return;
  83797. }
  83798. // Culling
  83799. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83800. // Managing instances
  83801. var batch = mesh._getInstancesRenderList(subMesh._id);
  83802. if (batch.mustReturn) {
  83803. return;
  83804. }
  83805. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83806. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  83807. engine.enableEffect(_this._effect);
  83808. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83809. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83810. _this._effect.setMatrix("view", scene.getViewMatrix());
  83811. // Alpha test
  83812. if (material && material.needAlphaTesting()) {
  83813. var alphaTexture = material.getAlphaTestTexture();
  83814. if (alphaTexture) {
  83815. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83816. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83817. }
  83818. }
  83819. // Bones
  83820. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83821. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83822. }
  83823. // Draw
  83824. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83825. }
  83826. };
  83827. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83828. var index;
  83829. if (depthOnlySubMeshes.length) {
  83830. engine.setColorWrite(false);
  83831. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83832. renderSubMesh(depthOnlySubMeshes.data[index]);
  83833. }
  83834. engine.setColorWrite(true);
  83835. }
  83836. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83837. renderSubMesh(opaqueSubMeshes.data[index]);
  83838. }
  83839. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83840. renderSubMesh(alphaTestSubMeshes.data[index]);
  83841. }
  83842. };
  83843. };
  83844. return GeometryBufferRenderer;
  83845. }());
  83846. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  83847. })(BABYLON || (BABYLON = {}));
  83848. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  83849. var BABYLON;
  83850. (function (BABYLON) {
  83851. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  83852. get: function () {
  83853. this._geometryBufferRenderer;
  83854. },
  83855. set: function (value) {
  83856. if (value && value.isSupported) {
  83857. this._geometryBufferRenderer = value;
  83858. }
  83859. },
  83860. enumerable: true,
  83861. configurable: true
  83862. });
  83863. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  83864. if (ratio === void 0) { ratio = 1; }
  83865. if (this._geometryBufferRenderer) {
  83866. return this._geometryBufferRenderer;
  83867. }
  83868. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  83869. if (!this._geometryBufferRenderer.isSupported) {
  83870. this._geometryBufferRenderer = null;
  83871. }
  83872. return this._geometryBufferRenderer;
  83873. };
  83874. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  83875. if (!this._geometryBufferRenderer) {
  83876. return;
  83877. }
  83878. this._geometryBufferRenderer.dispose();
  83879. this._geometryBufferRenderer = null;
  83880. };
  83881. /**
  83882. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  83883. * in several rendering techniques.
  83884. */
  83885. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  83886. /**
  83887. * Creates a new instance of the component for the given scene
  83888. * @param scene Defines the scene to register the component in
  83889. */
  83890. function GeometryBufferRendererSceneComponent(scene) {
  83891. /**
  83892. * The component name helpful to identify the component in the list of scene components.
  83893. */
  83894. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  83895. this.scene = scene;
  83896. }
  83897. /**
  83898. * Registers the component in a given scene
  83899. */
  83900. GeometryBufferRendererSceneComponent.prototype.register = function () {
  83901. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  83902. };
  83903. /**
  83904. * Rebuilds the elements related to this component in case of
  83905. * context lost for instance.
  83906. */
  83907. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  83908. // Nothing to do for this component
  83909. };
  83910. /**
  83911. * Disposes the component and the associated ressources
  83912. */
  83913. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  83914. // Nothing to do for this component
  83915. };
  83916. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83917. if (this.scene._geometryBufferRenderer) {
  83918. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  83919. }
  83920. };
  83921. return GeometryBufferRendererSceneComponent;
  83922. }());
  83923. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  83924. })(BABYLON || (BABYLON = {}));
  83925. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  83926. var BABYLON;
  83927. (function (BABYLON) {
  83928. /**
  83929. * Render pipeline to produce ssao effect
  83930. */
  83931. var SSAORenderingPipeline = /** @class */ (function (_super) {
  83932. __extends(SSAORenderingPipeline, _super);
  83933. /**
  83934. * @constructor
  83935. * @param name - The rendering pipeline name
  83936. * @param scene - The scene linked to this pipeline
  83937. * @param 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 }
  83938. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  83939. */
  83940. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  83941. var _this = _super.call(this, scene.getEngine(), name) || this;
  83942. // Members
  83943. /**
  83944. * @ignore
  83945. * The PassPostProcess id in the pipeline that contains the original scene color
  83946. */
  83947. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83948. /**
  83949. * @ignore
  83950. * The SSAO PostProcess id in the pipeline
  83951. */
  83952. _this.SSAORenderEffect = "SSAORenderEffect";
  83953. /**
  83954. * @ignore
  83955. * The horizontal blur PostProcess id in the pipeline
  83956. */
  83957. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83958. /**
  83959. * @ignore
  83960. * The vertical blur PostProcess id in the pipeline
  83961. */
  83962. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83963. /**
  83964. * @ignore
  83965. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83966. */
  83967. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83968. /**
  83969. * The output strength of the SSAO post-process. Default value is 1.0.
  83970. */
  83971. _this.totalStrength = 1.0;
  83972. /**
  83973. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  83974. */
  83975. _this.radius = 0.0001;
  83976. /**
  83977. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  83978. * Must not be equal to fallOff and superior to fallOff.
  83979. * Default value is 0.975
  83980. */
  83981. _this.area = 0.0075;
  83982. /**
  83983. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  83984. * Must not be equal to area and inferior to area.
  83985. * Default value is 0.0
  83986. */
  83987. _this.fallOff = 0.000001;
  83988. /**
  83989. * The base color of the SSAO post-process
  83990. * The final result is "base + ssao" between [0, 1]
  83991. */
  83992. _this.base = 0.5;
  83993. _this._firstUpdate = true;
  83994. _this._scene = scene;
  83995. // Set up assets
  83996. _this._createRandomTexture();
  83997. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  83998. var ssaoRatio = ratio.ssaoRatio || ratio;
  83999. var combineRatio = ratio.combineRatio || ratio;
  84000. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  84001. _this._createSSAOPostProcess(ssaoRatio);
  84002. _this._createBlurPostProcess(ssaoRatio);
  84003. _this._createSSAOCombinePostProcess(combineRatio);
  84004. // Set up pipeline
  84005. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  84006. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  84007. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  84008. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  84009. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  84010. // Finish
  84011. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84012. if (cameras) {
  84013. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84014. }
  84015. return _this;
  84016. }
  84017. // Public Methods
  84018. /**
  84019. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84020. */
  84021. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84022. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84023. for (var i = 0; i < this._scene.cameras.length; i++) {
  84024. var camera = this._scene.cameras[i];
  84025. this._originalColorPostProcess.dispose(camera);
  84026. this._ssaoPostProcess.dispose(camera);
  84027. this._blurHPostProcess.dispose(camera);
  84028. this._blurVPostProcess.dispose(camera);
  84029. this._ssaoCombinePostProcess.dispose(camera);
  84030. }
  84031. this._randomTexture.dispose();
  84032. if (disableDepthRender) {
  84033. this._scene.disableDepthRenderer();
  84034. }
  84035. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84036. _super.prototype.dispose.call(this);
  84037. };
  84038. // Private Methods
  84039. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  84040. var _this = this;
  84041. var size = 16;
  84042. 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);
  84043. 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);
  84044. this._blurHPostProcess.onActivateObservable.add(function () {
  84045. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  84046. _this._blurHPostProcess.kernel = size * dw;
  84047. });
  84048. this._blurVPostProcess.onActivateObservable.add(function () {
  84049. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  84050. _this._blurVPostProcess.kernel = size * dw;
  84051. });
  84052. };
  84053. /** @hidden */
  84054. SSAORenderingPipeline.prototype._rebuild = function () {
  84055. this._firstUpdate = true;
  84056. _super.prototype._rebuild.call(this);
  84057. };
  84058. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84059. var _this = this;
  84060. var numSamples = 16;
  84061. var sampleSphere = [
  84062. 0.5381, 0.1856, -0.4319,
  84063. 0.1379, 0.2486, 0.4430,
  84064. 0.3371, 0.5679, -0.0057,
  84065. -0.6999, -0.0451, -0.0019,
  84066. 0.0689, -0.1598, -0.8547,
  84067. 0.0560, 0.0069, -0.1843,
  84068. -0.0146, 0.1402, 0.0762,
  84069. 0.0100, -0.1924, -0.0344,
  84070. -0.3577, -0.5301, -0.4358,
  84071. -0.3169, 0.1063, 0.0158,
  84072. 0.0103, -0.5869, 0.0046,
  84073. -0.0897, -0.4940, 0.3287,
  84074. 0.7119, -0.0154, -0.0918,
  84075. -0.0533, 0.0596, -0.5411,
  84076. 0.0352, -0.0631, 0.5460,
  84077. -0.4776, 0.2847, -0.0271
  84078. ];
  84079. var samplesFactor = 1.0 / numSamples;
  84080. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  84081. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84082. "area", "fallOff", "base", "range", "viewport"
  84083. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84084. this._ssaoPostProcess.onApply = function (effect) {
  84085. if (_this._firstUpdate) {
  84086. effect.setArray3("sampleSphere", sampleSphere);
  84087. effect.setFloat("samplesFactor", samplesFactor);
  84088. effect.setFloat("randTextureTiles", 4.0);
  84089. }
  84090. effect.setFloat("totalStrength", _this.totalStrength);
  84091. effect.setFloat("radius", _this.radius);
  84092. effect.setFloat("area", _this.area);
  84093. effect.setFloat("fallOff", _this.fallOff);
  84094. effect.setFloat("base", _this.base);
  84095. effect.setTexture("textureSampler", _this._depthTexture);
  84096. effect.setTexture("randomSampler", _this._randomTexture);
  84097. };
  84098. };
  84099. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84100. var _this = this;
  84101. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84102. this._ssaoCombinePostProcess.onApply = function (effect) {
  84103. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  84104. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84105. };
  84106. };
  84107. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  84108. var size = 512;
  84109. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84110. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84111. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84112. var context = this._randomTexture.getContext();
  84113. var rand = function (min, max) {
  84114. return Math.random() * (max - min) + min;
  84115. };
  84116. var randVector = BABYLON.Vector3.Zero();
  84117. for (var x = 0; x < size; x++) {
  84118. for (var y = 0; y < size; y++) {
  84119. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  84120. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  84121. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  84122. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84123. context.fillRect(x, y, 1, 1);
  84124. }
  84125. }
  84126. this._randomTexture.update(false);
  84127. };
  84128. __decorate([
  84129. BABYLON.serialize()
  84130. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  84131. __decorate([
  84132. BABYLON.serialize()
  84133. ], SSAORenderingPipeline.prototype, "radius", void 0);
  84134. __decorate([
  84135. BABYLON.serialize()
  84136. ], SSAORenderingPipeline.prototype, "area", void 0);
  84137. __decorate([
  84138. BABYLON.serialize()
  84139. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  84140. __decorate([
  84141. BABYLON.serialize()
  84142. ], SSAORenderingPipeline.prototype, "base", void 0);
  84143. return SSAORenderingPipeline;
  84144. }(BABYLON.PostProcessRenderPipeline));
  84145. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  84146. })(BABYLON || (BABYLON = {}));
  84147. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  84148. var BABYLON;
  84149. (function (BABYLON) {
  84150. /**
  84151. * Render pipeline to produce ssao effect
  84152. */
  84153. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  84154. __extends(SSAO2RenderingPipeline, _super);
  84155. /**
  84156. * @constructor
  84157. * @param name The rendering pipeline name
  84158. * @param scene The scene linked to this pipeline
  84159. * @param 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 }
  84160. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84161. */
  84162. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  84163. var _this = _super.call(this, scene.getEngine(), name) || this;
  84164. // Members
  84165. /**
  84166. * @ignore
  84167. * The PassPostProcess id in the pipeline that contains the original scene color
  84168. */
  84169. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  84170. /**
  84171. * @ignore
  84172. * The SSAO PostProcess id in the pipeline
  84173. */
  84174. _this.SSAORenderEffect = "SSAORenderEffect";
  84175. /**
  84176. * @ignore
  84177. * The horizontal blur PostProcess id in the pipeline
  84178. */
  84179. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  84180. /**
  84181. * @ignore
  84182. * The vertical blur PostProcess id in the pipeline
  84183. */
  84184. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  84185. /**
  84186. * @ignore
  84187. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  84188. */
  84189. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  84190. /**
  84191. * The output strength of the SSAO post-process. Default value is 1.0.
  84192. */
  84193. _this.totalStrength = 1.0;
  84194. /**
  84195. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  84196. */
  84197. _this.maxZ = 100.0;
  84198. /**
  84199. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  84200. */
  84201. _this.minZAspect = 0.2;
  84202. _this._samples = 8;
  84203. _this._textureSamples = 1;
  84204. _this._expensiveBlur = true;
  84205. /**
  84206. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  84207. */
  84208. _this.radius = 2.0;
  84209. /**
  84210. * The base color of the SSAO post-process
  84211. * The final result is "base + ssao" between [0, 1]
  84212. */
  84213. _this.base = 0;
  84214. _this._firstUpdate = true;
  84215. _this._bits = new Uint32Array(1);
  84216. _this._scene = scene;
  84217. _this._ratio = ratio;
  84218. if (!_this.isSupported) {
  84219. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  84220. return _this;
  84221. }
  84222. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  84223. var blurRatio = _this._ratio.blurRatio || ratio;
  84224. // Set up assets
  84225. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  84226. _this._createRandomTexture();
  84227. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  84228. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  84229. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  84230. _this._originalColorPostProcess.samples = _this.textureSamples;
  84231. _this._createSSAOPostProcess(1.0);
  84232. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  84233. _this._createSSAOCombinePostProcess(blurRatio);
  84234. // Set up pipeline
  84235. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  84236. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  84237. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  84238. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  84239. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  84240. // Finish
  84241. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84242. if (cameras) {
  84243. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84244. }
  84245. return _this;
  84246. }
  84247. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  84248. get: function () {
  84249. return this._samples;
  84250. },
  84251. /**
  84252. * Number of samples used for the SSAO calculations. Default value is 8
  84253. */
  84254. set: function (n) {
  84255. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  84256. this._samples = n;
  84257. this._sampleSphere = this._generateHemisphere();
  84258. this._firstUpdate = true;
  84259. },
  84260. enumerable: true,
  84261. configurable: true
  84262. });
  84263. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  84264. get: function () {
  84265. return this._textureSamples;
  84266. },
  84267. /**
  84268. * Number of samples to use for antialiasing
  84269. */
  84270. set: function (n) {
  84271. this._textureSamples = n;
  84272. this._originalColorPostProcess.samples = n;
  84273. this._blurHPostProcess.samples = n;
  84274. this._blurVPostProcess.samples = n;
  84275. this._ssaoPostProcess.samples = n;
  84276. this._ssaoCombinePostProcess.samples = n;
  84277. },
  84278. enumerable: true,
  84279. configurable: true
  84280. });
  84281. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  84282. get: function () {
  84283. return this._expensiveBlur;
  84284. },
  84285. /**
  84286. * If bilateral blur should be used
  84287. */
  84288. set: function (b) {
  84289. 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"]);
  84290. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  84291. this._expensiveBlur = b;
  84292. this._firstUpdate = true;
  84293. },
  84294. enumerable: true,
  84295. configurable: true
  84296. });
  84297. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  84298. /**
  84299. * Support test.
  84300. */
  84301. get: function () {
  84302. var engine = BABYLON.Engine.LastCreatedEngine;
  84303. if (!engine) {
  84304. return false;
  84305. }
  84306. return engine.getCaps().drawBuffersExtension;
  84307. },
  84308. enumerable: true,
  84309. configurable: true
  84310. });
  84311. // Public Methods
  84312. /**
  84313. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84314. */
  84315. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  84316. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  84317. for (var i = 0; i < this._scene.cameras.length; i++) {
  84318. var camera = this._scene.cameras[i];
  84319. this._originalColorPostProcess.dispose(camera);
  84320. this._ssaoPostProcess.dispose(camera);
  84321. this._blurHPostProcess.dispose(camera);
  84322. this._blurVPostProcess.dispose(camera);
  84323. this._ssaoCombinePostProcess.dispose(camera);
  84324. }
  84325. this._randomTexture.dispose();
  84326. if (disableGeometryBufferRenderer) {
  84327. this._scene.disableGeometryBufferRenderer();
  84328. }
  84329. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84330. _super.prototype.dispose.call(this);
  84331. };
  84332. // Private Methods
  84333. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  84334. var _this = this;
  84335. this._samplerOffsets = [];
  84336. var expensive = this.expensiveBlur;
  84337. for (var i = -8; i < 8; i++) {
  84338. this._samplerOffsets.push(i * 2 + 0.5);
  84339. }
  84340. 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");
  84341. this._blurHPostProcess.onApply = function (effect) {
  84342. if (!_this._scene.activeCamera) {
  84343. return;
  84344. }
  84345. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  84346. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84347. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84348. effect.setFloat("radius", _this.radius);
  84349. effect.setTexture("depthSampler", _this._depthTexture);
  84350. if (_this._firstUpdate) {
  84351. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84352. }
  84353. };
  84354. 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");
  84355. this._blurVPostProcess.onApply = function (effect) {
  84356. if (!_this._scene.activeCamera) {
  84357. return;
  84358. }
  84359. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  84360. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84361. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84362. effect.setFloat("radius", _this.radius);
  84363. effect.setTexture("depthSampler", _this._depthTexture);
  84364. if (_this._firstUpdate) {
  84365. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84366. _this._firstUpdate = false;
  84367. }
  84368. };
  84369. this._blurHPostProcess.samples = this.textureSamples;
  84370. this._blurVPostProcess.samples = this.textureSamples;
  84371. };
  84372. /** @hidden */
  84373. SSAO2RenderingPipeline.prototype._rebuild = function () {
  84374. this._firstUpdate = true;
  84375. _super.prototype._rebuild.call(this);
  84376. };
  84377. //Van der Corput radical inverse
  84378. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  84379. this._bits[0] = i;
  84380. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  84381. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  84382. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  84383. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  84384. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  84385. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  84386. };
  84387. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  84388. return [i / n, this._radicalInverse_VdC(i)];
  84389. };
  84390. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  84391. var phi = v * 2.0 * Math.PI;
  84392. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  84393. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  84394. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  84395. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  84396. };
  84397. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  84398. var numSamples = this.samples;
  84399. var result = [];
  84400. var vector;
  84401. var i = 0;
  84402. while (i < numSamples) {
  84403. if (numSamples < 16) {
  84404. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  84405. }
  84406. else {
  84407. var rand = this._hammersley(i, numSamples);
  84408. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  84409. }
  84410. result.push(vector.x, vector.y, vector.z);
  84411. i++;
  84412. }
  84413. return result;
  84414. };
  84415. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84416. var _this = this;
  84417. var numSamples = this.samples;
  84418. this._sampleSphere = this._generateHemisphere();
  84419. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  84420. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84421. "base", "range", "projection", "near", "far", "texelSize",
  84422. "xViewport", "yViewport", "maxZ", "minZAspect"
  84423. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84424. this._ssaoPostProcess.onApply = function (effect) {
  84425. if (_this._firstUpdate) {
  84426. effect.setArray3("sampleSphere", _this._sampleSphere);
  84427. effect.setFloat("randTextureTiles", 32.0);
  84428. }
  84429. if (!_this._scene.activeCamera) {
  84430. return;
  84431. }
  84432. effect.setFloat("samplesFactor", 1 / _this.samples);
  84433. effect.setFloat("totalStrength", _this.totalStrength);
  84434. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  84435. effect.setFloat("radius", _this.radius);
  84436. effect.setFloat("maxZ", _this.maxZ);
  84437. effect.setFloat("minZAspect", _this.minZAspect);
  84438. effect.setFloat("base", _this.base);
  84439. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84440. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84441. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  84442. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  84443. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  84444. effect.setTexture("textureSampler", _this._depthTexture);
  84445. effect.setTexture("normalSampler", _this._normalTexture);
  84446. effect.setTexture("randomSampler", _this._randomTexture);
  84447. };
  84448. this._ssaoPostProcess.samples = this.textureSamples;
  84449. };
  84450. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84451. var _this = this;
  84452. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84453. this._ssaoCombinePostProcess.onApply = function (effect) {
  84454. var viewport = _this._scene.activeCamera.viewport;
  84455. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  84456. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84457. };
  84458. this._ssaoCombinePostProcess.samples = this.textureSamples;
  84459. };
  84460. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  84461. var size = 128;
  84462. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84463. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84464. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84465. var context = this._randomTexture.getContext();
  84466. var rand = function (min, max) {
  84467. return Math.random() * (max - min) + min;
  84468. };
  84469. var randVector = BABYLON.Vector3.Zero();
  84470. for (var x = 0; x < size; x++) {
  84471. for (var y = 0; y < size; y++) {
  84472. randVector.x = rand(0.0, 1.0);
  84473. randVector.y = rand(0.0, 1.0);
  84474. randVector.z = 0.0;
  84475. randVector.normalize();
  84476. randVector.scaleInPlace(255);
  84477. randVector.x = Math.floor(randVector.x);
  84478. randVector.y = Math.floor(randVector.y);
  84479. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84480. context.fillRect(x, y, 1, 1);
  84481. }
  84482. }
  84483. this._randomTexture.update(false);
  84484. };
  84485. /**
  84486. * Serialize the rendering pipeline (Used when exporting)
  84487. * @returns the serialized object
  84488. */
  84489. SSAO2RenderingPipeline.prototype.serialize = function () {
  84490. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84491. serializationObject.customType = "SSAO2RenderingPipeline";
  84492. return serializationObject;
  84493. };
  84494. /**
  84495. * Parse the serialized pipeline
  84496. * @param source Source pipeline.
  84497. * @param scene The scene to load the pipeline to.
  84498. * @param rootUrl The URL of the serialized pipeline.
  84499. * @returns An instantiated pipeline from the serialized object.
  84500. */
  84501. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  84502. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84503. };
  84504. __decorate([
  84505. BABYLON.serialize()
  84506. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  84507. __decorate([
  84508. BABYLON.serialize()
  84509. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  84510. __decorate([
  84511. BABYLON.serialize()
  84512. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  84513. __decorate([
  84514. BABYLON.serialize("samples")
  84515. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  84516. __decorate([
  84517. BABYLON.serialize("textureSamples")
  84518. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  84519. __decorate([
  84520. BABYLON.serialize()
  84521. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  84522. __decorate([
  84523. BABYLON.serialize("expensiveBlur")
  84524. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  84525. __decorate([
  84526. BABYLON.serialize()
  84527. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  84528. __decorate([
  84529. BABYLON.serialize()
  84530. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  84531. return SSAO2RenderingPipeline;
  84532. }(BABYLON.PostProcessRenderPipeline));
  84533. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  84534. })(BABYLON || (BABYLON = {}));
  84535. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  84536. var BABYLON;
  84537. (function (BABYLON) {
  84538. /**
  84539. * BABYLON.JS Chromatic Aberration GLSL Shader
  84540. * Author: Olivier Guyot
  84541. * Separates very slightly R, G and B colors on the edges of the screen
  84542. * Inspired by Francois Tarlier & Martins Upitis
  84543. */
  84544. var LensRenderingPipeline = /** @class */ (function (_super) {
  84545. __extends(LensRenderingPipeline, _super);
  84546. /**
  84547. * @constructor
  84548. *
  84549. * Effect parameters are as follow:
  84550. * {
  84551. * chromatic_aberration: number; // from 0 to x (1 for realism)
  84552. * edge_blur: number; // from 0 to x (1 for realism)
  84553. * distortion: number; // from 0 to x (1 for realism)
  84554. * grain_amount: number; // from 0 to 1
  84555. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  84556. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  84557. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  84558. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  84559. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  84560. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  84561. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  84562. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  84563. * }
  84564. * Note: if an effect parameter is unset, effect is disabled
  84565. *
  84566. * @param name The rendering pipeline name
  84567. * @param parameters - An object containing all parameters (see above)
  84568. * @param scene The scene linked to this pipeline
  84569. * @param 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)
  84570. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84571. */
  84572. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  84573. if (ratio === void 0) { ratio = 1.0; }
  84574. var _this = _super.call(this, scene.getEngine(), name) || this;
  84575. // Lens effects can be of the following:
  84576. // - chromatic aberration (slight shift of RGB colors)
  84577. // - blur on the edge of the lens
  84578. // - lens distortion
  84579. // - depth-of-field blur & highlights enhancing
  84580. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  84581. // - grain effect (noise or custom texture)
  84582. // Two additional texture samplers are needed:
  84583. // - depth map (for depth-of-field)
  84584. // - grain texture
  84585. /**
  84586. * @ignore
  84587. * The chromatic aberration PostProcess id in the pipeline
  84588. */
  84589. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  84590. /**
  84591. * @ignore
  84592. * The highlights enhancing PostProcess id in the pipeline
  84593. */
  84594. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  84595. /**
  84596. * @ignore
  84597. * The depth-of-field PostProcess id in the pipeline
  84598. */
  84599. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  84600. _this._scene = scene;
  84601. // Fetch texture samplers
  84602. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  84603. if (parameters.grain_texture) {
  84604. _this._grainTexture = parameters.grain_texture;
  84605. }
  84606. else {
  84607. _this._createGrainTexture();
  84608. }
  84609. // save parameters
  84610. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  84611. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  84612. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  84613. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  84614. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  84615. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  84616. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  84617. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  84618. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  84619. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  84620. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  84621. // Create effects
  84622. _this._createChromaticAberrationPostProcess(ratio);
  84623. _this._createHighlightsPostProcess(ratio);
  84624. _this._createDepthOfFieldPostProcess(ratio / 4);
  84625. // Set up pipeline
  84626. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  84627. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  84628. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  84629. if (_this._highlightsGain === -1) {
  84630. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  84631. }
  84632. // Finish
  84633. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84634. if (cameras) {
  84635. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84636. }
  84637. return _this;
  84638. }
  84639. // public methods (self explanatory)
  84640. /**
  84641. * Sets the amount of blur at the edges
  84642. * @param amount blur amount
  84643. */
  84644. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  84645. /**
  84646. * Sets edge blur to 0
  84647. */
  84648. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  84649. /**
  84650. * Sets the amout of grain
  84651. * @param amount Amount of grain
  84652. */
  84653. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  84654. /**
  84655. * Set grain amount to 0
  84656. */
  84657. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  84658. /**
  84659. * Sets the chromatic aberration amount
  84660. * @param amount amount of chromatic aberration
  84661. */
  84662. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  84663. /**
  84664. * Sets chromatic aberration amount to 0
  84665. */
  84666. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  84667. /**
  84668. * Sets the EdgeDistortion amount
  84669. * @param amount amount of EdgeDistortion
  84670. */
  84671. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  84672. /**
  84673. * Sets edge distortion to 0
  84674. */
  84675. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  84676. /**
  84677. * Sets the FocusDistance amount
  84678. * @param amount amount of FocusDistance
  84679. */
  84680. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  84681. /**
  84682. * Disables depth of field
  84683. */
  84684. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  84685. /**
  84686. * Sets the Aperture amount
  84687. * @param amount amount of Aperture
  84688. */
  84689. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  84690. /**
  84691. * Sets the DarkenOutOfFocus amount
  84692. * @param amount amount of DarkenOutOfFocus
  84693. */
  84694. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  84695. /**
  84696. * Creates a pentagon bokeh effect
  84697. */
  84698. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  84699. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  84700. };
  84701. /**
  84702. * Disables the pentagon bokeh effect
  84703. */
  84704. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  84705. this._highlightsPostProcess.updateEffect();
  84706. };
  84707. /**
  84708. * Enables noise blur
  84709. */
  84710. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  84711. /**
  84712. * Disables noise blur
  84713. */
  84714. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  84715. /**
  84716. * Sets the HighlightsGain amount
  84717. * @param amount amount of HighlightsGain
  84718. */
  84719. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  84720. this._highlightsGain = amount;
  84721. };
  84722. /**
  84723. * Sets the HighlightsThreshold amount
  84724. * @param amount amount of HighlightsThreshold
  84725. */
  84726. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  84727. if (this._highlightsGain === -1) {
  84728. this._highlightsGain = 1.0;
  84729. }
  84730. this._highlightsThreshold = amount;
  84731. };
  84732. /**
  84733. * Disables highlights
  84734. */
  84735. LensRenderingPipeline.prototype.disableHighlights = function () {
  84736. this._highlightsGain = -1;
  84737. };
  84738. /**
  84739. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  84740. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  84741. */
  84742. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84743. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84744. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84745. this._chromaticAberrationPostProcess = null;
  84746. this._highlightsPostProcess = null;
  84747. this._depthOfFieldPostProcess = null;
  84748. this._grainTexture.dispose();
  84749. if (disableDepthRender) {
  84750. this._scene.disableDepthRenderer();
  84751. }
  84752. };
  84753. // colors shifting and distortion
  84754. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  84755. var _this = this;
  84756. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  84757. [], // samplers
  84758. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84759. this._chromaticAberrationPostProcess.onApply = function (effect) {
  84760. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  84761. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84762. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84763. effect.setFloat('radialIntensity', 1);
  84764. effect.setFloat2('direction', 17, 17);
  84765. effect.setFloat2('centerPosition', 0.5, 0.5);
  84766. };
  84767. };
  84768. // highlights enhancing
  84769. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  84770. var _this = this;
  84771. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  84772. [], // samplers
  84773. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  84774. this._highlightsPostProcess.onApply = function (effect) {
  84775. effect.setFloat('gain', _this._highlightsGain);
  84776. effect.setFloat('threshold', _this._highlightsThreshold);
  84777. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  84778. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84779. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84780. };
  84781. };
  84782. // colors shifting and distortion
  84783. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  84784. var _this = this;
  84785. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  84786. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  84787. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  84788. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84789. this._depthOfFieldPostProcess.onApply = function (effect) {
  84790. effect.setTexture("depthSampler", _this._depthTexture);
  84791. effect.setTexture("grainSampler", _this._grainTexture);
  84792. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  84793. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  84794. effect.setFloat('grain_amount', _this._grainAmount);
  84795. effect.setBool('blur_noise', _this._blurNoise);
  84796. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84797. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84798. effect.setFloat('distortion', _this._distortion);
  84799. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  84800. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  84801. effect.setFloat('aperture', _this._dofAperture);
  84802. effect.setFloat('darken', _this._dofDarken);
  84803. effect.setFloat('edge_blur', _this._edgeBlur);
  84804. effect.setBool('highlights', (_this._highlightsGain !== -1));
  84805. if (_this._scene.activeCamera) {
  84806. effect.setFloat('near', _this._scene.activeCamera.minZ);
  84807. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  84808. }
  84809. };
  84810. };
  84811. // creates a black and white random noise texture, 512x512
  84812. LensRenderingPipeline.prototype._createGrainTexture = function () {
  84813. var size = 512;
  84814. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84815. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84816. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84817. var context = this._grainTexture.getContext();
  84818. var rand = function (min, max) {
  84819. return Math.random() * (max - min) + min;
  84820. };
  84821. var value;
  84822. for (var x = 0; x < size; x++) {
  84823. for (var y = 0; y < size; y++) {
  84824. value = Math.floor(rand(0.42, 0.58) * 255);
  84825. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  84826. context.fillRect(x, y, 1, 1);
  84827. }
  84828. }
  84829. this._grainTexture.update(false);
  84830. };
  84831. return LensRenderingPipeline;
  84832. }(BABYLON.PostProcessRenderPipeline));
  84833. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  84834. })(BABYLON || (BABYLON = {}));
  84835. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  84836. var BABYLON;
  84837. (function (BABYLON) {
  84838. /**
  84839. * Standard rendering pipeline
  84840. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84841. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  84842. */
  84843. var StandardRenderingPipeline = /** @class */ (function (_super) {
  84844. __extends(StandardRenderingPipeline, _super);
  84845. /**
  84846. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84847. * @constructor
  84848. * @param name The rendering pipeline name
  84849. * @param scene The scene linked to this pipeline
  84850. * @param 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)
  84851. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  84852. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84853. */
  84854. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  84855. if (originalPostProcess === void 0) { originalPostProcess = null; }
  84856. var _this = _super.call(this, scene.getEngine(), name) || this;
  84857. /**
  84858. * Post-process used to down scale an image x4
  84859. */
  84860. _this.downSampleX4PostProcess = null;
  84861. /**
  84862. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  84863. */
  84864. _this.brightPassPostProcess = null;
  84865. /**
  84866. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  84867. */
  84868. _this.blurHPostProcesses = [];
  84869. /**
  84870. * Post-process array storing all the vertical blur post-processes used by the pipeline
  84871. */
  84872. _this.blurVPostProcesses = [];
  84873. /**
  84874. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  84875. */
  84876. _this.textureAdderPostProcess = null;
  84877. /**
  84878. * Post-process used to create volumetric lighting effect
  84879. */
  84880. _this.volumetricLightPostProcess = null;
  84881. /**
  84882. * Post-process used to smooth the previous volumetric light post-process on the X axis
  84883. */
  84884. _this.volumetricLightSmoothXPostProcess = null;
  84885. /**
  84886. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  84887. */
  84888. _this.volumetricLightSmoothYPostProcess = null;
  84889. /**
  84890. * Post-process used to merge the volumetric light effect and the real scene color
  84891. */
  84892. _this.volumetricLightMergePostProces = null;
  84893. /**
  84894. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  84895. */
  84896. _this.volumetricLightFinalPostProcess = null;
  84897. /**
  84898. * Base post-process used to calculate the average luminance of the final image for HDR
  84899. */
  84900. _this.luminancePostProcess = null;
  84901. /**
  84902. * Post-processes used to create down sample post-processes in order to get
  84903. * the average luminance of the final image for HDR
  84904. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  84905. */
  84906. _this.luminanceDownSamplePostProcesses = [];
  84907. /**
  84908. * Post-process used to create a HDR effect (light adaptation)
  84909. */
  84910. _this.hdrPostProcess = null;
  84911. /**
  84912. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  84913. */
  84914. _this.textureAdderFinalPostProcess = null;
  84915. /**
  84916. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  84917. */
  84918. _this.lensFlareFinalPostProcess = null;
  84919. /**
  84920. * Post-process used to merge the final HDR post-process and the real scene color
  84921. */
  84922. _this.hdrFinalPostProcess = null;
  84923. /**
  84924. * Post-process used to create a lens flare effect
  84925. */
  84926. _this.lensFlarePostProcess = null;
  84927. /**
  84928. * Post-process that merges the result of the lens flare post-process and the real scene color
  84929. */
  84930. _this.lensFlareComposePostProcess = null;
  84931. /**
  84932. * Post-process used to create a motion blur effect
  84933. */
  84934. _this.motionBlurPostProcess = null;
  84935. /**
  84936. * Post-process used to create a depth of field effect
  84937. */
  84938. _this.depthOfFieldPostProcess = null;
  84939. /**
  84940. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  84941. */
  84942. _this.fxaaPostProcess = null;
  84943. // Values
  84944. /**
  84945. * Represents the brightness threshold in order to configure the illuminated surfaces
  84946. */
  84947. _this.brightThreshold = 1.0;
  84948. /**
  84949. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  84950. */
  84951. _this.blurWidth = 512.0;
  84952. /**
  84953. * Sets if the blur for highlighted surfaces must be only horizontal
  84954. */
  84955. _this.horizontalBlur = false;
  84956. /**
  84957. * Sets the overall exposure used by the pipeline
  84958. */
  84959. _this.exposure = 1.0;
  84960. /**
  84961. * Texture used typically to simulate "dirty" on camera lens
  84962. */
  84963. _this.lensTexture = null;
  84964. /**
  84965. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  84966. */
  84967. _this.volumetricLightCoefficient = 0.2;
  84968. /**
  84969. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  84970. */
  84971. _this.volumetricLightPower = 4.0;
  84972. /**
  84973. * Used the set the blur intensity to smooth the volumetric lights
  84974. */
  84975. _this.volumetricLightBlurScale = 64.0;
  84976. /**
  84977. * Light (spot or directional) used to generate the volumetric lights rays
  84978. * The source light must have a shadow generate so the pipeline can get its
  84979. * depth map
  84980. */
  84981. _this.sourceLight = null;
  84982. /**
  84983. * For eye adaptation, represents the minimum luminance the eye can see
  84984. */
  84985. _this.hdrMinimumLuminance = 1.0;
  84986. /**
  84987. * For eye adaptation, represents the decrease luminance speed
  84988. */
  84989. _this.hdrDecreaseRate = 0.5;
  84990. /**
  84991. * For eye adaptation, represents the increase luminance speed
  84992. */
  84993. _this.hdrIncreaseRate = 0.5;
  84994. /**
  84995. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  84996. */
  84997. _this.lensColorTexture = null;
  84998. /**
  84999. * The overall strengh for the lens flare effect
  85000. */
  85001. _this.lensFlareStrength = 20.0;
  85002. /**
  85003. * Dispersion coefficient for lens flare ghosts
  85004. */
  85005. _this.lensFlareGhostDispersal = 1.4;
  85006. /**
  85007. * Main lens flare halo width
  85008. */
  85009. _this.lensFlareHaloWidth = 0.7;
  85010. /**
  85011. * Based on the lens distortion effect, defines how much the lens flare result
  85012. * is distorted
  85013. */
  85014. _this.lensFlareDistortionStrength = 16.0;
  85015. /**
  85016. * Lens star texture must be used to simulate rays on the flares and is available
  85017. * in the documentation
  85018. */
  85019. _this.lensStarTexture = null;
  85020. /**
  85021. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  85022. * flare effect by taking account of the dirt texture
  85023. */
  85024. _this.lensFlareDirtTexture = null;
  85025. /**
  85026. * Represents the focal length for the depth of field effect
  85027. */
  85028. _this.depthOfFieldDistance = 10.0;
  85029. /**
  85030. * Represents the blur intensity for the blurred part of the depth of field effect
  85031. */
  85032. _this.depthOfFieldBlurWidth = 64.0;
  85033. /**
  85034. * For motion blur, defines how much the image is blurred by the movement
  85035. */
  85036. _this.motionStrength = 1.0;
  85037. /**
  85038. * List of animations for the pipeline (IAnimatable implementation)
  85039. */
  85040. _this.animations = [];
  85041. _this._currentDepthOfFieldSource = null;
  85042. _this._hdrCurrentLuminance = 1.0;
  85043. // Getters and setters
  85044. _this._bloomEnabled = false;
  85045. _this._depthOfFieldEnabled = false;
  85046. _this._vlsEnabled = false;
  85047. _this._lensFlareEnabled = false;
  85048. _this._hdrEnabled = false;
  85049. _this._motionBlurEnabled = false;
  85050. _this._fxaaEnabled = false;
  85051. _this._motionBlurSamples = 64.0;
  85052. _this._volumetricLightStepsCount = 50.0;
  85053. _this._samples = 1;
  85054. _this._cameras = cameras || [];
  85055. // Initialize
  85056. _this._scene = scene;
  85057. _this._basePostProcess = originalPostProcess;
  85058. _this._ratio = ratio;
  85059. // Misc
  85060. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85061. // Finish
  85062. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85063. _this._buildPipeline();
  85064. return _this;
  85065. }
  85066. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  85067. /**
  85068. * @ignore
  85069. * Specifies if the bloom pipeline is enabled
  85070. */
  85071. get: function () {
  85072. return this._bloomEnabled;
  85073. },
  85074. set: function (enabled) {
  85075. if (this._bloomEnabled === enabled) {
  85076. return;
  85077. }
  85078. this._bloomEnabled = enabled;
  85079. this._buildPipeline();
  85080. },
  85081. enumerable: true,
  85082. configurable: true
  85083. });
  85084. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  85085. /**
  85086. * @ignore
  85087. * Specifies if the depth of field pipeline is enabed
  85088. */
  85089. get: function () {
  85090. return this._depthOfFieldEnabled;
  85091. },
  85092. set: function (enabled) {
  85093. if (this._depthOfFieldEnabled === enabled) {
  85094. return;
  85095. }
  85096. this._depthOfFieldEnabled = enabled;
  85097. this._buildPipeline();
  85098. },
  85099. enumerable: true,
  85100. configurable: true
  85101. });
  85102. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  85103. /**
  85104. * @ignore
  85105. * Specifies if the lens flare pipeline is enabed
  85106. */
  85107. get: function () {
  85108. return this._lensFlareEnabled;
  85109. },
  85110. set: function (enabled) {
  85111. if (this._lensFlareEnabled === enabled) {
  85112. return;
  85113. }
  85114. this._lensFlareEnabled = enabled;
  85115. this._buildPipeline();
  85116. },
  85117. enumerable: true,
  85118. configurable: true
  85119. });
  85120. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  85121. /**
  85122. * @ignore
  85123. * Specifies if the HDR pipeline is enabled
  85124. */
  85125. get: function () {
  85126. return this._hdrEnabled;
  85127. },
  85128. set: function (enabled) {
  85129. if (this._hdrEnabled === enabled) {
  85130. return;
  85131. }
  85132. this._hdrEnabled = enabled;
  85133. this._buildPipeline();
  85134. },
  85135. enumerable: true,
  85136. configurable: true
  85137. });
  85138. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  85139. /**
  85140. * @ignore
  85141. * Specifies if the volumetric lights scattering effect is enabled
  85142. */
  85143. get: function () {
  85144. return this._vlsEnabled;
  85145. },
  85146. set: function (enabled) {
  85147. if (this._vlsEnabled === enabled) {
  85148. return;
  85149. }
  85150. if (enabled) {
  85151. var geometry = this._scene.enableGeometryBufferRenderer();
  85152. if (!geometry) {
  85153. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  85154. return;
  85155. }
  85156. }
  85157. this._vlsEnabled = enabled;
  85158. this._buildPipeline();
  85159. },
  85160. enumerable: true,
  85161. configurable: true
  85162. });
  85163. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  85164. /**
  85165. * @ignore
  85166. * Specifies if the motion blur effect is enabled
  85167. */
  85168. get: function () {
  85169. return this._motionBlurEnabled;
  85170. },
  85171. set: function (enabled) {
  85172. if (this._motionBlurEnabled === enabled) {
  85173. return;
  85174. }
  85175. this._motionBlurEnabled = enabled;
  85176. this._buildPipeline();
  85177. },
  85178. enumerable: true,
  85179. configurable: true
  85180. });
  85181. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  85182. /**
  85183. * Specifies if anti-aliasing is enabled
  85184. */
  85185. get: function () {
  85186. return this._fxaaEnabled;
  85187. },
  85188. set: function (enabled) {
  85189. if (this._fxaaEnabled === enabled) {
  85190. return;
  85191. }
  85192. this._fxaaEnabled = enabled;
  85193. this._buildPipeline();
  85194. },
  85195. enumerable: true,
  85196. configurable: true
  85197. });
  85198. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  85199. /**
  85200. * Specifies the number of steps used to calculate the volumetric lights
  85201. * Typically in interval [50, 200]
  85202. */
  85203. get: function () {
  85204. return this._volumetricLightStepsCount;
  85205. },
  85206. set: function (count) {
  85207. if (this.volumetricLightPostProcess) {
  85208. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  85209. }
  85210. this._volumetricLightStepsCount = count;
  85211. },
  85212. enumerable: true,
  85213. configurable: true
  85214. });
  85215. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  85216. /**
  85217. * Specifies the number of samples used for the motion blur effect
  85218. * Typically in interval [16, 64]
  85219. */
  85220. get: function () {
  85221. return this._motionBlurSamples;
  85222. },
  85223. set: function (samples) {
  85224. if (this.motionBlurPostProcess) {
  85225. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  85226. }
  85227. this._motionBlurSamples = samples;
  85228. },
  85229. enumerable: true,
  85230. configurable: true
  85231. });
  85232. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  85233. /**
  85234. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  85235. */
  85236. get: function () {
  85237. return this._samples;
  85238. },
  85239. set: function (sampleCount) {
  85240. if (this._samples === sampleCount) {
  85241. return;
  85242. }
  85243. this._samples = sampleCount;
  85244. this._buildPipeline();
  85245. },
  85246. enumerable: true,
  85247. configurable: true
  85248. });
  85249. StandardRenderingPipeline.prototype._buildPipeline = function () {
  85250. var _this = this;
  85251. var ratio = this._ratio;
  85252. var scene = this._scene;
  85253. this._disposePostProcesses();
  85254. this._reset();
  85255. // Create pass post-process
  85256. if (!this._basePostProcess) {
  85257. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  85258. this.originalPostProcess.onApply = function (effect) {
  85259. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  85260. };
  85261. }
  85262. else {
  85263. this.originalPostProcess = this._basePostProcess;
  85264. }
  85265. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  85266. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  85267. }
  85268. this._currentDepthOfFieldSource = this.originalPostProcess;
  85269. if (this._bloomEnabled) {
  85270. // Create down sample X4 post-process
  85271. this._createDownSampleX4PostProcess(scene, ratio / 2);
  85272. // Create bright pass post-process
  85273. this._createBrightPassPostProcess(scene, ratio / 2);
  85274. // Create gaussian blur post-processes (down sampling blurs)
  85275. this._createBlurPostProcesses(scene, ratio / 4, 1);
  85276. // Create texture adder post-process
  85277. this._createTextureAdderPostProcess(scene, ratio);
  85278. // Create depth-of-field source post-process
  85279. 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);
  85280. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  85281. }
  85282. if (this._vlsEnabled) {
  85283. // Create volumetric light
  85284. this._createVolumetricLightPostProcess(scene, ratio);
  85285. // Create volumetric light final post-process
  85286. 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);
  85287. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  85288. }
  85289. if (this._lensFlareEnabled) {
  85290. // Create lens flare post-process
  85291. this._createLensFlarePostProcess(scene, ratio);
  85292. // Create depth-of-field source post-process post lens-flare and disable it now
  85293. 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);
  85294. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  85295. }
  85296. if (this._hdrEnabled) {
  85297. // Create luminance
  85298. this._createLuminancePostProcesses(scene, this._floatTextureType);
  85299. // Create HDR
  85300. this._createHdrPostProcess(scene, ratio);
  85301. // Create depth-of-field source post-process post hdr and disable it now
  85302. 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);
  85303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  85304. }
  85305. if (this._depthOfFieldEnabled) {
  85306. // Create gaussian blur used by depth-of-field
  85307. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  85308. // Create depth-of-field post-process
  85309. this._createDepthOfFieldPostProcess(scene, ratio);
  85310. }
  85311. if (this._motionBlurEnabled) {
  85312. // Create motion blur post-process
  85313. this._createMotionBlurPostProcess(scene, ratio);
  85314. }
  85315. if (this._fxaaEnabled) {
  85316. // Create fxaa post-process
  85317. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85318. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  85319. }
  85320. if (this._cameras !== null) {
  85321. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  85322. }
  85323. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  85324. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  85325. }
  85326. };
  85327. // Down Sample X4 Post-Processs
  85328. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  85329. var _this = this;
  85330. var downSampleX4Offsets = new Array(32);
  85331. 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);
  85332. this.downSampleX4PostProcess.onApply = function (effect) {
  85333. var id = 0;
  85334. var width = _this.downSampleX4PostProcess.width;
  85335. var height = _this.downSampleX4PostProcess.height;
  85336. for (var i = -2; i < 2; i++) {
  85337. for (var j = -2; j < 2; j++) {
  85338. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  85339. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  85340. id += 2;
  85341. }
  85342. }
  85343. effect.setArray2("dsOffsets", downSampleX4Offsets);
  85344. };
  85345. // Add to pipeline
  85346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  85347. };
  85348. // Brightpass Post-Process
  85349. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  85350. var _this = this;
  85351. var brightOffsets = new Array(8);
  85352. 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);
  85353. this.brightPassPostProcess.onApply = function (effect) {
  85354. var sU = (1.0 / _this.brightPassPostProcess.width);
  85355. var sV = (1.0 / _this.brightPassPostProcess.height);
  85356. brightOffsets[0] = -0.5 * sU;
  85357. brightOffsets[1] = 0.5 * sV;
  85358. brightOffsets[2] = 0.5 * sU;
  85359. brightOffsets[3] = 0.5 * sV;
  85360. brightOffsets[4] = -0.5 * sU;
  85361. brightOffsets[5] = -0.5 * sV;
  85362. brightOffsets[6] = 0.5 * sU;
  85363. brightOffsets[7] = -0.5 * sV;
  85364. effect.setArray2("dsOffsets", brightOffsets);
  85365. effect.setFloat("brightThreshold", _this.brightThreshold);
  85366. };
  85367. // Add to pipeline
  85368. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  85369. };
  85370. // Create blur H&V post-processes
  85371. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  85372. var _this = this;
  85373. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  85374. var engine = scene.getEngine();
  85375. 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);
  85376. 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);
  85377. blurX.onActivateObservable.add(function () {
  85378. var dw = blurX.width / engine.getRenderWidth();
  85379. blurX.kernel = _this[blurWidthKey] * dw;
  85380. });
  85381. blurY.onActivateObservable.add(function () {
  85382. var dw = blurY.height / engine.getRenderHeight();
  85383. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  85384. });
  85385. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  85386. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  85387. this.blurHPostProcesses.push(blurX);
  85388. this.blurVPostProcesses.push(blurY);
  85389. };
  85390. // Create texture adder post-process
  85391. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  85392. var _this = this;
  85393. 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);
  85394. this.textureAdderPostProcess.onApply = function (effect) {
  85395. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  85396. effect.setTexture("lensSampler", _this.lensTexture);
  85397. effect.setFloat("exposure", _this.exposure);
  85398. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  85399. };
  85400. // Add to pipeline
  85401. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  85402. };
  85403. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  85404. var _this = this;
  85405. var geometryRenderer = scene.enableGeometryBufferRenderer();
  85406. geometryRenderer.enablePosition = true;
  85407. var geometry = geometryRenderer.getGBuffer();
  85408. // Base post-process
  85409. 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));
  85410. var depthValues = BABYLON.Vector2.Zero();
  85411. this.volumetricLightPostProcess.onApply = function (effect) {
  85412. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  85413. var generator = _this.sourceLight.getShadowGenerator();
  85414. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  85415. effect.setTexture("positionSampler", geometry.textures[2]);
  85416. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  85417. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  85418. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  85419. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  85420. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  85421. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  85422. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  85423. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  85424. effect.setVector2("depthValues", depthValues);
  85425. }
  85426. };
  85427. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  85428. // Smooth
  85429. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  85430. // Merge
  85431. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  85432. this.volumetricLightMergePostProces.onApply = function (effect) {
  85433. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  85434. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  85435. };
  85436. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  85437. };
  85438. // Create luminance
  85439. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  85440. var _this = this;
  85441. // Create luminance
  85442. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  85443. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  85444. var offsets = [];
  85445. this.luminancePostProcess.onApply = function (effect) {
  85446. var sU = (1.0 / _this.luminancePostProcess.width);
  85447. var sV = (1.0 / _this.luminancePostProcess.height);
  85448. offsets[0] = -0.5 * sU;
  85449. offsets[1] = 0.5 * sV;
  85450. offsets[2] = 0.5 * sU;
  85451. offsets[3] = 0.5 * sV;
  85452. offsets[4] = -0.5 * sU;
  85453. offsets[5] = -0.5 * sV;
  85454. offsets[6] = 0.5 * sU;
  85455. offsets[7] = -0.5 * sV;
  85456. effect.setArray2("lumOffsets", offsets);
  85457. };
  85458. // Add to pipeline
  85459. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  85460. // Create down sample luminance
  85461. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  85462. var size = Math.pow(3, i);
  85463. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  85464. if (i === 0) {
  85465. defines += "#define FINAL_DOWN_SAMPLER";
  85466. }
  85467. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  85468. this.luminanceDownSamplePostProcesses.push(postProcess);
  85469. }
  85470. // Create callbacks and add effects
  85471. var lastLuminance = this.luminancePostProcess;
  85472. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  85473. var downSampleOffsets = new Array(18);
  85474. pp.onApply = function (effect) {
  85475. if (!lastLuminance) {
  85476. return;
  85477. }
  85478. var id = 0;
  85479. for (var x = -1; x < 2; x++) {
  85480. for (var y = -1; y < 2; y++) {
  85481. downSampleOffsets[id] = x / lastLuminance.width;
  85482. downSampleOffsets[id + 1] = y / lastLuminance.height;
  85483. id += 2;
  85484. }
  85485. }
  85486. effect.setArray2("dsOffsets", downSampleOffsets);
  85487. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  85488. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85489. lastLuminance = _this.luminancePostProcess;
  85490. }
  85491. else {
  85492. lastLuminance = pp;
  85493. }
  85494. };
  85495. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85496. pp.onAfterRender = function (effect) {
  85497. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  85498. 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);
  85499. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  85500. };
  85501. }
  85502. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  85503. });
  85504. };
  85505. // Create HDR post-process
  85506. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  85507. var _this = this;
  85508. 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);
  85509. var outputLiminance = 1;
  85510. var time = 0;
  85511. var lastTime = 0;
  85512. this.hdrPostProcess.onApply = function (effect) {
  85513. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  85514. time += scene.getEngine().getDeltaTime();
  85515. if (outputLiminance < 0) {
  85516. outputLiminance = _this._hdrCurrentLuminance;
  85517. }
  85518. else {
  85519. var dt = (lastTime - time) / 1000.0;
  85520. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  85521. outputLiminance += _this.hdrDecreaseRate * dt;
  85522. }
  85523. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  85524. outputLiminance -= _this.hdrIncreaseRate * dt;
  85525. }
  85526. else {
  85527. outputLiminance = _this._hdrCurrentLuminance;
  85528. }
  85529. }
  85530. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  85531. effect.setFloat("averageLuminance", outputLiminance);
  85532. lastTime = time;
  85533. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  85534. };
  85535. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  85536. };
  85537. // Create lens flare post-process
  85538. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  85539. var _this = this;
  85540. 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);
  85541. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  85542. this._createBlurPostProcesses(scene, ratio / 4, 2);
  85543. 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);
  85544. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  85545. var resolution = new BABYLON.Vector2(0, 0);
  85546. // Lens flare
  85547. this.lensFlarePostProcess.onApply = function (effect) {
  85548. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  85549. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  85550. effect.setFloat("strength", _this.lensFlareStrength);
  85551. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  85552. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  85553. // Shift
  85554. resolution.x = _this.lensFlarePostProcess.width;
  85555. resolution.y = _this.lensFlarePostProcess.height;
  85556. effect.setVector2("resolution", resolution);
  85557. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  85558. };
  85559. // Compose
  85560. 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);
  85561. 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);
  85562. this.lensFlareComposePostProcess.onApply = function (effect) {
  85563. if (!_this._scene.activeCamera) {
  85564. return;
  85565. }
  85566. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85567. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  85568. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  85569. // Lens start rotation matrix
  85570. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  85571. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  85572. 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));
  85573. camRot *= 4.0;
  85574. 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);
  85575. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  85576. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  85577. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  85578. };
  85579. };
  85580. // Create depth-of-field post-process
  85581. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  85582. var _this = this;
  85583. 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);
  85584. this.depthOfFieldPostProcess.onApply = function (effect) {
  85585. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85586. effect.setTexture("depthSampler", _this._getDepthTexture());
  85587. effect.setFloat("distance", _this.depthOfFieldDistance);
  85588. };
  85589. // Add to pipeline
  85590. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  85591. };
  85592. // Create motion blur post-process
  85593. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  85594. var _this = this;
  85595. 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);
  85596. var motionScale = 0;
  85597. var prevViewProjection = BABYLON.Matrix.Identity();
  85598. var invViewProjection = BABYLON.Matrix.Identity();
  85599. var viewProjection = BABYLON.Matrix.Identity();
  85600. var screenSize = BABYLON.Vector2.Zero();
  85601. this.motionBlurPostProcess.onApply = function (effect) {
  85602. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  85603. viewProjection.invertToRef(invViewProjection);
  85604. effect.setMatrix("inverseViewProjection", invViewProjection);
  85605. effect.setMatrix("prevViewProjection", prevViewProjection);
  85606. prevViewProjection = viewProjection;
  85607. screenSize.x = _this.motionBlurPostProcess.width;
  85608. screenSize.y = _this.motionBlurPostProcess.height;
  85609. effect.setVector2("screenSize", screenSize);
  85610. motionScale = scene.getEngine().getFps() / 60.0;
  85611. effect.setFloat("motionScale", motionScale);
  85612. effect.setFloat("motionStrength", _this.motionStrength);
  85613. effect.setTexture("depthSampler", _this._getDepthTexture());
  85614. };
  85615. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  85616. };
  85617. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  85618. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  85619. var renderer = this._scene.enableGeometryBufferRenderer();
  85620. return renderer.getGBuffer().textures[0];
  85621. }
  85622. return this._scene.enableDepthRenderer().getDepthMap();
  85623. };
  85624. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  85625. for (var i = 0; i < this._cameras.length; i++) {
  85626. var camera = this._cameras[i];
  85627. if (this.originalPostProcess) {
  85628. this.originalPostProcess.dispose(camera);
  85629. }
  85630. if (this.downSampleX4PostProcess) {
  85631. this.downSampleX4PostProcess.dispose(camera);
  85632. }
  85633. if (this.brightPassPostProcess) {
  85634. this.brightPassPostProcess.dispose(camera);
  85635. }
  85636. if (this.textureAdderPostProcess) {
  85637. this.textureAdderPostProcess.dispose(camera);
  85638. }
  85639. if (this.textureAdderFinalPostProcess) {
  85640. this.textureAdderFinalPostProcess.dispose(camera);
  85641. }
  85642. if (this.volumetricLightPostProcess) {
  85643. this.volumetricLightPostProcess.dispose(camera);
  85644. }
  85645. if (this.volumetricLightSmoothXPostProcess) {
  85646. this.volumetricLightSmoothXPostProcess.dispose(camera);
  85647. }
  85648. if (this.volumetricLightSmoothYPostProcess) {
  85649. this.volumetricLightSmoothYPostProcess.dispose(camera);
  85650. }
  85651. if (this.volumetricLightMergePostProces) {
  85652. this.volumetricLightMergePostProces.dispose(camera);
  85653. }
  85654. if (this.volumetricLightFinalPostProcess) {
  85655. this.volumetricLightFinalPostProcess.dispose(camera);
  85656. }
  85657. if (this.lensFlarePostProcess) {
  85658. this.lensFlarePostProcess.dispose(camera);
  85659. }
  85660. if (this.lensFlareComposePostProcess) {
  85661. this.lensFlareComposePostProcess.dispose(camera);
  85662. }
  85663. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  85664. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  85665. }
  85666. if (this.luminancePostProcess) {
  85667. this.luminancePostProcess.dispose(camera);
  85668. }
  85669. if (this.hdrPostProcess) {
  85670. this.hdrPostProcess.dispose(camera);
  85671. }
  85672. if (this.hdrFinalPostProcess) {
  85673. this.hdrFinalPostProcess.dispose(camera);
  85674. }
  85675. if (this.depthOfFieldPostProcess) {
  85676. this.depthOfFieldPostProcess.dispose(camera);
  85677. }
  85678. if (this.motionBlurPostProcess) {
  85679. this.motionBlurPostProcess.dispose(camera);
  85680. }
  85681. if (this.fxaaPostProcess) {
  85682. this.fxaaPostProcess.dispose(camera);
  85683. }
  85684. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  85685. this.blurHPostProcesses[j].dispose(camera);
  85686. }
  85687. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  85688. this.blurVPostProcesses[j].dispose(camera);
  85689. }
  85690. }
  85691. this.originalPostProcess = null;
  85692. this.downSampleX4PostProcess = null;
  85693. this.brightPassPostProcess = null;
  85694. this.textureAdderPostProcess = null;
  85695. this.textureAdderFinalPostProcess = null;
  85696. this.volumetricLightPostProcess = null;
  85697. this.volumetricLightSmoothXPostProcess = null;
  85698. this.volumetricLightSmoothYPostProcess = null;
  85699. this.volumetricLightMergePostProces = null;
  85700. this.volumetricLightFinalPostProcess = null;
  85701. this.lensFlarePostProcess = null;
  85702. this.lensFlareComposePostProcess = null;
  85703. this.luminancePostProcess = null;
  85704. this.hdrPostProcess = null;
  85705. this.hdrFinalPostProcess = null;
  85706. this.depthOfFieldPostProcess = null;
  85707. this.motionBlurPostProcess = null;
  85708. this.fxaaPostProcess = null;
  85709. this.luminanceDownSamplePostProcesses = [];
  85710. this.blurHPostProcesses = [];
  85711. this.blurVPostProcesses = [];
  85712. };
  85713. /**
  85714. * Dispose of the pipeline and stop all post processes
  85715. */
  85716. StandardRenderingPipeline.prototype.dispose = function () {
  85717. this._disposePostProcesses();
  85718. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85719. _super.prototype.dispose.call(this);
  85720. };
  85721. /**
  85722. * Serialize the rendering pipeline (Used when exporting)
  85723. * @returns the serialized object
  85724. */
  85725. StandardRenderingPipeline.prototype.serialize = function () {
  85726. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85727. if (this.sourceLight) {
  85728. serializationObject.sourceLightId = this.sourceLight.id;
  85729. }
  85730. serializationObject.customType = "StandardRenderingPipeline";
  85731. return serializationObject;
  85732. };
  85733. /**
  85734. * Parse the serialized pipeline
  85735. * @param source Source pipeline.
  85736. * @param scene The scene to load the pipeline to.
  85737. * @param rootUrl The URL of the serialized pipeline.
  85738. * @returns An instantiated pipeline from the serialized object.
  85739. */
  85740. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  85741. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85742. if (source.sourceLightId) {
  85743. p.sourceLight = scene.getLightByID(source.sourceLightId);
  85744. }
  85745. return p;
  85746. };
  85747. /**
  85748. * Luminance steps
  85749. */
  85750. StandardRenderingPipeline.LuminanceSteps = 6;
  85751. __decorate([
  85752. BABYLON.serialize()
  85753. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  85754. __decorate([
  85755. BABYLON.serialize()
  85756. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  85757. __decorate([
  85758. BABYLON.serialize()
  85759. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  85760. __decorate([
  85761. BABYLON.serialize()
  85762. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  85763. __decorate([
  85764. BABYLON.serializeAsTexture("lensTexture")
  85765. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  85766. __decorate([
  85767. BABYLON.serialize()
  85768. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  85769. __decorate([
  85770. BABYLON.serialize()
  85771. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  85772. __decorate([
  85773. BABYLON.serialize()
  85774. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  85775. __decorate([
  85776. BABYLON.serialize()
  85777. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  85778. __decorate([
  85779. BABYLON.serialize()
  85780. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  85781. __decorate([
  85782. BABYLON.serialize()
  85783. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  85784. __decorate([
  85785. BABYLON.serializeAsTexture("lensColorTexture")
  85786. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  85787. __decorate([
  85788. BABYLON.serialize()
  85789. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  85790. __decorate([
  85791. BABYLON.serialize()
  85792. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  85793. __decorate([
  85794. BABYLON.serialize()
  85795. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  85796. __decorate([
  85797. BABYLON.serialize()
  85798. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  85799. __decorate([
  85800. BABYLON.serializeAsTexture("lensStarTexture")
  85801. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  85802. __decorate([
  85803. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  85804. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  85805. __decorate([
  85806. BABYLON.serialize()
  85807. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  85808. __decorate([
  85809. BABYLON.serialize()
  85810. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  85811. __decorate([
  85812. BABYLON.serialize()
  85813. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  85814. __decorate([
  85815. BABYLON.serialize()
  85816. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  85817. __decorate([
  85818. BABYLON.serialize()
  85819. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  85820. __decorate([
  85821. BABYLON.serialize()
  85822. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  85823. __decorate([
  85824. BABYLON.serialize()
  85825. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  85826. __decorate([
  85827. BABYLON.serialize()
  85828. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  85829. __decorate([
  85830. BABYLON.serialize()
  85831. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  85832. __decorate([
  85833. BABYLON.serialize()
  85834. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  85835. __decorate([
  85836. BABYLON.serialize()
  85837. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  85838. __decorate([
  85839. BABYLON.serialize()
  85840. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  85841. __decorate([
  85842. BABYLON.serialize()
  85843. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  85844. __decorate([
  85845. BABYLON.serialize()
  85846. ], StandardRenderingPipeline.prototype, "samples", null);
  85847. return StandardRenderingPipeline;
  85848. }(BABYLON.PostProcessRenderPipeline));
  85849. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  85850. })(BABYLON || (BABYLON = {}));
  85851. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  85852. var BABYLON;
  85853. (function (BABYLON) {
  85854. /**
  85855. * Fxaa post process
  85856. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  85857. */
  85858. var FxaaPostProcess = /** @class */ (function (_super) {
  85859. __extends(FxaaPostProcess, _super);
  85860. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85861. if (camera === void 0) { camera = null; }
  85862. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85863. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  85864. var defines = _this._getDefines();
  85865. _this.updateEffect(defines);
  85866. _this.onApplyObservable.add(function (effect) {
  85867. var texelSize = _this.texelSize;
  85868. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  85869. });
  85870. return _this;
  85871. }
  85872. FxaaPostProcess.prototype._getDefines = function () {
  85873. var engine = this.getEngine();
  85874. if (!engine) {
  85875. return null;
  85876. }
  85877. var glInfo = engine.getGlInfo();
  85878. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  85879. return "#define MALI 1\n";
  85880. }
  85881. return null;
  85882. };
  85883. return FxaaPostProcess;
  85884. }(BABYLON.PostProcess));
  85885. BABYLON.FxaaPostProcess = FxaaPostProcess;
  85886. })(BABYLON || (BABYLON = {}));
  85887. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  85888. var BABYLON;
  85889. (function (BABYLON) {
  85890. /**
  85891. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  85892. */
  85893. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  85894. __extends(ChromaticAberrationPostProcess, _super);
  85895. /**
  85896. * Creates a new instance ChromaticAberrationPostProcess
  85897. * @param name The name of the effect.
  85898. * @param screenWidth The width of the screen to apply the effect on.
  85899. * @param screenHeight The height of the screen to apply the effect on.
  85900. * @param options The required width/height ratio to downsize to before computing the render pass.
  85901. * @param camera The camera to apply the render pass to.
  85902. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85903. * @param engine The engine which the post process will be applied. (default: current engine)
  85904. * @param reusable If the post process can be reused on the same frame. (default: false)
  85905. * @param textureType Type of textures used when performing the post process. (default: 0)
  85906. * @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)
  85907. */
  85908. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85909. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85910. if (blockCompilation === void 0) { blockCompilation = false; }
  85911. 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;
  85912. /**
  85913. * The amount of seperation of rgb channels (default: 30)
  85914. */
  85915. _this.aberrationAmount = 30;
  85916. /**
  85917. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  85918. */
  85919. _this.radialIntensity = 0;
  85920. /**
  85921. * 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))
  85922. */
  85923. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  85924. /**
  85925. * 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))
  85926. */
  85927. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  85928. _this.onApplyObservable.add(function (effect) {
  85929. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  85930. effect.setFloat('screen_width', screenWidth);
  85931. effect.setFloat('screen_height', screenHeight);
  85932. effect.setFloat('radialIntensity', _this.radialIntensity);
  85933. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  85934. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  85935. });
  85936. return _this;
  85937. }
  85938. return ChromaticAberrationPostProcess;
  85939. }(BABYLON.PostProcess));
  85940. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  85941. })(BABYLON || (BABYLON = {}));
  85942. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  85943. var BABYLON;
  85944. (function (BABYLON) {
  85945. /**
  85946. * The GrainPostProcess adds noise to the image at mid luminance levels
  85947. */
  85948. var GrainPostProcess = /** @class */ (function (_super) {
  85949. __extends(GrainPostProcess, _super);
  85950. /**
  85951. * Creates a new instance of @see GrainPostProcess
  85952. * @param name The name of the effect.
  85953. * @param options The required width/height ratio to downsize to before computing the render pass.
  85954. * @param camera The camera to apply the render pass to.
  85955. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85956. * @param engine The engine which the post process will be applied. (default: current engine)
  85957. * @param reusable If the post process can be reused on the same frame. (default: false)
  85958. * @param textureType Type of textures used when performing the post process. (default: 0)
  85959. * @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)
  85960. */
  85961. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85962. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85963. if (blockCompilation === void 0) { blockCompilation = false; }
  85964. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85965. /**
  85966. * The intensity of the grain added (default: 30)
  85967. */
  85968. _this.intensity = 30;
  85969. /**
  85970. * If the grain should be randomized on every frame
  85971. */
  85972. _this.animated = false;
  85973. _this.onApplyObservable.add(function (effect) {
  85974. effect.setFloat('intensity', _this.intensity);
  85975. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  85976. });
  85977. return _this;
  85978. }
  85979. return GrainPostProcess;
  85980. }(BABYLON.PostProcess));
  85981. BABYLON.GrainPostProcess = GrainPostProcess;
  85982. })(BABYLON || (BABYLON = {}));
  85983. //# sourceMappingURL=babylon.grainPostProcess.js.map
  85984. var BABYLON;
  85985. (function (BABYLON) {
  85986. /**
  85987. * The SharpenPostProcess applies a sharpen kernel to every pixel
  85988. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  85989. */
  85990. var SharpenPostProcess = /** @class */ (function (_super) {
  85991. __extends(SharpenPostProcess, _super);
  85992. /**
  85993. * Creates a new instance ConvolutionPostProcess
  85994. * @param name The name of the effect.
  85995. * @param options The required width/height ratio to downsize to before computing the render pass.
  85996. * @param camera The camera to apply the render pass to.
  85997. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85998. * @param engine The engine which the post process will be applied. (default: current engine)
  85999. * @param reusable If the post process can be reused on the same frame. (default: false)
  86000. * @param textureType Type of textures used when performing the post process. (default: 0)
  86001. * @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)
  86002. */
  86003. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86004. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86005. if (blockCompilation === void 0) { blockCompilation = false; }
  86006. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86007. /**
  86008. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  86009. */
  86010. _this.colorAmount = 1.0;
  86011. /**
  86012. * How much sharpness should be applied (default: 0.3)
  86013. */
  86014. _this.edgeAmount = 0.3;
  86015. _this.onApply = function (effect) {
  86016. effect.setFloat2("screenSize", _this.width, _this.height);
  86017. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  86018. };
  86019. return _this;
  86020. }
  86021. return SharpenPostProcess;
  86022. }(BABYLON.PostProcess));
  86023. BABYLON.SharpenPostProcess = SharpenPostProcess;
  86024. })(BABYLON || (BABYLON = {}));
  86025. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  86026. var BABYLON;
  86027. (function (BABYLON) {
  86028. /**
  86029. * The Blur Post Process which blurs an image based on a kernel and direction.
  86030. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  86031. */
  86032. var BlurPostProcess = /** @class */ (function (_super) {
  86033. __extends(BlurPostProcess, _super);
  86034. /**
  86035. * Creates a new instance BlurPostProcess
  86036. * @param name The name of the effect.
  86037. * @param direction The direction in which to blur the image.
  86038. * @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.
  86039. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  86040. * @param camera The camera to apply the render pass to.
  86041. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86042. * @param engine The engine which the post process will be applied. (default: current engine)
  86043. * @param reusable If the post process can be reused on the same frame. (default: false)
  86044. * @param textureType Type of textures used when performing the post process. (default: 0)
  86045. * @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)
  86046. */
  86047. function BlurPostProcess(name,
  86048. /** The direction in which to blur the image. */
  86049. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  86050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86051. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86052. if (defines === void 0) { defines = ""; }
  86053. if (blockCompilation === void 0) { blockCompilation = false; }
  86054. 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;
  86055. _this.direction = direction;
  86056. _this.blockCompilation = blockCompilation;
  86057. _this._packedFloat = false;
  86058. _this._staticDefines = "";
  86059. _this._staticDefines = defines;
  86060. _this.onApplyObservable.add(function (effect) {
  86061. if (_this._outputTexture) {
  86062. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  86063. }
  86064. else {
  86065. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  86066. }
  86067. });
  86068. _this.kernel = kernel;
  86069. return _this;
  86070. }
  86071. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  86072. /**
  86073. * Gets the length in pixels of the blur sample region
  86074. */
  86075. get: function () {
  86076. return this._idealKernel;
  86077. },
  86078. /**
  86079. * Sets the length in pixels of the blur sample region
  86080. */
  86081. set: function (v) {
  86082. if (this._idealKernel === v) {
  86083. return;
  86084. }
  86085. v = Math.max(v, 1);
  86086. this._idealKernel = v;
  86087. this._kernel = this._nearestBestKernel(v);
  86088. if (!this.blockCompilation) {
  86089. this._updateParameters();
  86090. }
  86091. },
  86092. enumerable: true,
  86093. configurable: true
  86094. });
  86095. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  86096. /**
  86097. * Gets wether or not the blur is unpacking/repacking floats
  86098. */
  86099. get: function () {
  86100. return this._packedFloat;
  86101. },
  86102. /**
  86103. * Sets wether or not the blur needs to unpack/repack floats
  86104. */
  86105. set: function (v) {
  86106. if (this._packedFloat === v) {
  86107. return;
  86108. }
  86109. this._packedFloat = v;
  86110. if (!this.blockCompilation) {
  86111. this._updateParameters();
  86112. }
  86113. },
  86114. enumerable: true,
  86115. configurable: true
  86116. });
  86117. /**
  86118. * Updates the effect with the current post process compile time values and recompiles the shader.
  86119. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86120. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86121. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86122. * @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
  86123. * @param onCompiled Called when the shader has been compiled.
  86124. * @param onError Called if there is an error when compiling a shader.
  86125. */
  86126. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86127. if (defines === void 0) { defines = null; }
  86128. if (uniforms === void 0) { uniforms = null; }
  86129. if (samplers === void 0) { samplers = null; }
  86130. this._updateParameters(onCompiled, onError);
  86131. };
  86132. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  86133. // Generate sampling offsets and weights
  86134. var N = this._kernel;
  86135. var centerIndex = (N - 1) / 2;
  86136. // Generate Gaussian sampling weights over kernel
  86137. var offsets = [];
  86138. var weights = [];
  86139. var totalWeight = 0;
  86140. for (var i = 0; i < N; i++) {
  86141. var u = i / (N - 1);
  86142. var w = this._gaussianWeight(u * 2.0 - 1);
  86143. offsets[i] = (i - centerIndex);
  86144. weights[i] = w;
  86145. totalWeight += w;
  86146. }
  86147. // Normalize weights
  86148. for (var i = 0; i < weights.length; i++) {
  86149. weights[i] /= totalWeight;
  86150. }
  86151. // Optimize: combine samples to take advantage of hardware linear sampling
  86152. // Walk from left to center, combining pairs (symmetrically)
  86153. var linearSamplingWeights = [];
  86154. var linearSamplingOffsets = [];
  86155. var linearSamplingMap = [];
  86156. for (var i = 0; i <= centerIndex; i += 2) {
  86157. var j = Math.min(i + 1, Math.floor(centerIndex));
  86158. var singleCenterSample = i === j;
  86159. if (singleCenterSample) {
  86160. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  86161. }
  86162. else {
  86163. var sharedCell = j === centerIndex;
  86164. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  86165. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  86166. if (offsetLinear === 0) {
  86167. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  86168. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  86169. }
  86170. else {
  86171. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  86172. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  86173. }
  86174. }
  86175. }
  86176. for (var i = 0; i < linearSamplingMap.length; i++) {
  86177. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  86178. linearSamplingWeights[i] = linearSamplingMap[i].w;
  86179. }
  86180. // Replace with optimized
  86181. offsets = linearSamplingOffsets;
  86182. weights = linearSamplingWeights;
  86183. // Generate shaders
  86184. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  86185. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  86186. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  86187. var defines = "";
  86188. defines += this._staticDefines;
  86189. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  86190. if (this._staticDefines.indexOf("DOF") != -1) {
  86191. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  86192. varyingCount--;
  86193. }
  86194. for (var i = 0; i < varyingCount; i++) {
  86195. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  86196. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  86197. }
  86198. var depCount = 0;
  86199. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  86200. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  86201. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  86202. depCount++;
  86203. }
  86204. if (this.packedFloat) {
  86205. defines += "#define PACKEDFLOAT 1";
  86206. }
  86207. this.blockCompilation = false;
  86208. _super.prototype.updateEffect.call(this, defines, null, null, {
  86209. varyingCount: varyingCount,
  86210. depCount: depCount
  86211. }, onCompiled, onError);
  86212. };
  86213. /**
  86214. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  86215. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  86216. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  86217. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  86218. * The gaps between physical kernels are compensated for in the weighting of the samples
  86219. * @param idealKernel Ideal blur kernel.
  86220. * @return Nearest best kernel.
  86221. */
  86222. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  86223. var v = Math.round(idealKernel);
  86224. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  86225. var k = _a[_i];
  86226. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  86227. return Math.max(k, 3);
  86228. }
  86229. }
  86230. return Math.max(v, 3);
  86231. };
  86232. /**
  86233. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  86234. * @param x The point on the Gaussian distribution to sample.
  86235. * @return the value of the Gaussian function at x.
  86236. */
  86237. BlurPostProcess.prototype._gaussianWeight = function (x) {
  86238. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  86239. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  86240. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  86241. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  86242. // truncated at around 1.3% of peak strength.
  86243. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  86244. var sigma = (1 / 3);
  86245. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  86246. var exponent = -((x * x) / (2.0 * sigma * sigma));
  86247. var weight = (1.0 / denominator) * Math.exp(exponent);
  86248. return weight;
  86249. };
  86250. /**
  86251. * Generates a string that can be used as a floating point number in GLSL.
  86252. * @param x Value to print.
  86253. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  86254. * @return GLSL float string.
  86255. */
  86256. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  86257. if (decimalFigures === void 0) { decimalFigures = 8; }
  86258. return x.toFixed(decimalFigures).replace(/0+$/, '');
  86259. };
  86260. return BlurPostProcess;
  86261. }(BABYLON.PostProcess));
  86262. BABYLON.BlurPostProcess = BlurPostProcess;
  86263. })(BABYLON || (BABYLON = {}));
  86264. //# sourceMappingURL=babylon.blurPostProcess.js.map
  86265. var BABYLON;
  86266. (function (BABYLON) {
  86267. /**
  86268. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  86269. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  86270. * based on samples that have a large difference in distance than the center pixel.
  86271. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86272. */
  86273. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  86274. __extends(DepthOfFieldBlurPostProcess, _super);
  86275. /**
  86276. * Creates a new instance CircleOfConfusionPostProcess
  86277. * @param name The name of the effect.
  86278. * @param scene The scene the effect belongs to.
  86279. * @param direction The direction the blur should be applied.
  86280. * @param kernel The size of the kernel used to blur.
  86281. * @param options The required width/height ratio to downsize to before computing the render pass.
  86282. * @param camera The camera to apply the render pass to.
  86283. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  86284. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  86285. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86286. * @param engine The engine which the post process will be applied. (default: current engine)
  86287. * @param reusable If the post process can be reused on the same frame. (default: false)
  86288. * @param textureType Type of textures used when performing the post process. (default: 0)
  86289. * @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)
  86290. */
  86291. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  86292. if (imageToBlur === void 0) { imageToBlur = null; }
  86293. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86294. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86295. if (blockCompilation === void 0) { blockCompilation = false; }
  86296. 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;
  86297. _this.direction = direction;
  86298. _this.onApplyObservable.add(function (effect) {
  86299. if (imageToBlur != null) {
  86300. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  86301. }
  86302. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86303. if (scene.activeCamera) {
  86304. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86305. }
  86306. });
  86307. return _this;
  86308. }
  86309. return DepthOfFieldBlurPostProcess;
  86310. }(BABYLON.BlurPostProcess));
  86311. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  86312. })(BABYLON || (BABYLON = {}));
  86313. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  86314. var BABYLON;
  86315. (function (BABYLON) {
  86316. /**
  86317. * Options to be set when merging outputs from the default pipeline.
  86318. */
  86319. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  86320. function DepthOfFieldMergePostProcessOptions() {
  86321. }
  86322. return DepthOfFieldMergePostProcessOptions;
  86323. }());
  86324. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  86325. /**
  86326. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86327. */
  86328. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  86329. __extends(DepthOfFieldMergePostProcess, _super);
  86330. /**
  86331. * Creates a new instance of DepthOfFieldMergePostProcess
  86332. * @param name The name of the effect.
  86333. * @param originalFromInput Post process which's input will be used for the merge.
  86334. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  86335. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  86336. * @param options The required width/height ratio to downsize to before computing the render pass.
  86337. * @param camera The camera to apply the render pass to.
  86338. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86339. * @param engine The engine which the post process will be applied. (default: current engine)
  86340. * @param reusable If the post process can be reused on the same frame. (default: false)
  86341. * @param textureType Type of textures used when performing the post process. (default: 0)
  86342. * @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)
  86343. */
  86344. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86345. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86346. if (blockCompilation === void 0) { blockCompilation = false; }
  86347. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86348. _this.blurSteps = blurSteps;
  86349. _this.onApplyObservable.add(function (effect) {
  86350. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86351. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86352. blurSteps.forEach(function (step, index) {
  86353. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  86354. });
  86355. });
  86356. if (!blockCompilation) {
  86357. _this.updateEffect();
  86358. }
  86359. return _this;
  86360. }
  86361. /**
  86362. * Updates the effect with the current post process compile time values and recompiles the shader.
  86363. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86364. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86365. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86366. * @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
  86367. * @param onCompiled Called when the shader has been compiled.
  86368. * @param onError Called if there is an error when compiling a shader.
  86369. */
  86370. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86371. if (defines === void 0) { defines = null; }
  86372. if (uniforms === void 0) { uniforms = null; }
  86373. if (samplers === void 0) { samplers = null; }
  86374. if (!defines) {
  86375. defines = "";
  86376. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  86377. }
  86378. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  86379. };
  86380. return DepthOfFieldMergePostProcess;
  86381. }(BABYLON.PostProcess));
  86382. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  86383. })(BABYLON || (BABYLON = {}));
  86384. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  86385. var BABYLON;
  86386. (function (BABYLON) {
  86387. /**
  86388. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  86389. */
  86390. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  86391. __extends(CircleOfConfusionPostProcess, _super);
  86392. /**
  86393. * Creates a new instance CircleOfConfusionPostProcess
  86394. * @param name The name of the effect.
  86395. * @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.
  86396. * @param options The required width/height ratio to downsize to before computing the render pass.
  86397. * @param camera The camera to apply the render pass to.
  86398. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86399. * @param engine The engine which the post process will be applied. (default: current engine)
  86400. * @param reusable If the post process can be reused on the same frame. (default: false)
  86401. * @param textureType Type of textures used when performing the post process. (default: 0)
  86402. * @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)
  86403. */
  86404. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86405. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86406. if (blockCompilation === void 0) { blockCompilation = false; }
  86407. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86408. /**
  86409. * 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.
  86410. */
  86411. _this.lensSize = 50;
  86412. /**
  86413. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86414. */
  86415. _this.fStop = 1.4;
  86416. /**
  86417. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86418. */
  86419. _this.focusDistance = 2000;
  86420. /**
  86421. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  86422. */
  86423. _this.focalLength = 50;
  86424. _this._depthTexture = null;
  86425. _this._depthTexture = depthTexture;
  86426. _this.onApplyObservable.add(function (effect) {
  86427. if (!_this._depthTexture) {
  86428. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  86429. return;
  86430. }
  86431. effect.setTexture("depthSampler", _this._depthTexture);
  86432. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  86433. var aperture = _this.lensSize / _this.fStop;
  86434. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  86435. effect.setFloat('focusDistance', _this.focusDistance);
  86436. effect.setFloat('cocPrecalculation', cocPrecalculation);
  86437. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  86438. });
  86439. return _this;
  86440. }
  86441. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  86442. /**
  86443. * 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.
  86444. */
  86445. set: function (value) {
  86446. this._depthTexture = value;
  86447. },
  86448. enumerable: true,
  86449. configurable: true
  86450. });
  86451. return CircleOfConfusionPostProcess;
  86452. }(BABYLON.PostProcess));
  86453. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  86454. })(BABYLON || (BABYLON = {}));
  86455. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  86456. var BABYLON;
  86457. (function (BABYLON) {
  86458. /**
  86459. * Specifies the level of max blur that should be applied when using the depth of field effect
  86460. */
  86461. var DepthOfFieldEffectBlurLevel;
  86462. (function (DepthOfFieldEffectBlurLevel) {
  86463. /**
  86464. * Subtle blur
  86465. */
  86466. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  86467. /**
  86468. * Medium blur
  86469. */
  86470. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  86471. /**
  86472. * Large blur
  86473. */
  86474. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  86475. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  86476. /**
  86477. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  86478. */
  86479. var DepthOfFieldEffect = /** @class */ (function (_super) {
  86480. __extends(DepthOfFieldEffect, _super);
  86481. /**
  86482. * Creates a new instance DepthOfFieldEffect
  86483. * @param scene The scene the effect belongs to.
  86484. * @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.
  86485. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86486. * @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)
  86487. */
  86488. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  86489. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  86490. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86491. if (blockCompilation === void 0) { blockCompilation = false; }
  86492. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  86493. return _this._effects;
  86494. }, true) || this;
  86495. /**
  86496. * @hidden Internal post processes in depth of field effect
  86497. */
  86498. _this._effects = [];
  86499. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  86500. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86501. // 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)
  86502. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  86503. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86504. _this._depthOfFieldBlurY = [];
  86505. _this._depthOfFieldBlurX = [];
  86506. var blurCount = 1;
  86507. var kernelSize = 15;
  86508. switch (blurLevel) {
  86509. case DepthOfFieldEffectBlurLevel.High: {
  86510. blurCount = 3;
  86511. kernelSize = 51;
  86512. break;
  86513. }
  86514. case DepthOfFieldEffectBlurLevel.Medium: {
  86515. blurCount = 2;
  86516. kernelSize = 31;
  86517. break;
  86518. }
  86519. default: {
  86520. kernelSize = 15;
  86521. blurCount = 1;
  86522. break;
  86523. }
  86524. }
  86525. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  86526. var ratio = 1.0;
  86527. for (var i = 0; i < blurCount; i++) {
  86528. 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);
  86529. blurY.autoClear = false;
  86530. ratio = 0.75 / Math.pow(2, i);
  86531. 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);
  86532. blurX.autoClear = false;
  86533. _this._depthOfFieldBlurY.push(blurY);
  86534. _this._depthOfFieldBlurX.push(blurX);
  86535. }
  86536. // Set all post processes on the effect.
  86537. _this._effects = [_this._circleOfConfusion];
  86538. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  86539. _this._effects.push(_this._depthOfFieldBlurY[i]);
  86540. _this._effects.push(_this._depthOfFieldBlurX[i]);
  86541. }
  86542. // Merge blurred images with original image based on circleOfConfusion
  86543. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86544. _this._dofMerge.autoClear = false;
  86545. _this._effects.push(_this._dofMerge);
  86546. return _this;
  86547. }
  86548. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  86549. get: function () {
  86550. return this._circleOfConfusion.focalLength;
  86551. },
  86552. /**
  86553. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  86554. */
  86555. set: function (value) {
  86556. this._circleOfConfusion.focalLength = value;
  86557. },
  86558. enumerable: true,
  86559. configurable: true
  86560. });
  86561. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  86562. get: function () {
  86563. return this._circleOfConfusion.fStop;
  86564. },
  86565. /**
  86566. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86567. */
  86568. set: function (value) {
  86569. this._circleOfConfusion.fStop = value;
  86570. },
  86571. enumerable: true,
  86572. configurable: true
  86573. });
  86574. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  86575. get: function () {
  86576. return this._circleOfConfusion.focusDistance;
  86577. },
  86578. /**
  86579. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86580. */
  86581. set: function (value) {
  86582. this._circleOfConfusion.focusDistance = value;
  86583. },
  86584. enumerable: true,
  86585. configurable: true
  86586. });
  86587. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  86588. get: function () {
  86589. return this._circleOfConfusion.lensSize;
  86590. },
  86591. /**
  86592. * 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.
  86593. */
  86594. set: function (value) {
  86595. this._circleOfConfusion.lensSize = value;
  86596. },
  86597. enumerable: true,
  86598. configurable: true
  86599. });
  86600. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  86601. /**
  86602. * 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.
  86603. */
  86604. set: function (value) {
  86605. this._circleOfConfusion.depthTexture = value;
  86606. },
  86607. enumerable: true,
  86608. configurable: true
  86609. });
  86610. /**
  86611. * Disposes each of the internal effects for a given camera.
  86612. * @param camera The camera to dispose the effect on.
  86613. */
  86614. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  86615. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86616. this._effects[effectIndex].dispose(camera);
  86617. }
  86618. };
  86619. /**
  86620. * @hidden Internal
  86621. */
  86622. DepthOfFieldEffect.prototype._updateEffects = function () {
  86623. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86624. this._effects[effectIndex].updateEffect();
  86625. }
  86626. };
  86627. /**
  86628. * Internal
  86629. * @returns if all the contained post processes are ready.
  86630. * @hidden
  86631. */
  86632. DepthOfFieldEffect.prototype._isReady = function () {
  86633. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86634. if (!this._effects[effectIndex].isReady()) {
  86635. return false;
  86636. }
  86637. }
  86638. return true;
  86639. };
  86640. return DepthOfFieldEffect;
  86641. }(BABYLON.PostProcessRenderEffect));
  86642. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  86643. })(BABYLON || (BABYLON = {}));
  86644. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  86645. var BABYLON;
  86646. (function (BABYLON) {
  86647. /**
  86648. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86649. */
  86650. var BloomMergePostProcess = /** @class */ (function (_super) {
  86651. __extends(BloomMergePostProcess, _super);
  86652. /**
  86653. * Creates a new instance of @see BloomMergePostProcess
  86654. * @param name The name of the effect.
  86655. * @param originalFromInput Post process which's input will be used for the merge.
  86656. * @param blurred Blurred highlights post process which's output will be used.
  86657. * @param weight Weight of the bloom to be added to the original input.
  86658. * @param options The required width/height ratio to downsize to before computing the render pass.
  86659. * @param camera The camera to apply the render pass to.
  86660. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86661. * @param engine The engine which the post process will be applied. (default: current engine)
  86662. * @param reusable If the post process can be reused on the same frame. (default: false)
  86663. * @param textureType Type of textures used when performing the post process. (default: 0)
  86664. * @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)
  86665. */
  86666. function BloomMergePostProcess(name, originalFromInput, blurred,
  86667. /** Weight of the bloom to be added to the original input. */
  86668. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86669. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86670. if (blockCompilation === void 0) { blockCompilation = false; }
  86671. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86672. _this.weight = weight;
  86673. _this.onApplyObservable.add(function (effect) {
  86674. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86675. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  86676. effect.setFloat("bloomWeight", _this.weight);
  86677. });
  86678. if (!blockCompilation) {
  86679. _this.updateEffect();
  86680. }
  86681. return _this;
  86682. }
  86683. return BloomMergePostProcess;
  86684. }(BABYLON.PostProcess));
  86685. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  86686. })(BABYLON || (BABYLON = {}));
  86687. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  86688. var BABYLON;
  86689. (function (BABYLON) {
  86690. /**
  86691. * 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.
  86692. */
  86693. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  86694. __extends(ExtractHighlightsPostProcess, _super);
  86695. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86696. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86697. if (blockCompilation === void 0) { blockCompilation = false; }
  86698. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86699. /**
  86700. * The luminance threshold, pixels below this value will be set to black.
  86701. */
  86702. _this.threshold = 0.9;
  86703. /** @hidden */
  86704. _this._exposure = 1;
  86705. /**
  86706. * Post process which has the input texture to be used when performing highlight extraction
  86707. * @hidden
  86708. */
  86709. _this._inputPostProcess = null;
  86710. _this.onApplyObservable.add(function (effect) {
  86711. if (_this._inputPostProcess) {
  86712. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  86713. }
  86714. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  86715. effect.setFloat('exposure', _this._exposure);
  86716. });
  86717. return _this;
  86718. }
  86719. return ExtractHighlightsPostProcess;
  86720. }(BABYLON.PostProcess));
  86721. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  86722. })(BABYLON || (BABYLON = {}));
  86723. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  86724. var BABYLON;
  86725. (function (BABYLON) {
  86726. /**
  86727. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  86728. */
  86729. var BloomEffect = /** @class */ (function (_super) {
  86730. __extends(BloomEffect, _super);
  86731. /**
  86732. * Creates a new instance of @see BloomEffect
  86733. * @param scene The scene the effect belongs to.
  86734. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  86735. * @param bloomKernel The size of the kernel to be used when applying the blur.
  86736. * @param bloomWeight The the strength of bloom.
  86737. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86738. * @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)
  86739. */
  86740. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  86741. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86742. if (blockCompilation === void 0) { blockCompilation = false; }
  86743. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  86744. return _this._effects;
  86745. }, true) || this;
  86746. _this.bloomScale = bloomScale;
  86747. /**
  86748. * @hidden Internal
  86749. */
  86750. _this._effects = [];
  86751. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86752. _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);
  86753. _this._blurX.alwaysForcePOT = true;
  86754. _this._blurX.autoClear = false;
  86755. _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);
  86756. _this._blurY.alwaysForcePOT = true;
  86757. _this._blurY.autoClear = false;
  86758. _this.kernel = bloomKernel;
  86759. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  86760. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86761. _this._merge.autoClear = false;
  86762. _this._effects.push(_this._merge);
  86763. return _this;
  86764. }
  86765. Object.defineProperty(BloomEffect.prototype, "threshold", {
  86766. /**
  86767. * The luminance threshold to find bright areas of the image to bloom.
  86768. */
  86769. get: function () {
  86770. return this._downscale.threshold;
  86771. },
  86772. set: function (value) {
  86773. this._downscale.threshold = value;
  86774. },
  86775. enumerable: true,
  86776. configurable: true
  86777. });
  86778. Object.defineProperty(BloomEffect.prototype, "weight", {
  86779. /**
  86780. * The strength of the bloom.
  86781. */
  86782. get: function () {
  86783. return this._merge.weight;
  86784. },
  86785. set: function (value) {
  86786. this._merge.weight = value;
  86787. },
  86788. enumerable: true,
  86789. configurable: true
  86790. });
  86791. Object.defineProperty(BloomEffect.prototype, "kernel", {
  86792. /**
  86793. * Specifies the size of the bloom blur kernel, relative to the final output size
  86794. */
  86795. get: function () {
  86796. return this._blurX.kernel / this.bloomScale;
  86797. },
  86798. set: function (value) {
  86799. this._blurX.kernel = value * this.bloomScale;
  86800. this._blurY.kernel = value * this.bloomScale;
  86801. },
  86802. enumerable: true,
  86803. configurable: true
  86804. });
  86805. /**
  86806. * Disposes each of the internal effects for a given camera.
  86807. * @param camera The camera to dispose the effect on.
  86808. */
  86809. BloomEffect.prototype.disposeEffects = function (camera) {
  86810. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86811. this._effects[effectIndex].dispose(camera);
  86812. }
  86813. };
  86814. /**
  86815. * @hidden Internal
  86816. */
  86817. BloomEffect.prototype._updateEffects = function () {
  86818. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86819. this._effects[effectIndex].updateEffect();
  86820. }
  86821. };
  86822. /**
  86823. * Internal
  86824. * @returns if all the contained post processes are ready.
  86825. * @hidden
  86826. */
  86827. BloomEffect.prototype._isReady = function () {
  86828. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86829. if (!this._effects[effectIndex].isReady()) {
  86830. return false;
  86831. }
  86832. }
  86833. return true;
  86834. };
  86835. return BloomEffect;
  86836. }(BABYLON.PostProcessRenderEffect));
  86837. BABYLON.BloomEffect = BloomEffect;
  86838. })(BABYLON || (BABYLON = {}));
  86839. //# sourceMappingURL=babylon.bloomEffect.js.map
  86840. var BABYLON;
  86841. (function (BABYLON) {
  86842. /**
  86843. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  86844. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  86845. */
  86846. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  86847. __extends(DefaultRenderingPipeline, _super);
  86848. /**
  86849. * @constructor
  86850. * @param name - The rendering pipeline name (default: "")
  86851. * @param hdr - If high dynamic range textures should be used (default: true)
  86852. * @param scene - The scene linked to this pipeline (default: the last created scene)
  86853. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  86854. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  86855. */
  86856. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  86857. if (name === void 0) { name = ""; }
  86858. if (hdr === void 0) { hdr = true; }
  86859. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  86860. if (automaticBuild === void 0) { automaticBuild = true; }
  86861. var _this = _super.call(this, scene.getEngine(), name) || this;
  86862. _this._camerasToBeAttached = [];
  86863. /**
  86864. * ID of the sharpen post process,
  86865. */
  86866. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  86867. /**
  86868. * @ignore
  86869. * ID of the image processing post process;
  86870. */
  86871. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  86872. /**
  86873. * @ignore
  86874. * ID of the Fast Approximate Anti-Aliasing post process;
  86875. */
  86876. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  86877. /**
  86878. * ID of the chromatic aberration post process,
  86879. */
  86880. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  86881. /**
  86882. * ID of the grain post process
  86883. */
  86884. _this.GrainPostProcessId = "GrainPostProcessEffect";
  86885. /**
  86886. * Glow post process which adds a glow to emmisive areas of the image
  86887. */
  86888. _this._glowLayer = null;
  86889. /**
  86890. * Animations which can be used to tweak settings over a period of time
  86891. */
  86892. _this.animations = [];
  86893. _this._imageProcessingConfigurationObserver = null;
  86894. // Values
  86895. _this._sharpenEnabled = false;
  86896. _this._bloomEnabled = false;
  86897. _this._depthOfFieldEnabled = false;
  86898. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  86899. _this._fxaaEnabled = false;
  86900. _this._imageProcessingEnabled = true;
  86901. _this._bloomScale = 0.5;
  86902. _this._chromaticAberrationEnabled = false;
  86903. _this._grainEnabled = false;
  86904. _this._buildAllowed = true;
  86905. _this._resizeObserver = null;
  86906. _this._hardwareScaleLevel = 1.0;
  86907. _this._bloomKernel = 64;
  86908. /**
  86909. * Specifies the weight of the bloom in the final rendering
  86910. */
  86911. _this._bloomWeight = 0.15;
  86912. /**
  86913. * Specifies the luma threshold for the area that will be blurred by the bloom
  86914. */
  86915. _this._bloomThreshold = 0.9;
  86916. _this._samples = 1;
  86917. _this._hasCleared = false;
  86918. _this._prevPostProcess = null;
  86919. _this._prevPrevPostProcess = null;
  86920. _this._depthOfFieldSceneObserver = null;
  86921. _this._cameras = cameras || scene.cameras;
  86922. _this._cameras = _this._cameras.slice();
  86923. _this._camerasToBeAttached = _this._cameras.slice();
  86924. _this._buildAllowed = automaticBuild;
  86925. // Initialize
  86926. _this._scene = scene;
  86927. var caps = _this._scene.getEngine().getCaps();
  86928. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  86929. // Misc
  86930. if (_this._hdr) {
  86931. if (caps.textureHalfFloatRender) {
  86932. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86933. }
  86934. else if (caps.textureFloatRender) {
  86935. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86936. }
  86937. }
  86938. else {
  86939. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86940. }
  86941. // Attach
  86942. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86943. var engine = _this._scene.getEngine();
  86944. // Create post processes before hand so they can be modified before enabled.
  86945. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  86946. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86947. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  86948. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  86949. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  86950. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86951. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  86952. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86953. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  86954. _this._resizeObserver = engine.onResizeObservable.add(function () {
  86955. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  86956. _this.bloomKernel = _this.bloomKernel;
  86957. });
  86958. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  86959. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  86960. });
  86961. _this._buildPipeline();
  86962. return _this;
  86963. }
  86964. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  86965. get: function () {
  86966. return this._sharpenEnabled;
  86967. },
  86968. /**
  86969. * Enable or disable the sharpen process from the pipeline
  86970. */
  86971. set: function (enabled) {
  86972. if (this._sharpenEnabled === enabled) {
  86973. return;
  86974. }
  86975. this._sharpenEnabled = enabled;
  86976. this._buildPipeline();
  86977. },
  86978. enumerable: true,
  86979. configurable: true
  86980. });
  86981. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  86982. /**
  86983. * Specifies the size of the bloom blur kernel, relative to the final output size
  86984. */
  86985. get: function () {
  86986. return this._bloomKernel;
  86987. },
  86988. set: function (value) {
  86989. this._bloomKernel = value;
  86990. this.bloom.kernel = value / this._hardwareScaleLevel;
  86991. },
  86992. enumerable: true,
  86993. configurable: true
  86994. });
  86995. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  86996. get: function () {
  86997. return this._bloomWeight;
  86998. },
  86999. /**
  87000. * The strength of the bloom.
  87001. */
  87002. set: function (value) {
  87003. if (this._bloomWeight === value) {
  87004. return;
  87005. }
  87006. this.bloom.weight = value;
  87007. this._bloomWeight = value;
  87008. },
  87009. enumerable: true,
  87010. configurable: true
  87011. });
  87012. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  87013. get: function () {
  87014. return this._bloomThreshold;
  87015. },
  87016. /**
  87017. * The strength of the bloom.
  87018. */
  87019. set: function (value) {
  87020. if (this._bloomThreshold === value) {
  87021. return;
  87022. }
  87023. this.bloom.threshold = value;
  87024. this._bloomThreshold = value;
  87025. },
  87026. enumerable: true,
  87027. configurable: true
  87028. });
  87029. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  87030. get: function () {
  87031. return this._bloomScale;
  87032. },
  87033. /**
  87034. * The scale of the bloom, lower value will provide better performance.
  87035. */
  87036. set: function (value) {
  87037. if (this._bloomScale === value) {
  87038. return;
  87039. }
  87040. this._bloomScale = value;
  87041. // recreate bloom and dispose old as this setting is not dynamic
  87042. this._rebuildBloom();
  87043. this._buildPipeline();
  87044. },
  87045. enumerable: true,
  87046. configurable: true
  87047. });
  87048. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  87049. get: function () {
  87050. return this._bloomEnabled;
  87051. },
  87052. /**
  87053. * Enable or disable the bloom from the pipeline
  87054. */
  87055. set: function (enabled) {
  87056. if (this._bloomEnabled === enabled) {
  87057. return;
  87058. }
  87059. this._bloomEnabled = enabled;
  87060. this._buildPipeline();
  87061. },
  87062. enumerable: true,
  87063. configurable: true
  87064. });
  87065. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  87066. // recreate bloom and dispose old as this setting is not dynamic
  87067. var oldBloom = this.bloom;
  87068. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  87069. this.bloom.threshold = oldBloom.threshold;
  87070. for (var i = 0; i < this._cameras.length; i++) {
  87071. oldBloom.disposeEffects(this._cameras[i]);
  87072. }
  87073. };
  87074. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  87075. /**
  87076. * If the depth of field is enabled.
  87077. */
  87078. get: function () {
  87079. return this._depthOfFieldEnabled;
  87080. },
  87081. set: function (enabled) {
  87082. if (this._depthOfFieldEnabled === enabled) {
  87083. return;
  87084. }
  87085. this._depthOfFieldEnabled = enabled;
  87086. this._buildPipeline();
  87087. },
  87088. enumerable: true,
  87089. configurable: true
  87090. });
  87091. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  87092. /**
  87093. * Blur level of the depth of field effect. (Higher blur will effect performance)
  87094. */
  87095. get: function () {
  87096. return this._depthOfFieldBlurLevel;
  87097. },
  87098. set: function (value) {
  87099. if (this._depthOfFieldBlurLevel === value) {
  87100. return;
  87101. }
  87102. this._depthOfFieldBlurLevel = value;
  87103. // recreate dof and dispose old as this setting is not dynamic
  87104. var oldDof = this.depthOfField;
  87105. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  87106. this.depthOfField.focalLength = oldDof.focalLength;
  87107. this.depthOfField.focusDistance = oldDof.focusDistance;
  87108. this.depthOfField.fStop = oldDof.fStop;
  87109. this.depthOfField.lensSize = oldDof.lensSize;
  87110. for (var i = 0; i < this._cameras.length; i++) {
  87111. oldDof.disposeEffects(this._cameras[i]);
  87112. }
  87113. this._buildPipeline();
  87114. },
  87115. enumerable: true,
  87116. configurable: true
  87117. });
  87118. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  87119. get: function () {
  87120. return this._fxaaEnabled;
  87121. },
  87122. /**
  87123. * If the anti aliasing is enabled.
  87124. */
  87125. set: function (enabled) {
  87126. if (this._fxaaEnabled === enabled) {
  87127. return;
  87128. }
  87129. this._fxaaEnabled = enabled;
  87130. this._buildPipeline();
  87131. },
  87132. enumerable: true,
  87133. configurable: true
  87134. });
  87135. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  87136. get: function () {
  87137. return this._samples;
  87138. },
  87139. /**
  87140. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  87141. */
  87142. set: function (sampleCount) {
  87143. if (this._samples === sampleCount) {
  87144. return;
  87145. }
  87146. this._samples = sampleCount;
  87147. this._buildPipeline();
  87148. },
  87149. enumerable: true,
  87150. configurable: true
  87151. });
  87152. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  87153. get: function () {
  87154. return this._imageProcessingEnabled;
  87155. },
  87156. /**
  87157. * If image processing is enabled.
  87158. */
  87159. set: function (enabled) {
  87160. if (this._imageProcessingEnabled === enabled) {
  87161. return;
  87162. }
  87163. this._imageProcessingEnabled = enabled;
  87164. this._buildPipeline();
  87165. },
  87166. enumerable: true,
  87167. configurable: true
  87168. });
  87169. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  87170. get: function () {
  87171. return this._glowLayer == null;
  87172. },
  87173. /**
  87174. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  87175. */
  87176. set: function (enabled) {
  87177. if (enabled && !this._glowLayer) {
  87178. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  87179. }
  87180. else if (!enabled && this._glowLayer) {
  87181. this._glowLayer.dispose();
  87182. this._glowLayer = null;
  87183. }
  87184. },
  87185. enumerable: true,
  87186. configurable: true
  87187. });
  87188. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  87189. get: function () {
  87190. return this._chromaticAberrationEnabled;
  87191. },
  87192. /**
  87193. * Enable or disable the chromaticAberration process from the pipeline
  87194. */
  87195. set: function (enabled) {
  87196. if (this._chromaticAberrationEnabled === enabled) {
  87197. return;
  87198. }
  87199. this._chromaticAberrationEnabled = enabled;
  87200. this._buildPipeline();
  87201. },
  87202. enumerable: true,
  87203. configurable: true
  87204. });
  87205. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  87206. get: function () {
  87207. return this._grainEnabled;
  87208. },
  87209. /**
  87210. * Enable or disable the grain process from the pipeline
  87211. */
  87212. set: function (enabled) {
  87213. if (this._grainEnabled === enabled) {
  87214. return;
  87215. }
  87216. this._grainEnabled = enabled;
  87217. this._buildPipeline();
  87218. },
  87219. enumerable: true,
  87220. configurable: true
  87221. });
  87222. /**
  87223. * Force the compilation of the entire pipeline.
  87224. */
  87225. DefaultRenderingPipeline.prototype.prepare = function () {
  87226. var previousState = this._buildAllowed;
  87227. this._buildAllowed = true;
  87228. this._buildPipeline();
  87229. this._buildAllowed = previousState;
  87230. };
  87231. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  87232. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  87233. if (this._hasCleared) {
  87234. postProcess.autoClear = false;
  87235. }
  87236. else {
  87237. postProcess.autoClear = true;
  87238. this._scene.autoClear = false;
  87239. this._hasCleared = true;
  87240. }
  87241. if (!skipTextureSharing) {
  87242. if (this._prevPrevPostProcess) {
  87243. postProcess.shareOutputWith(this._prevPrevPostProcess);
  87244. }
  87245. else {
  87246. postProcess.useOwnOutput();
  87247. }
  87248. if (this._prevPostProcess) {
  87249. this._prevPrevPostProcess = this._prevPostProcess;
  87250. }
  87251. this._prevPostProcess = postProcess;
  87252. }
  87253. };
  87254. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  87255. var _this = this;
  87256. if (!this._buildAllowed) {
  87257. return;
  87258. }
  87259. this._scene.autoClear = true;
  87260. var engine = this._scene.getEngine();
  87261. this._disposePostProcesses();
  87262. if (this._cameras !== null) {
  87263. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87264. // get back cameras to be used to reattach pipeline
  87265. this._cameras = this._camerasToBeAttached.slice();
  87266. }
  87267. this._reset();
  87268. this._prevPostProcess = null;
  87269. this._prevPrevPostProcess = null;
  87270. this._hasCleared = false;
  87271. if (this.depthOfFieldEnabled) {
  87272. // Multi camera suport
  87273. if (this._cameras.length > 1) {
  87274. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  87275. var camera = _a[_i];
  87276. var depthRenderer = this._scene.enableDepthRenderer(camera);
  87277. depthRenderer.useOnlyInActiveCamera = true;
  87278. }
  87279. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  87280. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  87281. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  87282. }
  87283. });
  87284. }
  87285. else {
  87286. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87287. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  87288. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  87289. }
  87290. if (!this.depthOfField._isReady()) {
  87291. this.depthOfField._updateEffects();
  87292. }
  87293. this.addEffect(this.depthOfField);
  87294. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  87295. }
  87296. else {
  87297. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87298. }
  87299. if (this.bloomEnabled) {
  87300. if (!this.bloom._isReady()) {
  87301. this.bloom._updateEffects();
  87302. }
  87303. this.addEffect(this.bloom);
  87304. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  87305. }
  87306. if (this._imageProcessingEnabled) {
  87307. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87308. if (this._hdr) {
  87309. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  87310. this._setAutoClearAndTextureSharing(this.imageProcessing);
  87311. }
  87312. else {
  87313. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  87314. }
  87315. }
  87316. if (this.sharpenEnabled) {
  87317. if (!this.sharpen.isReady()) {
  87318. this.sharpen.updateEffect();
  87319. }
  87320. this.addEffect(this._sharpenEffect);
  87321. this._setAutoClearAndTextureSharing(this.sharpen);
  87322. }
  87323. if (this.grainEnabled) {
  87324. if (!this.grain.isReady()) {
  87325. this.grain.updateEffect();
  87326. }
  87327. this.addEffect(this._grainEffect);
  87328. this._setAutoClearAndTextureSharing(this.grain);
  87329. }
  87330. if (this.chromaticAberrationEnabled) {
  87331. if (!this.chromaticAberration.isReady()) {
  87332. this.chromaticAberration.updateEffect();
  87333. }
  87334. this.addEffect(this._chromaticAberrationEffect);
  87335. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  87336. }
  87337. if (this.fxaaEnabled) {
  87338. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87339. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  87340. this._setAutoClearAndTextureSharing(this.fxaa, true);
  87341. }
  87342. if (this._cameras !== null) {
  87343. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  87344. }
  87345. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  87346. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  87347. }
  87348. };
  87349. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  87350. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  87351. for (var i = 0; i < this._cameras.length; i++) {
  87352. var camera = this._cameras[i];
  87353. if (this.imageProcessing) {
  87354. this.imageProcessing.dispose(camera);
  87355. }
  87356. if (this.fxaa) {
  87357. this.fxaa.dispose(camera);
  87358. }
  87359. // These are created in the constructor and should not be disposed on every pipeline change
  87360. if (disposeNonRecreated) {
  87361. if (this.sharpen) {
  87362. this.sharpen.dispose(camera);
  87363. }
  87364. if (this.depthOfField) {
  87365. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87366. this.depthOfField.disposeEffects(camera);
  87367. }
  87368. if (this.bloom) {
  87369. this.bloom.disposeEffects(camera);
  87370. }
  87371. if (this.chromaticAberration) {
  87372. this.chromaticAberration.dispose(camera);
  87373. }
  87374. if (this.grain) {
  87375. this.grain.dispose(camera);
  87376. }
  87377. if (this._glowLayer) {
  87378. this._glowLayer.dispose();
  87379. }
  87380. }
  87381. }
  87382. this.imageProcessing = null;
  87383. this.fxaa = null;
  87384. if (disposeNonRecreated) {
  87385. this.sharpen = null;
  87386. this._sharpenEffect = null;
  87387. this.depthOfField = null;
  87388. this.bloom = null;
  87389. this.chromaticAberration = null;
  87390. this._chromaticAberrationEffect = null;
  87391. this.grain = null;
  87392. this._grainEffect = null;
  87393. this._glowLayer = null;
  87394. }
  87395. };
  87396. /**
  87397. * Adds a camera to the pipeline
  87398. * @param camera the camera to be added
  87399. */
  87400. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  87401. this._camerasToBeAttached.push(camera);
  87402. this._buildPipeline();
  87403. };
  87404. /**
  87405. * Removes a camera from the pipeline
  87406. * @param camera the camera to remove
  87407. */
  87408. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  87409. var index = this._camerasToBeAttached.indexOf(camera);
  87410. this._camerasToBeAttached.splice(index, 1);
  87411. this._buildPipeline();
  87412. };
  87413. /**
  87414. * Dispose of the pipeline and stop all post processes
  87415. */
  87416. DefaultRenderingPipeline.prototype.dispose = function () {
  87417. this._disposePostProcesses(true);
  87418. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87419. this._scene.autoClear = true;
  87420. if (this._resizeObserver) {
  87421. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  87422. this._resizeObserver = null;
  87423. }
  87424. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  87425. _super.prototype.dispose.call(this);
  87426. };
  87427. /**
  87428. * Serialize the rendering pipeline (Used when exporting)
  87429. * @returns the serialized object
  87430. */
  87431. DefaultRenderingPipeline.prototype.serialize = function () {
  87432. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87433. serializationObject.customType = "DefaultRenderingPipeline";
  87434. return serializationObject;
  87435. };
  87436. /**
  87437. * Parse the serialized pipeline
  87438. * @param source Source pipeline.
  87439. * @param scene The scene to load the pipeline to.
  87440. * @param rootUrl The URL of the serialized pipeline.
  87441. * @returns An instantiated pipeline from the serialized object.
  87442. */
  87443. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  87444. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  87445. };
  87446. __decorate([
  87447. BABYLON.serialize()
  87448. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  87449. __decorate([
  87450. BABYLON.serialize()
  87451. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  87452. __decorate([
  87453. BABYLON.serialize()
  87454. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  87455. __decorate([
  87456. BABYLON.serialize()
  87457. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  87458. __decorate([
  87459. BABYLON.serialize()
  87460. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  87461. __decorate([
  87462. BABYLON.serialize()
  87463. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  87464. __decorate([
  87465. BABYLON.serialize()
  87466. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  87467. __decorate([
  87468. BABYLON.serialize()
  87469. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  87470. __decorate([
  87471. BABYLON.serialize()
  87472. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  87473. __decorate([
  87474. BABYLON.serialize()
  87475. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  87476. __decorate([
  87477. BABYLON.serialize()
  87478. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  87479. __decorate([
  87480. BABYLON.serialize()
  87481. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  87482. __decorate([
  87483. BABYLON.serialize()
  87484. ], DefaultRenderingPipeline.prototype, "samples", null);
  87485. __decorate([
  87486. BABYLON.serialize()
  87487. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  87488. __decorate([
  87489. BABYLON.serialize()
  87490. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  87491. __decorate([
  87492. BABYLON.serialize()
  87493. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  87494. __decorate([
  87495. BABYLON.serialize()
  87496. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  87497. return DefaultRenderingPipeline;
  87498. }(BABYLON.PostProcessRenderPipeline));
  87499. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  87500. })(BABYLON || (BABYLON = {}));
  87501. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  87502. var BABYLON;
  87503. (function (BABYLON) {
  87504. /**
  87505. * @hidden
  87506. */
  87507. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  87508. __extends(ImageProcessingConfigurationDefines, _super);
  87509. function ImageProcessingConfigurationDefines() {
  87510. var _this = _super.call(this) || this;
  87511. _this.IMAGEPROCESSING = false;
  87512. _this.VIGNETTE = false;
  87513. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87514. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87515. _this.TONEMAPPING = false;
  87516. _this.TONEMAPPING_ACES = false;
  87517. _this.CONTRAST = false;
  87518. _this.COLORCURVES = false;
  87519. _this.COLORGRADING = false;
  87520. _this.COLORGRADING3D = false;
  87521. _this.SAMPLER3DGREENDEPTH = false;
  87522. _this.SAMPLER3DBGRMAP = false;
  87523. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87524. _this.EXPOSURE = false;
  87525. _this.rebuild();
  87526. return _this;
  87527. }
  87528. return ImageProcessingConfigurationDefines;
  87529. }(BABYLON.MaterialDefines));
  87530. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  87531. /**
  87532. * This groups together the common properties used for image processing either in direct forward pass
  87533. * or through post processing effect depending on the use of the image processing pipeline in your scene
  87534. * or not.
  87535. */
  87536. var ImageProcessingConfiguration = /** @class */ (function () {
  87537. function ImageProcessingConfiguration() {
  87538. /**
  87539. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  87540. */
  87541. this.colorCurves = new BABYLON.ColorCurves();
  87542. this._colorCurvesEnabled = false;
  87543. this._colorGradingEnabled = false;
  87544. this._colorGradingWithGreenDepth = true;
  87545. this._colorGradingBGR = true;
  87546. /** @hidden */
  87547. this._exposure = 1.0;
  87548. this._toneMappingEnabled = false;
  87549. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  87550. this._contrast = 1.0;
  87551. /**
  87552. * Vignette stretch size.
  87553. */
  87554. this.vignetteStretch = 0;
  87555. /**
  87556. * Vignette centre X Offset.
  87557. */
  87558. this.vignetteCentreX = 0;
  87559. /**
  87560. * Vignette centre Y Offset.
  87561. */
  87562. this.vignetteCentreY = 0;
  87563. /**
  87564. * Vignette weight or intensity of the vignette effect.
  87565. */
  87566. this.vignetteWeight = 1.5;
  87567. /**
  87568. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87569. * if vignetteEnabled is set to true.
  87570. */
  87571. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87572. /**
  87573. * Camera field of view used by the Vignette effect.
  87574. */
  87575. this.vignetteCameraFov = 0.5;
  87576. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  87577. this._vignetteEnabled = false;
  87578. this._applyByPostProcess = false;
  87579. this._isEnabled = true;
  87580. /**
  87581. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  87582. */
  87583. this.onUpdateParameters = new BABYLON.Observable();
  87584. }
  87585. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  87586. /**
  87587. * Gets wether the color curves effect is enabled.
  87588. */
  87589. get: function () {
  87590. return this._colorCurvesEnabled;
  87591. },
  87592. /**
  87593. * Sets wether the color curves effect is enabled.
  87594. */
  87595. set: function (value) {
  87596. if (this._colorCurvesEnabled === value) {
  87597. return;
  87598. }
  87599. this._colorCurvesEnabled = value;
  87600. this._updateParameters();
  87601. },
  87602. enumerable: true,
  87603. configurable: true
  87604. });
  87605. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  87606. /**
  87607. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87608. */
  87609. get: function () {
  87610. return this._colorGradingTexture;
  87611. },
  87612. /**
  87613. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87614. */
  87615. set: function (value) {
  87616. if (this._colorGradingTexture === value) {
  87617. return;
  87618. }
  87619. this._colorGradingTexture = value;
  87620. this._updateParameters();
  87621. },
  87622. enumerable: true,
  87623. configurable: true
  87624. });
  87625. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  87626. /**
  87627. * Gets wether the color grading effect is enabled.
  87628. */
  87629. get: function () {
  87630. return this._colorGradingEnabled;
  87631. },
  87632. /**
  87633. * Sets wether the color grading effect is enabled.
  87634. */
  87635. set: function (value) {
  87636. if (this._colorGradingEnabled === value) {
  87637. return;
  87638. }
  87639. this._colorGradingEnabled = value;
  87640. this._updateParameters();
  87641. },
  87642. enumerable: true,
  87643. configurable: true
  87644. });
  87645. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  87646. /**
  87647. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  87648. */
  87649. get: function () {
  87650. return this._colorGradingWithGreenDepth;
  87651. },
  87652. /**
  87653. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  87654. */
  87655. set: function (value) {
  87656. if (this._colorGradingWithGreenDepth === value) {
  87657. return;
  87658. }
  87659. this._colorGradingWithGreenDepth = value;
  87660. this._updateParameters();
  87661. },
  87662. enumerable: true,
  87663. configurable: true
  87664. });
  87665. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  87666. /**
  87667. * Gets wether the color grading texture contains BGR values.
  87668. */
  87669. get: function () {
  87670. return this._colorGradingBGR;
  87671. },
  87672. /**
  87673. * Sets wether the color grading texture contains BGR values.
  87674. */
  87675. set: function (value) {
  87676. if (this._colorGradingBGR === value) {
  87677. return;
  87678. }
  87679. this._colorGradingBGR = value;
  87680. this._updateParameters();
  87681. },
  87682. enumerable: true,
  87683. configurable: true
  87684. });
  87685. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  87686. /**
  87687. * Gets the Exposure used in the effect.
  87688. */
  87689. get: function () {
  87690. return this._exposure;
  87691. },
  87692. /**
  87693. * Sets the Exposure used in the effect.
  87694. */
  87695. set: function (value) {
  87696. if (this._exposure === value) {
  87697. return;
  87698. }
  87699. this._exposure = value;
  87700. this._updateParameters();
  87701. },
  87702. enumerable: true,
  87703. configurable: true
  87704. });
  87705. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  87706. /**
  87707. * Gets wether the tone mapping effect is enabled.
  87708. */
  87709. get: function () {
  87710. return this._toneMappingEnabled;
  87711. },
  87712. /**
  87713. * Sets wether the tone mapping effect is enabled.
  87714. */
  87715. set: function (value) {
  87716. if (this._toneMappingEnabled === value) {
  87717. return;
  87718. }
  87719. this._toneMappingEnabled = value;
  87720. this._updateParameters();
  87721. },
  87722. enumerable: true,
  87723. configurable: true
  87724. });
  87725. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  87726. /**
  87727. * Gets the type of tone mapping effect.
  87728. */
  87729. get: function () {
  87730. return this._toneMappingType;
  87731. },
  87732. /**
  87733. * Sets the type of tone mapping effect used in BabylonJS.
  87734. */
  87735. set: function (value) {
  87736. if (this._toneMappingType === value) {
  87737. return;
  87738. }
  87739. this._toneMappingType = value;
  87740. this._updateParameters();
  87741. },
  87742. enumerable: true,
  87743. configurable: true
  87744. });
  87745. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  87746. /**
  87747. * Gets the contrast used in the effect.
  87748. */
  87749. get: function () {
  87750. return this._contrast;
  87751. },
  87752. /**
  87753. * Sets the contrast used in the effect.
  87754. */
  87755. set: function (value) {
  87756. if (this._contrast === value) {
  87757. return;
  87758. }
  87759. this._contrast = value;
  87760. this._updateParameters();
  87761. },
  87762. enumerable: true,
  87763. configurable: true
  87764. });
  87765. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  87766. /**
  87767. * Gets the vignette blend mode allowing different kind of effect.
  87768. */
  87769. get: function () {
  87770. return this._vignetteBlendMode;
  87771. },
  87772. /**
  87773. * Sets the vignette blend mode allowing different kind of effect.
  87774. */
  87775. set: function (value) {
  87776. if (this._vignetteBlendMode === value) {
  87777. return;
  87778. }
  87779. this._vignetteBlendMode = value;
  87780. this._updateParameters();
  87781. },
  87782. enumerable: true,
  87783. configurable: true
  87784. });
  87785. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  87786. /**
  87787. * Gets wether the vignette effect is enabled.
  87788. */
  87789. get: function () {
  87790. return this._vignetteEnabled;
  87791. },
  87792. /**
  87793. * Sets wether the vignette effect is enabled.
  87794. */
  87795. set: function (value) {
  87796. if (this._vignetteEnabled === value) {
  87797. return;
  87798. }
  87799. this._vignetteEnabled = value;
  87800. this._updateParameters();
  87801. },
  87802. enumerable: true,
  87803. configurable: true
  87804. });
  87805. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  87806. /**
  87807. * Gets wether the image processing is applied through a post process or not.
  87808. */
  87809. get: function () {
  87810. return this._applyByPostProcess;
  87811. },
  87812. /**
  87813. * Sets wether the image processing is applied through a post process or not.
  87814. */
  87815. set: function (value) {
  87816. if (this._applyByPostProcess === value) {
  87817. return;
  87818. }
  87819. this._applyByPostProcess = value;
  87820. this._updateParameters();
  87821. },
  87822. enumerable: true,
  87823. configurable: true
  87824. });
  87825. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  87826. /**
  87827. * Gets wether the image processing is enabled or not.
  87828. */
  87829. get: function () {
  87830. return this._isEnabled;
  87831. },
  87832. /**
  87833. * Sets wether the image processing is enabled or not.
  87834. */
  87835. set: function (value) {
  87836. if (this._isEnabled === value) {
  87837. return;
  87838. }
  87839. this._isEnabled = value;
  87840. this._updateParameters();
  87841. },
  87842. enumerable: true,
  87843. configurable: true
  87844. });
  87845. /**
  87846. * Method called each time the image processing information changes requires to recompile the effect.
  87847. */
  87848. ImageProcessingConfiguration.prototype._updateParameters = function () {
  87849. this.onUpdateParameters.notifyObservers(this);
  87850. };
  87851. /**
  87852. * Gets the current class name.
  87853. * @return "ImageProcessingConfiguration"
  87854. */
  87855. ImageProcessingConfiguration.prototype.getClassName = function () {
  87856. return "ImageProcessingConfiguration";
  87857. };
  87858. /**
  87859. * Prepare the list of uniforms associated with the Image Processing effects.
  87860. * @param uniforms The list of uniforms used in the effect
  87861. * @param defines the list of defines currently in use
  87862. */
  87863. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  87864. if (defines.EXPOSURE) {
  87865. uniforms.push("exposureLinear");
  87866. }
  87867. if (defines.CONTRAST) {
  87868. uniforms.push("contrast");
  87869. }
  87870. if (defines.COLORGRADING) {
  87871. uniforms.push("colorTransformSettings");
  87872. }
  87873. if (defines.VIGNETTE) {
  87874. uniforms.push("vInverseScreenSize");
  87875. uniforms.push("vignetteSettings1");
  87876. uniforms.push("vignetteSettings2");
  87877. }
  87878. if (defines.COLORCURVES) {
  87879. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  87880. }
  87881. };
  87882. /**
  87883. * Prepare the list of samplers associated with the Image Processing effects.
  87884. * @param samplersList The list of uniforms used in the effect
  87885. * @param defines the list of defines currently in use
  87886. */
  87887. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  87888. if (defines.COLORGRADING) {
  87889. samplersList.push("txColorTransform");
  87890. }
  87891. };
  87892. /**
  87893. * Prepare the list of defines associated to the shader.
  87894. * @param defines the list of defines to complete
  87895. * @param forPostProcess Define if we are currently in post process mode or not
  87896. */
  87897. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  87898. if (forPostProcess === void 0) { forPostProcess = false; }
  87899. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  87900. defines.VIGNETTE = false;
  87901. defines.TONEMAPPING = false;
  87902. defines.TONEMAPPING_ACES = false;
  87903. defines.CONTRAST = false;
  87904. defines.EXPOSURE = false;
  87905. defines.COLORCURVES = false;
  87906. defines.COLORGRADING = false;
  87907. defines.COLORGRADING3D = false;
  87908. defines.IMAGEPROCESSING = false;
  87909. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  87910. return;
  87911. }
  87912. defines.VIGNETTE = this.vignetteEnabled;
  87913. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  87914. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  87915. defines.TONEMAPPING = this.toneMappingEnabled;
  87916. switch (this._toneMappingType) {
  87917. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  87918. defines.TONEMAPPING_ACES = true;
  87919. break;
  87920. }
  87921. defines.CONTRAST = (this.contrast !== 1.0);
  87922. defines.EXPOSURE = (this.exposure !== 1.0);
  87923. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  87924. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  87925. if (defines.COLORGRADING) {
  87926. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  87927. }
  87928. else {
  87929. defines.COLORGRADING3D = false;
  87930. }
  87931. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  87932. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  87933. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  87934. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  87935. };
  87936. /**
  87937. * Returns true if all the image processing information are ready.
  87938. * @returns True if ready, otherwise, false
  87939. */
  87940. ImageProcessingConfiguration.prototype.isReady = function () {
  87941. // Color Grading texure can not be none blocking.
  87942. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  87943. };
  87944. /**
  87945. * Binds the image processing to the shader.
  87946. * @param effect The effect to bind to
  87947. * @param aspectRatio Define the current aspect ratio of the effect
  87948. */
  87949. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  87950. if (aspectRatio === void 0) { aspectRatio = 1; }
  87951. // Color Curves
  87952. if (this._colorCurvesEnabled && this.colorCurves) {
  87953. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  87954. }
  87955. // Vignette
  87956. if (this._vignetteEnabled) {
  87957. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  87958. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  87959. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  87960. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  87961. var vignetteScaleX = vignetteScaleY * aspectRatio;
  87962. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  87963. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  87964. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  87965. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  87966. var vignettePower = -2.0 * this.vignetteWeight;
  87967. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  87968. }
  87969. // Exposure
  87970. effect.setFloat("exposureLinear", this.exposure);
  87971. // Contrast
  87972. effect.setFloat("contrast", this.contrast);
  87973. // Color transform settings
  87974. if (this.colorGradingTexture) {
  87975. effect.setTexture("txColorTransform", this.colorGradingTexture);
  87976. var textureSize = this.colorGradingTexture.getSize().height;
  87977. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  87978. 0.5 / textureSize, // textureOffset
  87979. textureSize, // textureSize
  87980. this.colorGradingTexture.level // weight
  87981. );
  87982. }
  87983. };
  87984. /**
  87985. * Clones the current image processing instance.
  87986. * @return The cloned image processing
  87987. */
  87988. ImageProcessingConfiguration.prototype.clone = function () {
  87989. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  87990. };
  87991. /**
  87992. * Serializes the current image processing instance to a json representation.
  87993. * @return a JSON representation
  87994. */
  87995. ImageProcessingConfiguration.prototype.serialize = function () {
  87996. return BABYLON.SerializationHelper.Serialize(this);
  87997. };
  87998. /**
  87999. * Parses the image processing from a json representation.
  88000. * @param source the JSON source to parse
  88001. * @return The parsed image processing
  88002. */
  88003. ImageProcessingConfiguration.Parse = function (source) {
  88004. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  88005. };
  88006. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  88007. /**
  88008. * Used to apply the vignette as a mix with the pixel color.
  88009. */
  88010. get: function () {
  88011. return this._VIGNETTEMODE_MULTIPLY;
  88012. },
  88013. enumerable: true,
  88014. configurable: true
  88015. });
  88016. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  88017. /**
  88018. * Used to apply the vignette as a replacement of the pixel color.
  88019. */
  88020. get: function () {
  88021. return this._VIGNETTEMODE_OPAQUE;
  88022. },
  88023. enumerable: true,
  88024. configurable: true
  88025. });
  88026. /**
  88027. * Default tone mapping applied in BabylonJS.
  88028. */
  88029. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  88030. /**
  88031. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  88032. * to other engines rendering to increase portability.
  88033. */
  88034. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  88035. // Static constants associated to the image processing.
  88036. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  88037. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  88038. __decorate([
  88039. BABYLON.serializeAsColorCurves()
  88040. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  88041. __decorate([
  88042. BABYLON.serialize()
  88043. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  88044. __decorate([
  88045. BABYLON.serializeAsTexture("colorGradingTexture")
  88046. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  88047. __decorate([
  88048. BABYLON.serialize()
  88049. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  88050. __decorate([
  88051. BABYLON.serialize()
  88052. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  88053. __decorate([
  88054. BABYLON.serialize()
  88055. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  88056. __decorate([
  88057. BABYLON.serialize()
  88058. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  88059. __decorate([
  88060. BABYLON.serialize()
  88061. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  88062. __decorate([
  88063. BABYLON.serialize()
  88064. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  88065. __decorate([
  88066. BABYLON.serialize()
  88067. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  88068. __decorate([
  88069. BABYLON.serialize()
  88070. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  88071. __decorate([
  88072. BABYLON.serialize()
  88073. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  88074. __decorate([
  88075. BABYLON.serialize()
  88076. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  88077. __decorate([
  88078. BABYLON.serialize()
  88079. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  88080. __decorate([
  88081. BABYLON.serializeAsColor4()
  88082. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  88083. __decorate([
  88084. BABYLON.serialize()
  88085. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  88086. __decorate([
  88087. BABYLON.serialize()
  88088. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  88089. __decorate([
  88090. BABYLON.serialize()
  88091. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  88092. __decorate([
  88093. BABYLON.serialize()
  88094. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  88095. __decorate([
  88096. BABYLON.serialize()
  88097. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  88098. return ImageProcessingConfiguration;
  88099. }());
  88100. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  88101. })(BABYLON || (BABYLON = {}));
  88102. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  88103. var BABYLON;
  88104. (function (BABYLON) {
  88105. /**
  88106. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  88107. * It can help converting any input color in a desired output one. This can then be used to create effects
  88108. * from sepia, black and white to sixties or futuristic rendering...
  88109. *
  88110. * The only supported format is currently 3dl.
  88111. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  88112. */
  88113. var ColorGradingTexture = /** @class */ (function (_super) {
  88114. __extends(ColorGradingTexture, _super);
  88115. /**
  88116. * Instantiates a ColorGradingTexture from the following parameters.
  88117. *
  88118. * @param url The location of the color gradind data (currently only supporting 3dl)
  88119. * @param scene The scene the texture will be used in
  88120. */
  88121. function ColorGradingTexture(url, scene) {
  88122. var _this = _super.call(this, scene) || this;
  88123. if (!url) {
  88124. return _this;
  88125. }
  88126. _this._engine = scene.getEngine();
  88127. _this._textureMatrix = BABYLON.Matrix.Identity();
  88128. _this.name = url;
  88129. _this.url = url;
  88130. _this.hasAlpha = false;
  88131. _this.isCube = false;
  88132. _this.is3D = _this._engine.webGLVersion > 1;
  88133. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88134. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88135. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88136. _this.anisotropicFilteringLevel = 1;
  88137. _this._texture = _this._getFromCache(url, true);
  88138. if (!_this._texture) {
  88139. if (!scene.useDelayedTextureLoading) {
  88140. _this.loadTexture();
  88141. }
  88142. else {
  88143. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  88144. }
  88145. }
  88146. return _this;
  88147. }
  88148. /**
  88149. * Returns the texture matrix used in most of the material.
  88150. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  88151. */
  88152. ColorGradingTexture.prototype.getTextureMatrix = function () {
  88153. return this._textureMatrix;
  88154. };
  88155. /**
  88156. * Occurs when the file being loaded is a .3dl LUT file.
  88157. */
  88158. ColorGradingTexture.prototype.load3dlTexture = function () {
  88159. var engine = this._engine;
  88160. var texture;
  88161. if (engine.webGLVersion === 1) {
  88162. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88163. }
  88164. else {
  88165. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88166. }
  88167. this._texture = texture;
  88168. var callback = function (text) {
  88169. if (typeof text !== "string") {
  88170. return;
  88171. }
  88172. var data = null;
  88173. var tempData = null;
  88174. var line;
  88175. var lines = text.split('\n');
  88176. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  88177. var maxColor = 0;
  88178. for (var i = 0; i < lines.length; i++) {
  88179. line = lines[i];
  88180. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  88181. continue;
  88182. }
  88183. if (line.indexOf('#') === 0) {
  88184. continue;
  88185. }
  88186. var words = line.split(" ");
  88187. if (size === 0) {
  88188. // Number of space + one
  88189. size = words.length;
  88190. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  88191. tempData = new Float32Array(size * size * size * 4);
  88192. continue;
  88193. }
  88194. if (size != 0) {
  88195. var r = Math.max(parseInt(words[0]), 0);
  88196. var g = Math.max(parseInt(words[1]), 0);
  88197. var b = Math.max(parseInt(words[2]), 0);
  88198. maxColor = Math.max(r, maxColor);
  88199. maxColor = Math.max(g, maxColor);
  88200. maxColor = Math.max(b, maxColor);
  88201. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  88202. if (tempData) {
  88203. tempData[pixelStorageIndex + 0] = r;
  88204. tempData[pixelStorageIndex + 1] = g;
  88205. tempData[pixelStorageIndex + 2] = b;
  88206. }
  88207. // Keep for reference in case of back compat problems.
  88208. // pixelIndexSlice++;
  88209. // if (pixelIndexSlice % size == 0) {
  88210. // pixelIndexH++;
  88211. // pixelIndexSlice = 0;
  88212. // if (pixelIndexH % size == 0) {
  88213. // pixelIndexW++;
  88214. // pixelIndexH = 0;
  88215. // }
  88216. // }
  88217. pixelIndexH++;
  88218. if (pixelIndexH % size == 0) {
  88219. pixelIndexSlice++;
  88220. pixelIndexH = 0;
  88221. if (pixelIndexSlice % size == 0) {
  88222. pixelIndexW++;
  88223. pixelIndexSlice = 0;
  88224. }
  88225. }
  88226. }
  88227. }
  88228. if (tempData && data) {
  88229. for (var i = 0; i < tempData.length; i++) {
  88230. if (i > 0 && (i + 1) % 4 === 0) {
  88231. data[i] = 255;
  88232. }
  88233. else {
  88234. var value = tempData[i];
  88235. data[i] = (value / maxColor * 255);
  88236. }
  88237. }
  88238. }
  88239. if (texture.is3D) {
  88240. texture.updateSize(size, size, size);
  88241. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  88242. }
  88243. else {
  88244. texture.updateSize(size * size, size);
  88245. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  88246. }
  88247. };
  88248. var scene = this.getScene();
  88249. if (scene) {
  88250. scene._loadFile(this.url, callback);
  88251. }
  88252. else {
  88253. this._engine._loadFile(this.url, callback);
  88254. }
  88255. return this._texture;
  88256. };
  88257. /**
  88258. * Starts the loading process of the texture.
  88259. */
  88260. ColorGradingTexture.prototype.loadTexture = function () {
  88261. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  88262. this.load3dlTexture();
  88263. }
  88264. };
  88265. /**
  88266. * Clones the color gradind texture.
  88267. */
  88268. ColorGradingTexture.prototype.clone = function () {
  88269. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  88270. // Base texture
  88271. newTexture.level = this.level;
  88272. return newTexture;
  88273. };
  88274. /**
  88275. * Called during delayed load for textures.
  88276. */
  88277. ColorGradingTexture.prototype.delayLoad = function () {
  88278. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  88279. return;
  88280. }
  88281. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  88282. this._texture = this._getFromCache(this.url, true);
  88283. if (!this._texture) {
  88284. this.loadTexture();
  88285. }
  88286. };
  88287. /**
  88288. * Parses a color grading texture serialized by Babylon.
  88289. * @param parsedTexture The texture information being parsedTexture
  88290. * @param scene The scene to load the texture in
  88291. * @param rootUrl The root url of the data assets to load
  88292. * @return A color gradind texture
  88293. */
  88294. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88295. var texture = null;
  88296. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88297. texture = new ColorGradingTexture(parsedTexture.name, scene);
  88298. texture.name = parsedTexture.name;
  88299. texture.level = parsedTexture.level;
  88300. }
  88301. return texture;
  88302. };
  88303. /**
  88304. * Serializes the LUT texture to json format.
  88305. */
  88306. ColorGradingTexture.prototype.serialize = function () {
  88307. if (!this.name) {
  88308. return null;
  88309. }
  88310. var serializationObject = {};
  88311. serializationObject.name = this.name;
  88312. serializationObject.level = this.level;
  88313. serializationObject.customType = "BABYLON.ColorGradingTexture";
  88314. return serializationObject;
  88315. };
  88316. /**
  88317. * Empty line regex stored for GC.
  88318. */
  88319. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  88320. return ColorGradingTexture;
  88321. }(BABYLON.BaseTexture));
  88322. BABYLON.ColorGradingTexture = ColorGradingTexture;
  88323. })(BABYLON || (BABYLON = {}));
  88324. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  88325. var BABYLON;
  88326. (function (BABYLON) {
  88327. /**
  88328. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88329. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88330. * 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;
  88331. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88332. */
  88333. var ColorCurves = /** @class */ (function () {
  88334. function ColorCurves() {
  88335. this._dirty = true;
  88336. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  88337. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  88338. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88339. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  88340. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88341. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  88342. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  88343. this._globalHue = 30;
  88344. this._globalDensity = 0;
  88345. this._globalSaturation = 0;
  88346. this._globalExposure = 0;
  88347. this._highlightsHue = 30;
  88348. this._highlightsDensity = 0;
  88349. this._highlightsSaturation = 0;
  88350. this._highlightsExposure = 0;
  88351. this._midtonesHue = 30;
  88352. this._midtonesDensity = 0;
  88353. this._midtonesSaturation = 0;
  88354. this._midtonesExposure = 0;
  88355. this._shadowsHue = 30;
  88356. this._shadowsDensity = 0;
  88357. this._shadowsSaturation = 0;
  88358. this._shadowsExposure = 0;
  88359. }
  88360. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  88361. /**
  88362. * Gets the global Hue value.
  88363. * 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).
  88364. */
  88365. get: function () {
  88366. return this._globalHue;
  88367. },
  88368. /**
  88369. * Sets the global Hue value.
  88370. * 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).
  88371. */
  88372. set: function (value) {
  88373. this._globalHue = value;
  88374. this._dirty = true;
  88375. },
  88376. enumerable: true,
  88377. configurable: true
  88378. });
  88379. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  88380. /**
  88381. * Gets the global Density value.
  88382. * 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.
  88383. * Values less than zero provide a filter of opposite hue.
  88384. */
  88385. get: function () {
  88386. return this._globalDensity;
  88387. },
  88388. /**
  88389. * Sets the global Density value.
  88390. * 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.
  88391. * Values less than zero provide a filter of opposite hue.
  88392. */
  88393. set: function (value) {
  88394. this._globalDensity = value;
  88395. this._dirty = true;
  88396. },
  88397. enumerable: true,
  88398. configurable: true
  88399. });
  88400. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  88401. /**
  88402. * Gets the global Saturation value.
  88403. * 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.
  88404. */
  88405. get: function () {
  88406. return this._globalSaturation;
  88407. },
  88408. /**
  88409. * Sets the global Saturation value.
  88410. * 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.
  88411. */
  88412. set: function (value) {
  88413. this._globalSaturation = value;
  88414. this._dirty = true;
  88415. },
  88416. enumerable: true,
  88417. configurable: true
  88418. });
  88419. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  88420. /**
  88421. * Gets the global Exposure value.
  88422. * 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.
  88423. */
  88424. get: function () {
  88425. return this._globalExposure;
  88426. },
  88427. /**
  88428. * Sets the global Exposure value.
  88429. * 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.
  88430. */
  88431. set: function (value) {
  88432. this._globalExposure = value;
  88433. this._dirty = true;
  88434. },
  88435. enumerable: true,
  88436. configurable: true
  88437. });
  88438. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  88439. /**
  88440. * Gets the highlights Hue value.
  88441. * 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).
  88442. */
  88443. get: function () {
  88444. return this._highlightsHue;
  88445. },
  88446. /**
  88447. * Sets the highlights Hue value.
  88448. * 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).
  88449. */
  88450. set: function (value) {
  88451. this._highlightsHue = value;
  88452. this._dirty = true;
  88453. },
  88454. enumerable: true,
  88455. configurable: true
  88456. });
  88457. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  88458. /**
  88459. * Gets the highlights Density value.
  88460. * 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.
  88461. * Values less than zero provide a filter of opposite hue.
  88462. */
  88463. get: function () {
  88464. return this._highlightsDensity;
  88465. },
  88466. /**
  88467. * Sets the highlights Density value.
  88468. * 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.
  88469. * Values less than zero provide a filter of opposite hue.
  88470. */
  88471. set: function (value) {
  88472. this._highlightsDensity = value;
  88473. this._dirty = true;
  88474. },
  88475. enumerable: true,
  88476. configurable: true
  88477. });
  88478. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  88479. /**
  88480. * Gets the highlights Saturation value.
  88481. * 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.
  88482. */
  88483. get: function () {
  88484. return this._highlightsSaturation;
  88485. },
  88486. /**
  88487. * Sets the highlights Saturation value.
  88488. * 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.
  88489. */
  88490. set: function (value) {
  88491. this._highlightsSaturation = value;
  88492. this._dirty = true;
  88493. },
  88494. enumerable: true,
  88495. configurable: true
  88496. });
  88497. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  88498. /**
  88499. * Gets the highlights Exposure value.
  88500. * 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.
  88501. */
  88502. get: function () {
  88503. return this._highlightsExposure;
  88504. },
  88505. /**
  88506. * Sets the highlights Exposure value.
  88507. * 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.
  88508. */
  88509. set: function (value) {
  88510. this._highlightsExposure = value;
  88511. this._dirty = true;
  88512. },
  88513. enumerable: true,
  88514. configurable: true
  88515. });
  88516. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  88517. /**
  88518. * Gets the midtones Hue value.
  88519. * 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).
  88520. */
  88521. get: function () {
  88522. return this._midtonesHue;
  88523. },
  88524. /**
  88525. * Sets the midtones Hue value.
  88526. * 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).
  88527. */
  88528. set: function (value) {
  88529. this._midtonesHue = value;
  88530. this._dirty = true;
  88531. },
  88532. enumerable: true,
  88533. configurable: true
  88534. });
  88535. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  88536. /**
  88537. * Gets the midtones Density value.
  88538. * 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.
  88539. * Values less than zero provide a filter of opposite hue.
  88540. */
  88541. get: function () {
  88542. return this._midtonesDensity;
  88543. },
  88544. /**
  88545. * Sets the midtones Density value.
  88546. * 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.
  88547. * Values less than zero provide a filter of opposite hue.
  88548. */
  88549. set: function (value) {
  88550. this._midtonesDensity = value;
  88551. this._dirty = true;
  88552. },
  88553. enumerable: true,
  88554. configurable: true
  88555. });
  88556. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  88557. /**
  88558. * Gets the midtones Saturation value.
  88559. * 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.
  88560. */
  88561. get: function () {
  88562. return this._midtonesSaturation;
  88563. },
  88564. /**
  88565. * Sets the midtones Saturation value.
  88566. * 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.
  88567. */
  88568. set: function (value) {
  88569. this._midtonesSaturation = value;
  88570. this._dirty = true;
  88571. },
  88572. enumerable: true,
  88573. configurable: true
  88574. });
  88575. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  88576. /**
  88577. * Gets the midtones Exposure value.
  88578. * 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.
  88579. */
  88580. get: function () {
  88581. return this._midtonesExposure;
  88582. },
  88583. /**
  88584. * Sets the midtones Exposure value.
  88585. * 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.
  88586. */
  88587. set: function (value) {
  88588. this._midtonesExposure = value;
  88589. this._dirty = true;
  88590. },
  88591. enumerable: true,
  88592. configurable: true
  88593. });
  88594. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  88595. /**
  88596. * Gets the shadows Hue value.
  88597. * 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).
  88598. */
  88599. get: function () {
  88600. return this._shadowsHue;
  88601. },
  88602. /**
  88603. * Sets the shadows Hue value.
  88604. * 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).
  88605. */
  88606. set: function (value) {
  88607. this._shadowsHue = value;
  88608. this._dirty = true;
  88609. },
  88610. enumerable: true,
  88611. configurable: true
  88612. });
  88613. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  88614. /**
  88615. * Gets the shadows Density value.
  88616. * 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.
  88617. * Values less than zero provide a filter of opposite hue.
  88618. */
  88619. get: function () {
  88620. return this._shadowsDensity;
  88621. },
  88622. /**
  88623. * Sets the shadows Density value.
  88624. * 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.
  88625. * Values less than zero provide a filter of opposite hue.
  88626. */
  88627. set: function (value) {
  88628. this._shadowsDensity = value;
  88629. this._dirty = true;
  88630. },
  88631. enumerable: true,
  88632. configurable: true
  88633. });
  88634. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  88635. /**
  88636. * Gets the shadows Saturation value.
  88637. * 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.
  88638. */
  88639. get: function () {
  88640. return this._shadowsSaturation;
  88641. },
  88642. /**
  88643. * Sets the shadows Saturation value.
  88644. * 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.
  88645. */
  88646. set: function (value) {
  88647. this._shadowsSaturation = value;
  88648. this._dirty = true;
  88649. },
  88650. enumerable: true,
  88651. configurable: true
  88652. });
  88653. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  88654. /**
  88655. * Gets the shadows Exposure value.
  88656. * 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.
  88657. */
  88658. get: function () {
  88659. return this._shadowsExposure;
  88660. },
  88661. /**
  88662. * Sets the shadows Exposure value.
  88663. * 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.
  88664. */
  88665. set: function (value) {
  88666. this._shadowsExposure = value;
  88667. this._dirty = true;
  88668. },
  88669. enumerable: true,
  88670. configurable: true
  88671. });
  88672. /**
  88673. * Returns the class name
  88674. * @returns The class name
  88675. */
  88676. ColorCurves.prototype.getClassName = function () {
  88677. return "ColorCurves";
  88678. };
  88679. /**
  88680. * Binds the color curves to the shader.
  88681. * @param colorCurves The color curve to bind
  88682. * @param effect The effect to bind to
  88683. * @param positiveUniform The positive uniform shader parameter
  88684. * @param neutralUniform The neutral uniform shader parameter
  88685. * @param negativeUniform The negative uniform shader parameter
  88686. */
  88687. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  88688. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  88689. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  88690. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  88691. if (colorCurves._dirty) {
  88692. colorCurves._dirty = false;
  88693. // Fill in global info.
  88694. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  88695. // Compute highlights info.
  88696. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  88697. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  88698. // Compute midtones info.
  88699. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  88700. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  88701. // Compute shadows info.
  88702. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  88703. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  88704. // Compute deltas (neutral is midtones).
  88705. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  88706. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  88707. }
  88708. if (effect) {
  88709. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  88710. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  88711. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  88712. }
  88713. };
  88714. /**
  88715. * Prepare the list of uniforms associated with the ColorCurves effects.
  88716. * @param uniformsList The list of uniforms used in the effect
  88717. */
  88718. ColorCurves.PrepareUniforms = function (uniformsList) {
  88719. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  88720. };
  88721. /**
  88722. * Returns color grading data based on a hue, density, saturation and exposure value.
  88723. * @param filterHue The hue of the color filter.
  88724. * @param filterDensity The density of the color filter.
  88725. * @param saturation The saturation.
  88726. * @param exposure The exposure.
  88727. * @param result The result data container.
  88728. */
  88729. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  88730. if (hue == null) {
  88731. return;
  88732. }
  88733. hue = ColorCurves.clamp(hue, 0, 360);
  88734. density = ColorCurves.clamp(density, -100, 100);
  88735. saturation = ColorCurves.clamp(saturation, -100, 100);
  88736. exposure = ColorCurves.clamp(exposure, -100, 100);
  88737. // Remap the slider/config filter density with non-linear mapping and also scale by half
  88738. // so that the maximum filter density is only 50% control. This provides fine control
  88739. // for small values and reasonable range.
  88740. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  88741. density *= 0.5;
  88742. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  88743. if (density < 0) {
  88744. density *= -1;
  88745. hue = (hue + 180) % 360;
  88746. }
  88747. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  88748. result.scaleToRef(2, result);
  88749. result.a = 1 + 0.01 * saturation;
  88750. };
  88751. /**
  88752. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  88753. * @param value The input slider value in range [-100,100].
  88754. * @returns Adjusted value.
  88755. */
  88756. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  88757. value /= 100;
  88758. var x = Math.abs(value);
  88759. x = Math.pow(x, 2);
  88760. if (value < 0) {
  88761. x *= -1;
  88762. }
  88763. x *= 100;
  88764. return x;
  88765. };
  88766. /**
  88767. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  88768. * @param hue The hue (H) input.
  88769. * @param saturation The saturation (S) input.
  88770. * @param brightness The brightness (B) input.
  88771. * @result An RGBA color represented as Vector4.
  88772. */
  88773. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  88774. var h = ColorCurves.clamp(hue, 0, 360);
  88775. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  88776. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  88777. if (s === 0) {
  88778. result.r = v;
  88779. result.g = v;
  88780. result.b = v;
  88781. }
  88782. else {
  88783. // sector 0 to 5
  88784. h /= 60;
  88785. var i = Math.floor(h);
  88786. // fractional part of h
  88787. var f = h - i;
  88788. var p = v * (1 - s);
  88789. var q = v * (1 - s * f);
  88790. var t = v * (1 - s * (1 - f));
  88791. switch (i) {
  88792. case 0:
  88793. result.r = v;
  88794. result.g = t;
  88795. result.b = p;
  88796. break;
  88797. case 1:
  88798. result.r = q;
  88799. result.g = v;
  88800. result.b = p;
  88801. break;
  88802. case 2:
  88803. result.r = p;
  88804. result.g = v;
  88805. result.b = t;
  88806. break;
  88807. case 3:
  88808. result.r = p;
  88809. result.g = q;
  88810. result.b = v;
  88811. break;
  88812. case 4:
  88813. result.r = t;
  88814. result.g = p;
  88815. result.b = v;
  88816. break;
  88817. default: // case 5:
  88818. result.r = v;
  88819. result.g = p;
  88820. result.b = q;
  88821. break;
  88822. }
  88823. }
  88824. result.a = 1;
  88825. };
  88826. /**
  88827. * Returns a value clamped between min and max
  88828. * @param value The value to clamp
  88829. * @param min The minimum of value
  88830. * @param max The maximum of value
  88831. * @returns The clamped value.
  88832. */
  88833. ColorCurves.clamp = function (value, min, max) {
  88834. return Math.min(Math.max(value, min), max);
  88835. };
  88836. /**
  88837. * Clones the current color curve instance.
  88838. * @return The cloned curves
  88839. */
  88840. ColorCurves.prototype.clone = function () {
  88841. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  88842. };
  88843. /**
  88844. * Serializes the current color curve instance to a json representation.
  88845. * @return a JSON representation
  88846. */
  88847. ColorCurves.prototype.serialize = function () {
  88848. return BABYLON.SerializationHelper.Serialize(this);
  88849. };
  88850. /**
  88851. * Parses the color curve from a json representation.
  88852. * @param source the JSON source to parse
  88853. * @return The parsed curves
  88854. */
  88855. ColorCurves.Parse = function (source) {
  88856. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  88857. };
  88858. __decorate([
  88859. BABYLON.serialize()
  88860. ], ColorCurves.prototype, "_globalHue", void 0);
  88861. __decorate([
  88862. BABYLON.serialize()
  88863. ], ColorCurves.prototype, "_globalDensity", void 0);
  88864. __decorate([
  88865. BABYLON.serialize()
  88866. ], ColorCurves.prototype, "_globalSaturation", void 0);
  88867. __decorate([
  88868. BABYLON.serialize()
  88869. ], ColorCurves.prototype, "_globalExposure", void 0);
  88870. __decorate([
  88871. BABYLON.serialize()
  88872. ], ColorCurves.prototype, "_highlightsHue", void 0);
  88873. __decorate([
  88874. BABYLON.serialize()
  88875. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  88876. __decorate([
  88877. BABYLON.serialize()
  88878. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  88879. __decorate([
  88880. BABYLON.serialize()
  88881. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  88882. __decorate([
  88883. BABYLON.serialize()
  88884. ], ColorCurves.prototype, "_midtonesHue", void 0);
  88885. __decorate([
  88886. BABYLON.serialize()
  88887. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  88888. __decorate([
  88889. BABYLON.serialize()
  88890. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  88891. __decorate([
  88892. BABYLON.serialize()
  88893. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  88894. return ColorCurves;
  88895. }());
  88896. BABYLON.ColorCurves = ColorCurves;
  88897. })(BABYLON || (BABYLON = {}));
  88898. //# sourceMappingURL=babylon.colorCurves.js.map
  88899. var BABYLON;
  88900. (function (BABYLON) {
  88901. /**
  88902. * Post process which applies a refractin texture
  88903. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88904. */
  88905. var RefractionPostProcess = /** @class */ (function (_super) {
  88906. __extends(RefractionPostProcess, _super);
  88907. /**
  88908. * Initializes the RefractionPostProcess
  88909. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88910. * @param name The name of the effect.
  88911. * @param refractionTextureUrl Url of the refraction texture to use
  88912. * @param color the base color of the refraction (used to taint the rendering)
  88913. * @param depth simulated refraction depth
  88914. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  88915. * @param camera The camera to apply the render pass to.
  88916. * @param options The required width/height ratio to downsize to before computing the render pass.
  88917. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88918. * @param engine The engine which the post process will be applied. (default: current engine)
  88919. * @param reusable If the post process can be reused on the same frame. (default: false)
  88920. */
  88921. function RefractionPostProcess(name, refractionTextureUrl,
  88922. /** the base color of the refraction (used to taint the rendering) */
  88923. color,
  88924. /** simulated refraction depth */
  88925. depth,
  88926. /** the coefficient of the base color (0 to remove base color tainting) */
  88927. colorLevel, options, camera, samplingMode, engine, reusable) {
  88928. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  88929. _this.color = color;
  88930. _this.depth = depth;
  88931. _this.colorLevel = colorLevel;
  88932. _this._ownRefractionTexture = true;
  88933. _this.onActivateObservable.add(function (cam) {
  88934. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  88935. });
  88936. _this.onApplyObservable.add(function (effect) {
  88937. effect.setColor3("baseColor", _this.color);
  88938. effect.setFloat("depth", _this.depth);
  88939. effect.setFloat("colorLevel", _this.colorLevel);
  88940. effect.setTexture("refractionSampler", _this._refTexture);
  88941. });
  88942. return _this;
  88943. }
  88944. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  88945. /**
  88946. * Gets or sets the refraction texture
  88947. * Please note that you are responsible for disposing the texture if you set it manually
  88948. */
  88949. get: function () {
  88950. return this._refTexture;
  88951. },
  88952. set: function (value) {
  88953. if (this._refTexture && this._ownRefractionTexture) {
  88954. this._refTexture.dispose();
  88955. }
  88956. this._refTexture = value;
  88957. this._ownRefractionTexture = false;
  88958. },
  88959. enumerable: true,
  88960. configurable: true
  88961. });
  88962. // Methods
  88963. /**
  88964. * Disposes of the post process
  88965. * @param camera Camera to dispose post process on
  88966. */
  88967. RefractionPostProcess.prototype.dispose = function (camera) {
  88968. if (this._refTexture && this._ownRefractionTexture) {
  88969. this._refTexture.dispose();
  88970. this._refTexture = null;
  88971. }
  88972. _super.prototype.dispose.call(this, camera);
  88973. };
  88974. return RefractionPostProcess;
  88975. }(BABYLON.PostProcess));
  88976. BABYLON.RefractionPostProcess = RefractionPostProcess;
  88977. })(BABYLON || (BABYLON = {}));
  88978. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  88979. var BABYLON;
  88980. (function (BABYLON) {
  88981. /**
  88982. * Post process used to render in black and white
  88983. */
  88984. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  88985. __extends(BlackAndWhitePostProcess, _super);
  88986. /**
  88987. * Creates a black and white post process
  88988. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  88989. * @param name The name of the effect.
  88990. * @param options The required width/height ratio to downsize to before computing the render pass.
  88991. * @param camera The camera to apply the render pass to.
  88992. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88993. * @param engine The engine which the post process will be applied. (default: current engine)
  88994. * @param reusable If the post process can be reused on the same frame. (default: false)
  88995. */
  88996. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  88997. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  88998. /**
  88999. * Linear about to convert he result to black and white (default: 1)
  89000. */
  89001. _this.degree = 1;
  89002. _this.onApplyObservable.add(function (effect) {
  89003. effect.setFloat("degree", _this.degree);
  89004. });
  89005. return _this;
  89006. }
  89007. return BlackAndWhitePostProcess;
  89008. }(BABYLON.PostProcess));
  89009. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  89010. })(BABYLON || (BABYLON = {}));
  89011. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  89012. var BABYLON;
  89013. (function (BABYLON) {
  89014. /**
  89015. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  89016. * input texture to perform effects such as edge detection or sharpening
  89017. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  89018. */
  89019. var ConvolutionPostProcess = /** @class */ (function (_super) {
  89020. __extends(ConvolutionPostProcess, _super);
  89021. /**
  89022. * Creates a new instance ConvolutionPostProcess
  89023. * @param name The name of the effect.
  89024. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  89025. * @param options The required width/height ratio to downsize to before computing the render pass.
  89026. * @param camera The camera to apply the render pass to.
  89027. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89028. * @param engine The engine which the post process will be applied. (default: current engine)
  89029. * @param reusable If the post process can be reused on the same frame. (default: false)
  89030. * @param textureType Type of textures used when performing the post process. (default: 0)
  89031. */
  89032. function ConvolutionPostProcess(name,
  89033. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  89034. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  89035. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89036. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89037. _this.kernel = kernel;
  89038. _this.onApply = function (effect) {
  89039. effect.setFloat2("screenSize", _this.width, _this.height);
  89040. effect.setArray("kernel", _this.kernel);
  89041. };
  89042. return _this;
  89043. }
  89044. // Statics
  89045. /**
  89046. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89047. */
  89048. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  89049. /**
  89050. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89051. */
  89052. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  89053. /**
  89054. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89055. */
  89056. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  89057. /**
  89058. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89059. */
  89060. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  89061. /**
  89062. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89063. */
  89064. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  89065. /**
  89066. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89067. */
  89068. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  89069. return ConvolutionPostProcess;
  89070. }(BABYLON.PostProcess));
  89071. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  89072. })(BABYLON || (BABYLON = {}));
  89073. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  89074. var BABYLON;
  89075. (function (BABYLON) {
  89076. /**
  89077. * Applies a kernel filter to the image
  89078. */
  89079. var FilterPostProcess = /** @class */ (function (_super) {
  89080. __extends(FilterPostProcess, _super);
  89081. /**
  89082. *
  89083. * @param name The name of the effect.
  89084. * @param kernelMatrix The matrix to be applied to the image
  89085. * @param options The required width/height ratio to downsize to before computing the render pass.
  89086. * @param camera The camera to apply the render pass to.
  89087. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89088. * @param engine The engine which the post process will be applied. (default: current engine)
  89089. * @param reusable If the post process can be reused on the same frame. (default: false)
  89090. */
  89091. function FilterPostProcess(name,
  89092. /** The matrix to be applied to the image */
  89093. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  89094. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  89095. _this.kernelMatrix = kernelMatrix;
  89096. _this.onApply = function (effect) {
  89097. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  89098. };
  89099. return _this;
  89100. }
  89101. return FilterPostProcess;
  89102. }(BABYLON.PostProcess));
  89103. BABYLON.FilterPostProcess = FilterPostProcess;
  89104. })(BABYLON || (BABYLON = {}));
  89105. //# sourceMappingURL=babylon.filterPostProcess.js.map
  89106. var BABYLON;
  89107. (function (BABYLON) {
  89108. /**
  89109. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  89110. */
  89111. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  89112. __extends(VolumetricLightScatteringPostProcess, _super);
  89113. /**
  89114. * @constructor
  89115. * @param name The post-process name
  89116. * @param 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)
  89117. * @param camera The camera that the post-process will be attached to
  89118. * @param mesh The mesh used to create the light scattering
  89119. * @param samples The post-process quality, default 100
  89120. * @param samplingModeThe post-process filtering mode
  89121. * @param engine The babylon engine
  89122. * @param reusable If the post-process is reusable
  89123. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  89124. */
  89125. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  89126. if (samples === void 0) { samples = 100; }
  89127. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89128. 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;
  89129. _this._screenCoordinates = BABYLON.Vector2.Zero();
  89130. /**
  89131. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  89132. */
  89133. _this.customMeshPosition = BABYLON.Vector3.Zero();
  89134. /**
  89135. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  89136. */
  89137. _this.useCustomMeshPosition = false;
  89138. /**
  89139. * If the post-process should inverse the light scattering direction
  89140. */
  89141. _this.invert = true;
  89142. /**
  89143. * Array containing the excluded meshes not rendered in the internal pass
  89144. */
  89145. _this.excludedMeshes = new Array();
  89146. /**
  89147. * Controls the overall intensity of the post-process
  89148. */
  89149. _this.exposure = 0.3;
  89150. /**
  89151. * Dissipates each sample's contribution in range [0, 1]
  89152. */
  89153. _this.decay = 0.96815;
  89154. /**
  89155. * Controls the overall intensity of each sample
  89156. */
  89157. _this.weight = 0.58767;
  89158. /**
  89159. * Controls the density of each sample
  89160. */
  89161. _this.density = 0.926;
  89162. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  89163. engine = scene.getEngine();
  89164. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  89165. // Configure mesh
  89166. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  89167. // Configure
  89168. _this._createPass(scene, ratio.passRatio || ratio);
  89169. _this.onActivate = function (camera) {
  89170. if (!_this.isSupported) {
  89171. _this.dispose(camera);
  89172. }
  89173. _this.onActivate = null;
  89174. };
  89175. _this.onApplyObservable.add(function (effect) {
  89176. _this._updateMeshScreenCoordinates(scene);
  89177. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  89178. effect.setFloat("exposure", _this.exposure);
  89179. effect.setFloat("decay", _this.decay);
  89180. effect.setFloat("weight", _this.weight);
  89181. effect.setFloat("density", _this.density);
  89182. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  89183. });
  89184. return _this;
  89185. }
  89186. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  89187. /**
  89188. * @hidden
  89189. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  89190. */
  89191. get: function () {
  89192. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  89193. return false;
  89194. },
  89195. set: function (useDiffuseColor) {
  89196. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  89197. },
  89198. enumerable: true,
  89199. configurable: true
  89200. });
  89201. /**
  89202. * Returns the string "VolumetricLightScatteringPostProcess"
  89203. * @returns "VolumetricLightScatteringPostProcess"
  89204. */
  89205. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  89206. return "VolumetricLightScatteringPostProcess";
  89207. };
  89208. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  89209. var mesh = subMesh.getMesh();
  89210. // Render this.mesh as default
  89211. if (mesh === this.mesh && mesh.material) {
  89212. return mesh.material.isReady(mesh);
  89213. }
  89214. var defines = [];
  89215. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89216. var material = subMesh.getMaterial();
  89217. // Alpha test
  89218. if (material) {
  89219. if (material.needAlphaTesting()) {
  89220. defines.push("#define ALPHATEST");
  89221. }
  89222. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89223. attribs.push(BABYLON.VertexBuffer.UVKind);
  89224. defines.push("#define UV1");
  89225. }
  89226. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  89227. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89228. defines.push("#define UV2");
  89229. }
  89230. }
  89231. // Bones
  89232. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89233. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89234. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89235. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89236. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  89237. }
  89238. else {
  89239. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89240. }
  89241. // Instances
  89242. if (useInstances) {
  89243. defines.push("#define INSTANCES");
  89244. attribs.push("world0");
  89245. attribs.push("world1");
  89246. attribs.push("world2");
  89247. attribs.push("world3");
  89248. }
  89249. // Get correct effect
  89250. var join = defines.join("\n");
  89251. if (this._cachedDefines !== join) {
  89252. this._cachedDefines = join;
  89253. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  89254. }
  89255. return this._volumetricLightScatteringPass.isReady();
  89256. };
  89257. /**
  89258. * Sets the new light position for light scattering effect
  89259. * @param position The new custom light position
  89260. */
  89261. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  89262. this.customMeshPosition = position;
  89263. };
  89264. /**
  89265. * Returns the light position for light scattering effect
  89266. * @return Vector3 The custom light position
  89267. */
  89268. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  89269. return this.customMeshPosition;
  89270. };
  89271. /**
  89272. * Disposes the internal assets and detaches the post-process from the camera
  89273. */
  89274. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  89275. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  89276. if (rttIndex !== -1) {
  89277. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  89278. }
  89279. this._volumetricLightScatteringRTT.dispose();
  89280. _super.prototype.dispose.call(this, camera);
  89281. };
  89282. /**
  89283. * Returns the render target texture used by the post-process
  89284. * @return the render target texture used by the post-process
  89285. */
  89286. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  89287. return this._volumetricLightScatteringRTT;
  89288. };
  89289. // Private methods
  89290. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  89291. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  89292. return true;
  89293. }
  89294. return false;
  89295. };
  89296. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  89297. var _this = this;
  89298. var engine = scene.getEngine();
  89299. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89300. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89301. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89302. this._volumetricLightScatteringRTT.renderList = null;
  89303. this._volumetricLightScatteringRTT.renderParticles = false;
  89304. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  89305. var camera = this.getCamera();
  89306. if (camera) {
  89307. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89308. }
  89309. else {
  89310. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89311. }
  89312. // Custom render function for submeshes
  89313. var renderSubMesh = function (subMesh) {
  89314. var mesh = subMesh.getRenderingMesh();
  89315. if (_this._meshExcluded(mesh)) {
  89316. return;
  89317. }
  89318. var material = subMesh.getMaterial();
  89319. if (!material) {
  89320. return;
  89321. }
  89322. var scene = mesh.getScene();
  89323. var engine = scene.getEngine();
  89324. // Culling
  89325. engine.setState(material.backFaceCulling);
  89326. // Managing instances
  89327. var batch = mesh._getInstancesRenderList(subMesh._id);
  89328. if (batch.mustReturn) {
  89329. return;
  89330. }
  89331. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  89332. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  89333. var effect = _this._volumetricLightScatteringPass;
  89334. if (mesh === _this.mesh) {
  89335. if (subMesh.effect) {
  89336. effect = subMesh.effect;
  89337. }
  89338. else {
  89339. effect = material.getEffect();
  89340. }
  89341. }
  89342. engine.enableEffect(effect);
  89343. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  89344. if (mesh === _this.mesh) {
  89345. material.bind(mesh.getWorldMatrix(), mesh);
  89346. }
  89347. else {
  89348. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  89349. // Alpha test
  89350. if (material && material.needAlphaTesting()) {
  89351. var alphaTexture = material.getAlphaTestTexture();
  89352. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  89353. if (alphaTexture) {
  89354. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89355. }
  89356. }
  89357. // Bones
  89358. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89359. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89360. }
  89361. }
  89362. // Draw
  89363. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  89364. }
  89365. };
  89366. // Render target texture callbacks
  89367. var savedSceneClearColor;
  89368. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  89369. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  89370. savedSceneClearColor = scene.clearColor;
  89371. scene.clearColor = sceneClearColor;
  89372. });
  89373. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  89374. scene.clearColor = savedSceneClearColor;
  89375. });
  89376. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89377. var engine = scene.getEngine();
  89378. var index;
  89379. if (depthOnlySubMeshes.length) {
  89380. engine.setColorWrite(false);
  89381. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89382. renderSubMesh(depthOnlySubMeshes.data[index]);
  89383. }
  89384. engine.setColorWrite(true);
  89385. }
  89386. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89387. renderSubMesh(opaqueSubMeshes.data[index]);
  89388. }
  89389. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89390. renderSubMesh(alphaTestSubMeshes.data[index]);
  89391. }
  89392. if (transparentSubMeshes.length) {
  89393. // Sort sub meshes
  89394. for (index = 0; index < transparentSubMeshes.length; index++) {
  89395. var submesh = transparentSubMeshes.data[index];
  89396. var boundingInfo = submesh.getBoundingInfo();
  89397. if (boundingInfo && scene.activeCamera) {
  89398. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  89399. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  89400. }
  89401. }
  89402. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  89403. sortedArray.sort(function (a, b) {
  89404. // Alpha index first
  89405. if (a._alphaIndex > b._alphaIndex) {
  89406. return 1;
  89407. }
  89408. if (a._alphaIndex < b._alphaIndex) {
  89409. return -1;
  89410. }
  89411. // Then distance to camera
  89412. if (a._distanceToCamera < b._distanceToCamera) {
  89413. return 1;
  89414. }
  89415. if (a._distanceToCamera > b._distanceToCamera) {
  89416. return -1;
  89417. }
  89418. return 0;
  89419. });
  89420. // Render sub meshes
  89421. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  89422. for (index = 0; index < sortedArray.length; index++) {
  89423. renderSubMesh(sortedArray[index]);
  89424. }
  89425. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89426. }
  89427. };
  89428. };
  89429. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  89430. var transform = scene.getTransformMatrix();
  89431. var meshPosition;
  89432. if (this.useCustomMeshPosition) {
  89433. meshPosition = this.customMeshPosition;
  89434. }
  89435. else if (this.attachedNode) {
  89436. meshPosition = this.attachedNode.position;
  89437. }
  89438. else {
  89439. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  89440. }
  89441. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  89442. this._screenCoordinates.x = pos.x / this._viewPort.width;
  89443. this._screenCoordinates.y = pos.y / this._viewPort.height;
  89444. if (this.invert) {
  89445. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  89446. }
  89447. };
  89448. // Static methods
  89449. /**
  89450. * Creates a default mesh for the Volumeric Light Scattering post-process
  89451. * @param name The mesh name
  89452. * @param scene The scene where to create the mesh
  89453. * @return the default mesh
  89454. */
  89455. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  89456. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  89457. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  89458. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  89459. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  89460. mesh.material = material;
  89461. return mesh;
  89462. };
  89463. __decorate([
  89464. BABYLON.serializeAsVector3()
  89465. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  89466. __decorate([
  89467. BABYLON.serialize()
  89468. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  89469. __decorate([
  89470. BABYLON.serialize()
  89471. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  89472. __decorate([
  89473. BABYLON.serializeAsMeshReference()
  89474. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  89475. __decorate([
  89476. BABYLON.serialize()
  89477. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  89478. __decorate([
  89479. BABYLON.serialize()
  89480. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  89481. __decorate([
  89482. BABYLON.serialize()
  89483. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  89484. __decorate([
  89485. BABYLON.serialize()
  89486. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  89487. __decorate([
  89488. BABYLON.serialize()
  89489. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  89490. return VolumetricLightScatteringPostProcess;
  89491. }(BABYLON.PostProcess));
  89492. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  89493. })(BABYLON || (BABYLON = {}));
  89494. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  89495. var BABYLON;
  89496. (function (BABYLON) {
  89497. /**
  89498. *
  89499. * This post-process allows the modification of rendered colors by using
  89500. * a 'look-up table' (LUT). This effect is also called Color Grading.
  89501. *
  89502. * The object needs to be provided an url to a texture containing the color
  89503. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  89504. * Use an image editing software to tweak the LUT to match your needs.
  89505. *
  89506. * For an example of a color LUT, see here:
  89507. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  89508. * For explanations on color grading, see here:
  89509. * @see http://udn.epicgames.com/Three/ColorGrading.html
  89510. *
  89511. */
  89512. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  89513. __extends(ColorCorrectionPostProcess, _super);
  89514. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  89515. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  89516. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89517. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  89518. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89519. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89520. _this.onApply = function (effect) {
  89521. effect.setTexture("colorTable", _this._colorTableTexture);
  89522. };
  89523. return _this;
  89524. }
  89525. return ColorCorrectionPostProcess;
  89526. }(BABYLON.PostProcess));
  89527. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  89528. })(BABYLON || (BABYLON = {}));
  89529. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  89530. var BABYLON;
  89531. (function (BABYLON) {
  89532. /** Defines operator used for tonemapping */
  89533. var TonemappingOperator;
  89534. (function (TonemappingOperator) {
  89535. /** Hable */
  89536. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  89537. /** Reinhard */
  89538. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  89539. /** HejiDawson */
  89540. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  89541. /** Photographic */
  89542. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  89543. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  89544. /**
  89545. * Defines a post process to apply tone mapping
  89546. */
  89547. var TonemapPostProcess = /** @class */ (function (_super) {
  89548. __extends(TonemapPostProcess, _super);
  89549. /**
  89550. * Creates a new TonemapPostProcess
  89551. * @param name defines the name of the postprocess
  89552. * @param _operator defines the operator to use
  89553. * @param exposureAdjustment defines the required exposure adjustement
  89554. * @param camera defines the camera to use (can be null)
  89555. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  89556. * @param engine defines the hosting engine (can be ignore if camera is set)
  89557. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  89558. */
  89559. function TonemapPostProcess(name, _operator,
  89560. /** Defines the required exposure adjustement */
  89561. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  89562. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89563. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89564. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  89565. _this._operator = _operator;
  89566. _this.exposureAdjustment = exposureAdjustment;
  89567. var defines = "#define ";
  89568. if (_this._operator === TonemappingOperator.Hable) {
  89569. defines += "HABLE_TONEMAPPING";
  89570. }
  89571. else if (_this._operator === TonemappingOperator.Reinhard) {
  89572. defines += "REINHARD_TONEMAPPING";
  89573. }
  89574. else if (_this._operator === TonemappingOperator.HejiDawson) {
  89575. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  89576. }
  89577. else if (_this._operator === TonemappingOperator.Photographic) {
  89578. defines += "PHOTOGRAPHIC_TONEMAPPING";
  89579. }
  89580. //sadly a second call to create the effect.
  89581. _this.updateEffect(defines);
  89582. _this.onApply = function (effect) {
  89583. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  89584. };
  89585. return _this;
  89586. }
  89587. return TonemapPostProcess;
  89588. }(BABYLON.PostProcess));
  89589. BABYLON.TonemapPostProcess = TonemapPostProcess;
  89590. })(BABYLON || (BABYLON = {}));
  89591. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  89592. var BABYLON;
  89593. (function (BABYLON) {
  89594. /**
  89595. * DisplayPassPostProcess which produces an output the same as it's input
  89596. */
  89597. var DisplayPassPostProcess = /** @class */ (function (_super) {
  89598. __extends(DisplayPassPostProcess, _super);
  89599. /**
  89600. * Creates the DisplayPassPostProcess
  89601. * @param name The name of the effect.
  89602. * @param options The required width/height ratio to downsize to before computing the render pass.
  89603. * @param camera The camera to apply the render pass to.
  89604. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89605. * @param engine The engine which the post process will be applied. (default: current engine)
  89606. * @param reusable If the post process can be reused on the same frame. (default: false)
  89607. */
  89608. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  89609. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  89610. }
  89611. return DisplayPassPostProcess;
  89612. }(BABYLON.PostProcess));
  89613. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  89614. })(BABYLON || (BABYLON = {}));
  89615. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  89616. var BABYLON;
  89617. (function (BABYLON) {
  89618. /**
  89619. * Extracts highlights from the image
  89620. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89621. */
  89622. var HighlightsPostProcess = /** @class */ (function (_super) {
  89623. __extends(HighlightsPostProcess, _super);
  89624. /**
  89625. * Extracts highlights from the image
  89626. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89627. * @param name The name of the effect.
  89628. * @param options The required width/height ratio to downsize to before computing the render pass.
  89629. * @param camera The camera to apply the render pass to.
  89630. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89631. * @param engine The engine which the post process will be applied. (default: current engine)
  89632. * @param reusable If the post process can be reused on the same frame. (default: false)
  89633. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  89634. */
  89635. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  89636. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89637. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89638. }
  89639. return HighlightsPostProcess;
  89640. }(BABYLON.PostProcess));
  89641. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  89642. })(BABYLON || (BABYLON = {}));
  89643. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  89644. var BABYLON;
  89645. (function (BABYLON) {
  89646. /**
  89647. * ImageProcessingPostProcess
  89648. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  89649. */
  89650. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  89651. __extends(ImageProcessingPostProcess, _super);
  89652. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  89653. if (camera === void 0) { camera = null; }
  89654. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89655. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  89656. _this._fromLinearSpace = true;
  89657. /**
  89658. * Defines cache preventing GC.
  89659. */
  89660. _this._defines = {
  89661. IMAGEPROCESSING: false,
  89662. VIGNETTE: false,
  89663. VIGNETTEBLENDMODEMULTIPLY: false,
  89664. VIGNETTEBLENDMODEOPAQUE: false,
  89665. TONEMAPPING: false,
  89666. TONEMAPPING_ACES: false,
  89667. CONTRAST: false,
  89668. COLORCURVES: false,
  89669. COLORGRADING: false,
  89670. COLORGRADING3D: false,
  89671. FROMLINEARSPACE: false,
  89672. SAMPLER3DGREENDEPTH: false,
  89673. SAMPLER3DBGRMAP: false,
  89674. IMAGEPROCESSINGPOSTPROCESS: false,
  89675. EXPOSURE: false,
  89676. };
  89677. // Setup the configuration as forced by the constructor. This would then not force the
  89678. // scene materials output in linear space and let untouched the default forward pass.
  89679. if (imageProcessingConfiguration) {
  89680. imageProcessingConfiguration.applyByPostProcess = true;
  89681. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  89682. // This will cause the shader to be compiled
  89683. _this.fromLinearSpace = false;
  89684. }
  89685. // Setup the default processing configuration to the scene.
  89686. else {
  89687. _this._attachImageProcessingConfiguration(null, true);
  89688. _this.imageProcessingConfiguration.applyByPostProcess = true;
  89689. }
  89690. _this.onApply = function (effect) {
  89691. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  89692. };
  89693. return _this;
  89694. }
  89695. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  89696. /**
  89697. * Gets the image processing configuration used either in this material.
  89698. */
  89699. get: function () {
  89700. return this._imageProcessingConfiguration;
  89701. },
  89702. /**
  89703. * Sets the Default image processing configuration used either in the this material.
  89704. *
  89705. * If sets to null, the scene one is in use.
  89706. */
  89707. set: function (value) {
  89708. this._attachImageProcessingConfiguration(value);
  89709. },
  89710. enumerable: true,
  89711. configurable: true
  89712. });
  89713. /**
  89714. * Attaches a new image processing configuration to the PBR Material.
  89715. * @param configuration
  89716. */
  89717. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  89718. var _this = this;
  89719. if (doNotBuild === void 0) { doNotBuild = false; }
  89720. if (configuration === this._imageProcessingConfiguration) {
  89721. return;
  89722. }
  89723. // Detaches observer.
  89724. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89725. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89726. }
  89727. // Pick the scene configuration if needed.
  89728. if (!configuration) {
  89729. var scene = null;
  89730. var engine = this.getEngine();
  89731. var camera = this.getCamera();
  89732. if (camera) {
  89733. scene = camera.getScene();
  89734. }
  89735. else if (engine && engine.scenes) {
  89736. var scenes = engine.scenes;
  89737. scene = scenes[scenes.length - 1];
  89738. }
  89739. else {
  89740. scene = BABYLON.Engine.LastCreatedScene;
  89741. }
  89742. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  89743. }
  89744. else {
  89745. this._imageProcessingConfiguration = configuration;
  89746. }
  89747. // Attaches observer.
  89748. if (this._imageProcessingConfiguration) {
  89749. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89750. _this._updateParameters();
  89751. });
  89752. }
  89753. // Ensure the effect will be rebuilt.
  89754. if (!doNotBuild) {
  89755. this._updateParameters();
  89756. }
  89757. };
  89758. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  89759. /**
  89760. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89761. */
  89762. get: function () {
  89763. return this.imageProcessingConfiguration.colorCurves;
  89764. },
  89765. /**
  89766. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89767. */
  89768. set: function (value) {
  89769. this.imageProcessingConfiguration.colorCurves = value;
  89770. },
  89771. enumerable: true,
  89772. configurable: true
  89773. });
  89774. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  89775. /**
  89776. * Gets wether the color curves effect is enabled.
  89777. */
  89778. get: function () {
  89779. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89780. },
  89781. /**
  89782. * Sets wether the color curves effect is enabled.
  89783. */
  89784. set: function (value) {
  89785. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89786. },
  89787. enumerable: true,
  89788. configurable: true
  89789. });
  89790. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  89791. /**
  89792. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89793. */
  89794. get: function () {
  89795. return this.imageProcessingConfiguration.colorGradingTexture;
  89796. },
  89797. /**
  89798. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89799. */
  89800. set: function (value) {
  89801. this.imageProcessingConfiguration.colorGradingTexture = value;
  89802. },
  89803. enumerable: true,
  89804. configurable: true
  89805. });
  89806. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  89807. /**
  89808. * Gets wether the color grading effect is enabled.
  89809. */
  89810. get: function () {
  89811. return this.imageProcessingConfiguration.colorGradingEnabled;
  89812. },
  89813. /**
  89814. * Gets wether the color grading effect is enabled.
  89815. */
  89816. set: function (value) {
  89817. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89818. },
  89819. enumerable: true,
  89820. configurable: true
  89821. });
  89822. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  89823. /**
  89824. * Gets exposure used in the effect.
  89825. */
  89826. get: function () {
  89827. return this.imageProcessingConfiguration.exposure;
  89828. },
  89829. /**
  89830. * Sets exposure used in the effect.
  89831. */
  89832. set: function (value) {
  89833. this.imageProcessingConfiguration.exposure = value;
  89834. },
  89835. enumerable: true,
  89836. configurable: true
  89837. });
  89838. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  89839. /**
  89840. * Gets wether tonemapping is enabled or not.
  89841. */
  89842. get: function () {
  89843. return this._imageProcessingConfiguration.toneMappingEnabled;
  89844. },
  89845. /**
  89846. * Sets wether tonemapping is enabled or not
  89847. */
  89848. set: function (value) {
  89849. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89850. },
  89851. enumerable: true,
  89852. configurable: true
  89853. });
  89854. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  89855. /**
  89856. * Gets contrast used in the effect.
  89857. */
  89858. get: function () {
  89859. return this.imageProcessingConfiguration.contrast;
  89860. },
  89861. /**
  89862. * Sets contrast used in the effect.
  89863. */
  89864. set: function (value) {
  89865. this.imageProcessingConfiguration.contrast = value;
  89866. },
  89867. enumerable: true,
  89868. configurable: true
  89869. });
  89870. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  89871. /**
  89872. * Gets Vignette stretch size.
  89873. */
  89874. get: function () {
  89875. return this.imageProcessingConfiguration.vignetteStretch;
  89876. },
  89877. /**
  89878. * Sets Vignette stretch size.
  89879. */
  89880. set: function (value) {
  89881. this.imageProcessingConfiguration.vignetteStretch = value;
  89882. },
  89883. enumerable: true,
  89884. configurable: true
  89885. });
  89886. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  89887. /**
  89888. * Gets Vignette centre X Offset.
  89889. */
  89890. get: function () {
  89891. return this.imageProcessingConfiguration.vignetteCentreX;
  89892. },
  89893. /**
  89894. * Sets Vignette centre X Offset.
  89895. */
  89896. set: function (value) {
  89897. this.imageProcessingConfiguration.vignetteCentreX = value;
  89898. },
  89899. enumerable: true,
  89900. configurable: true
  89901. });
  89902. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  89903. /**
  89904. * Gets Vignette centre Y Offset.
  89905. */
  89906. get: function () {
  89907. return this.imageProcessingConfiguration.vignetteCentreY;
  89908. },
  89909. /**
  89910. * Sets Vignette centre Y Offset.
  89911. */
  89912. set: function (value) {
  89913. this.imageProcessingConfiguration.vignetteCentreY = value;
  89914. },
  89915. enumerable: true,
  89916. configurable: true
  89917. });
  89918. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  89919. /**
  89920. * Gets Vignette weight or intensity of the vignette effect.
  89921. */
  89922. get: function () {
  89923. return this.imageProcessingConfiguration.vignetteWeight;
  89924. },
  89925. /**
  89926. * Sets Vignette weight or intensity of the vignette effect.
  89927. */
  89928. set: function (value) {
  89929. this.imageProcessingConfiguration.vignetteWeight = value;
  89930. },
  89931. enumerable: true,
  89932. configurable: true
  89933. });
  89934. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  89935. /**
  89936. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89937. * if vignetteEnabled is set to true.
  89938. */
  89939. get: function () {
  89940. return this.imageProcessingConfiguration.vignetteColor;
  89941. },
  89942. /**
  89943. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89944. * if vignetteEnabled is set to true.
  89945. */
  89946. set: function (value) {
  89947. this.imageProcessingConfiguration.vignetteColor = value;
  89948. },
  89949. enumerable: true,
  89950. configurable: true
  89951. });
  89952. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  89953. /**
  89954. * Gets Camera field of view used by the Vignette effect.
  89955. */
  89956. get: function () {
  89957. return this.imageProcessingConfiguration.vignetteCameraFov;
  89958. },
  89959. /**
  89960. * Sets Camera field of view used by the Vignette effect.
  89961. */
  89962. set: function (value) {
  89963. this.imageProcessingConfiguration.vignetteCameraFov = value;
  89964. },
  89965. enumerable: true,
  89966. configurable: true
  89967. });
  89968. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  89969. /**
  89970. * Gets the vignette blend mode allowing different kind of effect.
  89971. */
  89972. get: function () {
  89973. return this.imageProcessingConfiguration.vignetteBlendMode;
  89974. },
  89975. /**
  89976. * Sets the vignette blend mode allowing different kind of effect.
  89977. */
  89978. set: function (value) {
  89979. this.imageProcessingConfiguration.vignetteBlendMode = value;
  89980. },
  89981. enumerable: true,
  89982. configurable: true
  89983. });
  89984. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  89985. /**
  89986. * Gets wether the vignette effect is enabled.
  89987. */
  89988. get: function () {
  89989. return this.imageProcessingConfiguration.vignetteEnabled;
  89990. },
  89991. /**
  89992. * Sets wether the vignette effect is enabled.
  89993. */
  89994. set: function (value) {
  89995. this.imageProcessingConfiguration.vignetteEnabled = value;
  89996. },
  89997. enumerable: true,
  89998. configurable: true
  89999. });
  90000. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  90001. /**
  90002. * Gets wether the input of the processing is in Gamma or Linear Space.
  90003. */
  90004. get: function () {
  90005. return this._fromLinearSpace;
  90006. },
  90007. /**
  90008. * Sets wether the input of the processing is in Gamma or Linear Space.
  90009. */
  90010. set: function (value) {
  90011. if (this._fromLinearSpace === value) {
  90012. return;
  90013. }
  90014. this._fromLinearSpace = value;
  90015. this._updateParameters();
  90016. },
  90017. enumerable: true,
  90018. configurable: true
  90019. });
  90020. /**
  90021. * "ImageProcessingPostProcess"
  90022. * @returns "ImageProcessingPostProcess"
  90023. */
  90024. ImageProcessingPostProcess.prototype.getClassName = function () {
  90025. return "ImageProcessingPostProcess";
  90026. };
  90027. ImageProcessingPostProcess.prototype._updateParameters = function () {
  90028. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  90029. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  90030. var defines = "";
  90031. for (var define in this._defines) {
  90032. if (this._defines[define]) {
  90033. defines += "#define " + define + ";\r\n";
  90034. }
  90035. }
  90036. var samplers = ["textureSampler"];
  90037. var uniforms = ["scale"];
  90038. if (BABYLON.ImageProcessingConfiguration) {
  90039. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  90040. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  90041. }
  90042. this.updateEffect(defines, uniforms, samplers);
  90043. };
  90044. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  90045. _super.prototype.dispose.call(this, camera);
  90046. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90047. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90048. }
  90049. if (this._imageProcessingConfiguration) {
  90050. this.imageProcessingConfiguration.applyByPostProcess = false;
  90051. }
  90052. };
  90053. __decorate([
  90054. BABYLON.serialize()
  90055. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  90056. return ImageProcessingPostProcess;
  90057. }(BABYLON.PostProcess));
  90058. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  90059. })(BABYLON || (BABYLON = {}));
  90060. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  90061. var BABYLON;
  90062. (function (BABYLON) {
  90063. /**
  90064. * Class used to store bone information
  90065. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  90066. */
  90067. var Bone = /** @class */ (function (_super) {
  90068. __extends(Bone, _super);
  90069. /**
  90070. * Create a new bone
  90071. * @param name defines the bone name
  90072. * @param skeleton defines the parent skeleton
  90073. * @param parentBone defines the parent (can be null if the bone is the root)
  90074. * @param localMatrix defines the local matrix
  90075. * @param restPose defines the rest pose matrix
  90076. * @param baseMatrix defines the base matrix
  90077. * @param index defines index of the bone in the hiearchy
  90078. */
  90079. function Bone(
  90080. /**
  90081. * defines the bone name
  90082. */
  90083. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  90084. if (parentBone === void 0) { parentBone = null; }
  90085. if (localMatrix === void 0) { localMatrix = null; }
  90086. if (restPose === void 0) { restPose = null; }
  90087. if (baseMatrix === void 0) { baseMatrix = null; }
  90088. if (index === void 0) { index = null; }
  90089. var _this = _super.call(this, name, skeleton.getScene()) || this;
  90090. _this.name = name;
  90091. /**
  90092. * Gets the list of child bones
  90093. */
  90094. _this.children = new Array();
  90095. /** Gets the animations associated with this bone */
  90096. _this.animations = new Array();
  90097. /**
  90098. * @hidden Internal only
  90099. * Set this value to map this bone to a different index in the transform matrices
  90100. * Set this value to -1 to exclude the bone from the transform matrices
  90101. */
  90102. _this._index = null;
  90103. _this._absoluteTransform = new BABYLON.Matrix();
  90104. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  90105. _this._scalingDeterminant = 1;
  90106. _this._worldTransform = new BABYLON.Matrix();
  90107. _this._needToDecompose = true;
  90108. _this._needToCompose = false;
  90109. _this._skeleton = skeleton;
  90110. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  90111. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  90112. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  90113. _this._index = index;
  90114. skeleton.bones.push(_this);
  90115. _this.setParent(parentBone, false);
  90116. if (baseMatrix || localMatrix) {
  90117. _this._updateDifferenceMatrix();
  90118. }
  90119. return _this;
  90120. }
  90121. Object.defineProperty(Bone.prototype, "_matrix", {
  90122. /** @hidden */
  90123. get: function () {
  90124. this._compose();
  90125. return this._localMatrix;
  90126. },
  90127. /** @hidden */
  90128. set: function (value) {
  90129. this._localMatrix.copyFrom(value);
  90130. this._needToDecompose = true;
  90131. },
  90132. enumerable: true,
  90133. configurable: true
  90134. });
  90135. // Members
  90136. /**
  90137. * Gets the parent skeleton
  90138. * @returns a skeleton
  90139. */
  90140. Bone.prototype.getSkeleton = function () {
  90141. return this._skeleton;
  90142. };
  90143. /**
  90144. * Gets parent bone
  90145. * @returns a bone or null if the bone is the root of the bone hierarchy
  90146. */
  90147. Bone.prototype.getParent = function () {
  90148. return this._parent;
  90149. };
  90150. /**
  90151. * Sets the parent bone
  90152. * @param parent defines the parent (can be null if the bone is the root)
  90153. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90154. */
  90155. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  90156. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90157. if (this._parent === parent) {
  90158. return;
  90159. }
  90160. if (this._parent) {
  90161. var index = this._parent.children.indexOf(this);
  90162. if (index !== -1) {
  90163. this._parent.children.splice(index, 1);
  90164. }
  90165. }
  90166. this._parent = parent;
  90167. if (this._parent) {
  90168. this._parent.children.push(this);
  90169. }
  90170. if (updateDifferenceMatrix) {
  90171. this._updateDifferenceMatrix();
  90172. }
  90173. this.markAsDirty();
  90174. };
  90175. /**
  90176. * Gets the local matrix
  90177. * @returns a matrix
  90178. */
  90179. Bone.prototype.getLocalMatrix = function () {
  90180. this._compose();
  90181. return this._localMatrix;
  90182. };
  90183. /**
  90184. * Gets the base matrix (initial matrix which remains unchanged)
  90185. * @returns a matrix
  90186. */
  90187. Bone.prototype.getBaseMatrix = function () {
  90188. return this._baseMatrix;
  90189. };
  90190. /**
  90191. * Gets the rest pose matrix
  90192. * @returns a matrix
  90193. */
  90194. Bone.prototype.getRestPose = function () {
  90195. return this._restPose;
  90196. };
  90197. /**
  90198. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  90199. */
  90200. Bone.prototype.getWorldMatrix = function () {
  90201. return this._worldTransform;
  90202. };
  90203. /**
  90204. * Sets the local matrix to rest pose matrix
  90205. */
  90206. Bone.prototype.returnToRest = function () {
  90207. this.updateMatrix(this._restPose.clone());
  90208. };
  90209. /**
  90210. * Gets the inverse of the absolute transform matrix.
  90211. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  90212. * @returns a matrix
  90213. */
  90214. Bone.prototype.getInvertedAbsoluteTransform = function () {
  90215. return this._invertedAbsoluteTransform;
  90216. };
  90217. /**
  90218. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  90219. * @returns a matrix
  90220. */
  90221. Bone.prototype.getAbsoluteTransform = function () {
  90222. return this._absoluteTransform;
  90223. };
  90224. Object.defineProperty(Bone.prototype, "position", {
  90225. // Properties (matches AbstractMesh properties)
  90226. /** Gets or sets current position (in local space) */
  90227. get: function () {
  90228. this._decompose();
  90229. return this._localPosition;
  90230. },
  90231. set: function (newPosition) {
  90232. this._decompose();
  90233. this._localPosition.copyFrom(newPosition);
  90234. this._markAsDirtyAndCompose();
  90235. },
  90236. enumerable: true,
  90237. configurable: true
  90238. });
  90239. Object.defineProperty(Bone.prototype, "rotation", {
  90240. /** Gets or sets current rotation (in local space) */
  90241. get: function () {
  90242. return this.getRotation();
  90243. },
  90244. set: function (newRotation) {
  90245. this.setRotation(newRotation);
  90246. },
  90247. enumerable: true,
  90248. configurable: true
  90249. });
  90250. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  90251. /** Gets or sets current rotation quaternion (in local space) */
  90252. get: function () {
  90253. this._decompose();
  90254. return this._localRotation;
  90255. },
  90256. set: function (newRotation) {
  90257. this.setRotationQuaternion(newRotation);
  90258. },
  90259. enumerable: true,
  90260. configurable: true
  90261. });
  90262. Object.defineProperty(Bone.prototype, "scaling", {
  90263. /** Gets or sets current scaling (in local space) */
  90264. get: function () {
  90265. return this.getScale();
  90266. },
  90267. set: function (newScaling) {
  90268. this.setScale(newScaling);
  90269. },
  90270. enumerable: true,
  90271. configurable: true
  90272. });
  90273. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  90274. /**
  90275. * Gets the animation properties override
  90276. */
  90277. get: function () {
  90278. return this._skeleton.animationPropertiesOverride;
  90279. },
  90280. enumerable: true,
  90281. configurable: true
  90282. });
  90283. // Methods
  90284. Bone.prototype._decompose = function () {
  90285. if (!this._needToDecompose) {
  90286. return;
  90287. }
  90288. this._needToDecompose = false;
  90289. if (!this._localScaling) {
  90290. this._localScaling = BABYLON.Vector3.Zero();
  90291. this._localRotation = BABYLON.Quaternion.Zero();
  90292. this._localPosition = BABYLON.Vector3.Zero();
  90293. }
  90294. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  90295. };
  90296. Bone.prototype._compose = function () {
  90297. if (!this._needToCompose) {
  90298. return;
  90299. }
  90300. this._needToCompose = false;
  90301. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  90302. };
  90303. /**
  90304. * Update the base and local matrices
  90305. * @param matrix defines the new base or local matrix
  90306. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90307. * @param updateLocalMatrix defines if the local matrix should be updated
  90308. */
  90309. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  90310. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90311. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  90312. this._baseMatrix.copyFrom(matrix);
  90313. if (updateDifferenceMatrix) {
  90314. this._updateDifferenceMatrix();
  90315. }
  90316. if (updateLocalMatrix) {
  90317. this._localMatrix.copyFrom(matrix);
  90318. this._markAsDirtyAndDecompose();
  90319. }
  90320. else {
  90321. this.markAsDirty();
  90322. }
  90323. };
  90324. /** @hidden */
  90325. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  90326. if (updateChildren === void 0) { updateChildren = true; }
  90327. if (!rootMatrix) {
  90328. rootMatrix = this._baseMatrix;
  90329. }
  90330. if (this._parent) {
  90331. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90332. }
  90333. else {
  90334. this._absoluteTransform.copyFrom(rootMatrix);
  90335. }
  90336. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  90337. if (updateChildren) {
  90338. for (var index = 0; index < this.children.length; index++) {
  90339. this.children[index]._updateDifferenceMatrix();
  90340. }
  90341. }
  90342. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  90343. };
  90344. /**
  90345. * Flag the bone as dirty (Forcing it to update everything)
  90346. */
  90347. Bone.prototype.markAsDirty = function () {
  90348. this._currentRenderId++;
  90349. this._childRenderId++;
  90350. this._skeleton._markAsDirty();
  90351. };
  90352. Bone.prototype._markAsDirtyAndCompose = function () {
  90353. this.markAsDirty();
  90354. this._needToCompose = true;
  90355. };
  90356. Bone.prototype._markAsDirtyAndDecompose = function () {
  90357. this.markAsDirty();
  90358. this._needToDecompose = true;
  90359. };
  90360. /**
  90361. * Copy an animation range from another bone
  90362. * @param source defines the source bone
  90363. * @param rangeName defines the range name to copy
  90364. * @param frameOffset defines the frame offset
  90365. * @param rescaleAsRequired defines if rescaling must be applied if required
  90366. * @param skelDimensionsRatio defines the scaling ratio
  90367. * @returns true if operation was successful
  90368. */
  90369. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  90370. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90371. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  90372. // all animation may be coming from a library skeleton, so may need to create animation
  90373. if (this.animations.length === 0) {
  90374. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  90375. this.animations[0].setKeys([]);
  90376. }
  90377. // get animation info / verify there is such a range from the source bone
  90378. var sourceRange = source.animations[0].getRange(rangeName);
  90379. if (!sourceRange) {
  90380. return false;
  90381. }
  90382. var from = sourceRange.from;
  90383. var to = sourceRange.to;
  90384. var sourceKeys = source.animations[0].getKeys();
  90385. // rescaling prep
  90386. var sourceBoneLength = source.length;
  90387. var sourceParent = source.getParent();
  90388. var parent = this.getParent();
  90389. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  90390. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  90391. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  90392. var destKeys = this.animations[0].getKeys();
  90393. // loop vars declaration
  90394. var orig;
  90395. var origTranslation;
  90396. var mat;
  90397. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  90398. orig = sourceKeys[key];
  90399. if (orig.frame >= from && orig.frame <= to) {
  90400. if (rescaleAsRequired) {
  90401. mat = orig.value.clone();
  90402. // scale based on parent ratio, when bone has parent
  90403. if (parentScalingReqd) {
  90404. origTranslation = mat.getTranslation();
  90405. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  90406. // scale based on skeleton dimension ratio when root bone, and value is passed
  90407. }
  90408. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  90409. origTranslation = mat.getTranslation();
  90410. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  90411. // use original when root bone, and no data for skelDimensionsRatio
  90412. }
  90413. else {
  90414. mat = orig.value;
  90415. }
  90416. }
  90417. else {
  90418. mat = orig.value;
  90419. }
  90420. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  90421. }
  90422. }
  90423. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  90424. return true;
  90425. };
  90426. /**
  90427. * Translate the bone in local or world space
  90428. * @param vec The amount to translate the bone
  90429. * @param space The space that the translation is in
  90430. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90431. */
  90432. Bone.prototype.translate = function (vec, space, mesh) {
  90433. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90434. var lm = this.getLocalMatrix();
  90435. if (space == BABYLON.Space.LOCAL) {
  90436. lm.m[12] += vec.x;
  90437. lm.m[13] += vec.y;
  90438. lm.m[14] += vec.z;
  90439. }
  90440. else {
  90441. var wm = null;
  90442. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90443. if (mesh) {
  90444. wm = mesh.getWorldMatrix();
  90445. }
  90446. this._skeleton.computeAbsoluteTransforms();
  90447. var tmat = Bone._tmpMats[0];
  90448. var tvec = Bone._tmpVecs[0];
  90449. if (this._parent) {
  90450. if (mesh && wm) {
  90451. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90452. tmat.multiplyToRef(wm, tmat);
  90453. }
  90454. else {
  90455. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90456. }
  90457. }
  90458. tmat.m[12] = 0;
  90459. tmat.m[13] = 0;
  90460. tmat.m[14] = 0;
  90461. tmat.invert();
  90462. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  90463. lm.m[12] += tvec.x;
  90464. lm.m[13] += tvec.y;
  90465. lm.m[14] += tvec.z;
  90466. }
  90467. this._markAsDirtyAndDecompose();
  90468. };
  90469. /**
  90470. * Set the postion of the bone in local or world space
  90471. * @param position The position to set the bone
  90472. * @param space The space that the position is in
  90473. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90474. */
  90475. Bone.prototype.setPosition = function (position, space, mesh) {
  90476. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90477. var lm = this.getLocalMatrix();
  90478. if (space == BABYLON.Space.LOCAL) {
  90479. lm.m[12] = position.x;
  90480. lm.m[13] = position.y;
  90481. lm.m[14] = position.z;
  90482. }
  90483. else {
  90484. var wm = null;
  90485. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90486. if (mesh) {
  90487. wm = mesh.getWorldMatrix();
  90488. }
  90489. this._skeleton.computeAbsoluteTransforms();
  90490. var tmat = Bone._tmpMats[0];
  90491. var vec = Bone._tmpVecs[0];
  90492. if (this._parent) {
  90493. if (mesh && wm) {
  90494. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90495. tmat.multiplyToRef(wm, tmat);
  90496. }
  90497. else {
  90498. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90499. }
  90500. }
  90501. tmat.invert();
  90502. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  90503. lm.m[12] = vec.x;
  90504. lm.m[13] = vec.y;
  90505. lm.m[14] = vec.z;
  90506. }
  90507. this._markAsDirtyAndDecompose();
  90508. };
  90509. /**
  90510. * Set the absolute position of the bone (world space)
  90511. * @param position The position to set the bone
  90512. * @param mesh The mesh that this bone is attached to
  90513. */
  90514. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  90515. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  90516. };
  90517. /**
  90518. * Scale the bone on the x, y and z axes (in local space)
  90519. * @param x The amount to scale the bone on the x axis
  90520. * @param y The amount to scale the bone on the y axis
  90521. * @param z The amount to scale the bone on the z axis
  90522. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  90523. */
  90524. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  90525. if (scaleChildren === void 0) { scaleChildren = false; }
  90526. var locMat = this.getLocalMatrix();
  90527. // Apply new scaling on top of current local matrix
  90528. var scaleMat = Bone._tmpMats[0];
  90529. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  90530. scaleMat.multiplyToRef(locMat, locMat);
  90531. // Invert scaling matrix and apply the inverse to all children
  90532. scaleMat.invert();
  90533. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  90534. var child = _a[_i];
  90535. var cm = child.getLocalMatrix();
  90536. cm.multiplyToRef(scaleMat, cm);
  90537. cm.m[12] *= x;
  90538. cm.m[13] *= y;
  90539. cm.m[14] *= z;
  90540. child._markAsDirtyAndDecompose();
  90541. }
  90542. this._markAsDirtyAndDecompose();
  90543. if (scaleChildren) {
  90544. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  90545. var child = _c[_b];
  90546. child.scale(x, y, z, scaleChildren);
  90547. }
  90548. }
  90549. };
  90550. /**
  90551. * Set the bone scaling in local space
  90552. * @param scale defines the scaling vector
  90553. */
  90554. Bone.prototype.setScale = function (scale) {
  90555. this._decompose();
  90556. this._localScaling.copyFrom(scale);
  90557. this._markAsDirtyAndCompose();
  90558. };
  90559. /**
  90560. * Gets the current scaling in local space
  90561. * @returns the current scaling vector
  90562. */
  90563. Bone.prototype.getScale = function () {
  90564. this._decompose();
  90565. return this._localScaling;
  90566. };
  90567. /**
  90568. * Gets the current scaling in local space and stores it in a target vector
  90569. * @param result defines the target vector
  90570. */
  90571. Bone.prototype.getScaleToRef = function (result) {
  90572. this._decompose();
  90573. result.copyFrom(this._localScaling);
  90574. };
  90575. /**
  90576. * Set the yaw, pitch, and roll of the bone in local or world space
  90577. * @param yaw The rotation of the bone on the y axis
  90578. * @param pitch The rotation of the bone on the x axis
  90579. * @param roll The rotation of the bone on the z axis
  90580. * @param space The space that the axes of rotation are in
  90581. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90582. */
  90583. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  90584. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90585. if (space === BABYLON.Space.LOCAL) {
  90586. var quat = Bone._tmpQuat;
  90587. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  90588. this.setRotationQuaternion(quat, space, mesh);
  90589. return;
  90590. }
  90591. var rotMatInv = Bone._tmpMats[0];
  90592. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90593. return;
  90594. }
  90595. var rotMat = Bone._tmpMats[1];
  90596. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  90597. rotMatInv.multiplyToRef(rotMat, rotMat);
  90598. this._rotateWithMatrix(rotMat, space, mesh);
  90599. };
  90600. /**
  90601. * Add a rotation to the bone on an axis in local or world space
  90602. * @param axis The axis to rotate the bone on
  90603. * @param amount The amount to rotate the bone
  90604. * @param space The space that the axis is in
  90605. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90606. */
  90607. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  90608. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90609. var rmat = Bone._tmpMats[0];
  90610. rmat.m[12] = 0;
  90611. rmat.m[13] = 0;
  90612. rmat.m[14] = 0;
  90613. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  90614. this._rotateWithMatrix(rmat, space, mesh);
  90615. };
  90616. /**
  90617. * Set the rotation of the bone to a particular axis angle in local or world space
  90618. * @param axis The axis to rotate the bone on
  90619. * @param angle The angle that the bone should be rotated to
  90620. * @param space The space that the axis is in
  90621. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90622. */
  90623. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  90624. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90625. if (space === BABYLON.Space.LOCAL) {
  90626. var quat = Bone._tmpQuat;
  90627. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  90628. this.setRotationQuaternion(quat, space, mesh);
  90629. return;
  90630. }
  90631. var rotMatInv = Bone._tmpMats[0];
  90632. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90633. return;
  90634. }
  90635. var rotMat = Bone._tmpMats[1];
  90636. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  90637. rotMatInv.multiplyToRef(rotMat, rotMat);
  90638. this._rotateWithMatrix(rotMat, space, mesh);
  90639. };
  90640. /**
  90641. * Set the euler rotation of the bone in local of world space
  90642. * @param rotation The euler rotation that the bone should be set to
  90643. * @param space The space that the rotation is in
  90644. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90645. */
  90646. Bone.prototype.setRotation = function (rotation, space, mesh) {
  90647. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90648. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  90649. };
  90650. /**
  90651. * Set the quaternion rotation of the bone in local of world space
  90652. * @param quat The quaternion rotation that the bone should be set to
  90653. * @param space The space that the rotation is in
  90654. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90655. */
  90656. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  90657. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90658. if (space === BABYLON.Space.LOCAL) {
  90659. this._decompose();
  90660. this._localRotation.copyFrom(quat);
  90661. this._markAsDirtyAndCompose();
  90662. return;
  90663. }
  90664. var rotMatInv = Bone._tmpMats[0];
  90665. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90666. return;
  90667. }
  90668. var rotMat = Bone._tmpMats[1];
  90669. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  90670. rotMatInv.multiplyToRef(rotMat, rotMat);
  90671. this._rotateWithMatrix(rotMat, space, mesh);
  90672. };
  90673. /**
  90674. * Set the rotation matrix of the bone in local of world space
  90675. * @param rotMat The rotation matrix that the bone should be set to
  90676. * @param space The space that the rotation is in
  90677. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90678. */
  90679. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  90680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90681. if (space === BABYLON.Space.LOCAL) {
  90682. var quat = Bone._tmpQuat;
  90683. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  90684. this.setRotationQuaternion(quat, space, mesh);
  90685. return;
  90686. }
  90687. var rotMatInv = Bone._tmpMats[0];
  90688. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90689. return;
  90690. }
  90691. var rotMat2 = Bone._tmpMats[1];
  90692. rotMat2.copyFrom(rotMat);
  90693. rotMatInv.multiplyToRef(rotMat, rotMat2);
  90694. this._rotateWithMatrix(rotMat2, space, mesh);
  90695. };
  90696. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  90697. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90698. var lmat = this.getLocalMatrix();
  90699. var lx = lmat.m[12];
  90700. var ly = lmat.m[13];
  90701. var lz = lmat.m[14];
  90702. var parent = this.getParent();
  90703. var parentScale = Bone._tmpMats[3];
  90704. var parentScaleInv = Bone._tmpMats[4];
  90705. if (parent && space == BABYLON.Space.WORLD) {
  90706. if (mesh) {
  90707. parentScale.copyFrom(mesh.getWorldMatrix());
  90708. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  90709. }
  90710. else {
  90711. parentScale.copyFrom(parent.getAbsoluteTransform());
  90712. }
  90713. parentScaleInv.copyFrom(parentScale);
  90714. parentScaleInv.invert();
  90715. lmat.multiplyToRef(parentScale, lmat);
  90716. lmat.multiplyToRef(rmat, lmat);
  90717. lmat.multiplyToRef(parentScaleInv, lmat);
  90718. }
  90719. else {
  90720. if (space == BABYLON.Space.WORLD && mesh) {
  90721. parentScale.copyFrom(mesh.getWorldMatrix());
  90722. parentScaleInv.copyFrom(parentScale);
  90723. parentScaleInv.invert();
  90724. lmat.multiplyToRef(parentScale, lmat);
  90725. lmat.multiplyToRef(rmat, lmat);
  90726. lmat.multiplyToRef(parentScaleInv, lmat);
  90727. }
  90728. else {
  90729. lmat.multiplyToRef(rmat, lmat);
  90730. }
  90731. }
  90732. lmat.m[12] = lx;
  90733. lmat.m[13] = ly;
  90734. lmat.m[14] = lz;
  90735. this.computeAbsoluteTransforms();
  90736. this._markAsDirtyAndDecompose();
  90737. };
  90738. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  90739. var scaleMatrix = Bone._tmpMats[2];
  90740. rotMatInv.copyFrom(this.getAbsoluteTransform());
  90741. if (mesh) {
  90742. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  90743. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  90744. }
  90745. rotMatInv.invert();
  90746. if (isNaN(rotMatInv.m[0])) {
  90747. // Matrix failed to invert.
  90748. // This can happen if scale is zero for example.
  90749. return false;
  90750. }
  90751. scaleMatrix.m[0] *= this._scalingDeterminant;
  90752. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  90753. return true;
  90754. };
  90755. /**
  90756. * Get the position of the bone in local or world space
  90757. * @param space The space that the returned position is in
  90758. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90759. * @returns The position of the bone
  90760. */
  90761. Bone.prototype.getPosition = function (space, mesh) {
  90762. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90763. if (mesh === void 0) { mesh = null; }
  90764. var pos = BABYLON.Vector3.Zero();
  90765. this.getPositionToRef(space, mesh, pos);
  90766. return pos;
  90767. };
  90768. /**
  90769. * Copy the position of the bone to a vector3 in local or world space
  90770. * @param space The space that the returned position is in
  90771. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90772. * @param result The vector3 to copy the position to
  90773. */
  90774. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  90775. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90776. if (space == BABYLON.Space.LOCAL) {
  90777. var lm = this.getLocalMatrix();
  90778. result.x = lm.m[12];
  90779. result.y = lm.m[13];
  90780. result.z = lm.m[14];
  90781. }
  90782. else {
  90783. var wm = null;
  90784. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90785. if (mesh) {
  90786. wm = mesh.getWorldMatrix();
  90787. }
  90788. this._skeleton.computeAbsoluteTransforms();
  90789. var tmat = Bone._tmpMats[0];
  90790. if (mesh && wm) {
  90791. tmat.copyFrom(this.getAbsoluteTransform());
  90792. tmat.multiplyToRef(wm, tmat);
  90793. }
  90794. else {
  90795. tmat = this.getAbsoluteTransform();
  90796. }
  90797. result.x = tmat.m[12];
  90798. result.y = tmat.m[13];
  90799. result.z = tmat.m[14];
  90800. }
  90801. };
  90802. /**
  90803. * Get the absolute position of the bone (world space)
  90804. * @param mesh The mesh that this bone is attached to
  90805. * @returns The absolute position of the bone
  90806. */
  90807. Bone.prototype.getAbsolutePosition = function (mesh) {
  90808. if (mesh === void 0) { mesh = null; }
  90809. var pos = BABYLON.Vector3.Zero();
  90810. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  90811. return pos;
  90812. };
  90813. /**
  90814. * Copy the absolute position of the bone (world space) to the result param
  90815. * @param mesh The mesh that this bone is attached to
  90816. * @param result The vector3 to copy the absolute position to
  90817. */
  90818. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  90819. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  90820. };
  90821. /**
  90822. * Compute the absolute transforms of this bone and its children
  90823. */
  90824. Bone.prototype.computeAbsoluteTransforms = function () {
  90825. this._compose();
  90826. if (this._parent) {
  90827. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90828. }
  90829. else {
  90830. this._absoluteTransform.copyFrom(this._localMatrix);
  90831. var poseMatrix = this._skeleton.getPoseMatrix();
  90832. if (poseMatrix) {
  90833. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  90834. }
  90835. }
  90836. var children = this.children;
  90837. var len = children.length;
  90838. for (var i = 0; i < len; i++) {
  90839. children[i].computeAbsoluteTransforms();
  90840. }
  90841. };
  90842. /**
  90843. * Get the world direction from an axis that is in the local space of the bone
  90844. * @param localAxis The local direction that is used to compute the world direction
  90845. * @param mesh The mesh that this bone is attached to
  90846. * @returns The world direction
  90847. */
  90848. Bone.prototype.getDirection = function (localAxis, mesh) {
  90849. if (mesh === void 0) { mesh = null; }
  90850. var result = BABYLON.Vector3.Zero();
  90851. this.getDirectionToRef(localAxis, mesh, result);
  90852. return result;
  90853. };
  90854. /**
  90855. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  90856. * @param localAxis The local direction that is used to compute the world direction
  90857. * @param mesh The mesh that this bone is attached to
  90858. * @param result The vector3 that the world direction will be copied to
  90859. */
  90860. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  90861. if (mesh === void 0) { mesh = null; }
  90862. var wm = null;
  90863. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90864. if (mesh) {
  90865. wm = mesh.getWorldMatrix();
  90866. }
  90867. this._skeleton.computeAbsoluteTransforms();
  90868. var mat = Bone._tmpMats[0];
  90869. mat.copyFrom(this.getAbsoluteTransform());
  90870. if (mesh && wm) {
  90871. mat.multiplyToRef(wm, mat);
  90872. }
  90873. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  90874. result.normalize();
  90875. };
  90876. /**
  90877. * Get the euler rotation of the bone in local or world space
  90878. * @param space The space that the rotation should be in
  90879. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90880. * @returns The euler rotation
  90881. */
  90882. Bone.prototype.getRotation = function (space, mesh) {
  90883. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90884. if (mesh === void 0) { mesh = null; }
  90885. var result = BABYLON.Vector3.Zero();
  90886. this.getRotationToRef(space, mesh, result);
  90887. return result;
  90888. };
  90889. /**
  90890. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  90891. * @param space The space that the rotation should be in
  90892. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90893. * @param result The vector3 that the rotation should be copied to
  90894. */
  90895. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  90896. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90897. if (mesh === void 0) { mesh = null; }
  90898. var quat = Bone._tmpQuat;
  90899. this.getRotationQuaternionToRef(space, mesh, quat);
  90900. quat.toEulerAnglesToRef(result);
  90901. };
  90902. /**
  90903. * Get the quaternion rotation of the bone in either local or world space
  90904. * @param space The space that the rotation should be in
  90905. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90906. * @returns The quaternion rotation
  90907. */
  90908. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  90909. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90910. if (mesh === void 0) { mesh = null; }
  90911. var result = BABYLON.Quaternion.Identity();
  90912. this.getRotationQuaternionToRef(space, mesh, result);
  90913. return result;
  90914. };
  90915. /**
  90916. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  90917. * @param space The space that the rotation should be in
  90918. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90919. * @param result The quaternion that the rotation should be copied to
  90920. */
  90921. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  90922. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90923. if (mesh === void 0) { mesh = null; }
  90924. if (space == BABYLON.Space.LOCAL) {
  90925. this._decompose();
  90926. result.copyFrom(this._localRotation);
  90927. }
  90928. else {
  90929. var mat = Bone._tmpMats[0];
  90930. var amat = this.getAbsoluteTransform();
  90931. if (mesh) {
  90932. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90933. }
  90934. else {
  90935. mat.copyFrom(amat);
  90936. }
  90937. mat.m[0] *= this._scalingDeterminant;
  90938. mat.m[1] *= this._scalingDeterminant;
  90939. mat.m[2] *= this._scalingDeterminant;
  90940. mat.decompose(undefined, result, undefined);
  90941. }
  90942. };
  90943. /**
  90944. * Get the rotation matrix of the bone in local or world space
  90945. * @param space The space that the rotation should be in
  90946. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90947. * @returns The rotation matrix
  90948. */
  90949. Bone.prototype.getRotationMatrix = function (space, mesh) {
  90950. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90951. var result = BABYLON.Matrix.Identity();
  90952. this.getRotationMatrixToRef(space, mesh, result);
  90953. return result;
  90954. };
  90955. /**
  90956. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  90957. * @param space The space that the rotation should be in
  90958. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90959. * @param result The quaternion that the rotation should be copied to
  90960. */
  90961. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  90962. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90963. if (space == BABYLON.Space.LOCAL) {
  90964. this.getLocalMatrix().getRotationMatrixToRef(result);
  90965. }
  90966. else {
  90967. var mat = Bone._tmpMats[0];
  90968. var amat = this.getAbsoluteTransform();
  90969. if (mesh) {
  90970. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90971. }
  90972. else {
  90973. mat.copyFrom(amat);
  90974. }
  90975. mat.m[0] *= this._scalingDeterminant;
  90976. mat.m[1] *= this._scalingDeterminant;
  90977. mat.m[2] *= this._scalingDeterminant;
  90978. mat.getRotationMatrixToRef(result);
  90979. }
  90980. };
  90981. /**
  90982. * Get the world position of a point that is in the local space of the bone
  90983. * @param position The local position
  90984. * @param mesh The mesh that this bone is attached to
  90985. * @returns The world position
  90986. */
  90987. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  90988. if (mesh === void 0) { mesh = null; }
  90989. var result = BABYLON.Vector3.Zero();
  90990. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  90991. return result;
  90992. };
  90993. /**
  90994. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  90995. * @param position The local position
  90996. * @param mesh The mesh that this bone is attached to
  90997. * @param result The vector3 that the world position should be copied to
  90998. */
  90999. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  91000. if (mesh === void 0) { mesh = null; }
  91001. var wm = null;
  91002. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91003. if (mesh) {
  91004. wm = mesh.getWorldMatrix();
  91005. }
  91006. this._skeleton.computeAbsoluteTransforms();
  91007. var tmat = Bone._tmpMats[0];
  91008. if (mesh && wm) {
  91009. tmat.copyFrom(this.getAbsoluteTransform());
  91010. tmat.multiplyToRef(wm, tmat);
  91011. }
  91012. else {
  91013. tmat = this.getAbsoluteTransform();
  91014. }
  91015. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  91016. };
  91017. /**
  91018. * Get the local position of a point that is in world space
  91019. * @param position The world position
  91020. * @param mesh The mesh that this bone is attached to
  91021. * @returns The local position
  91022. */
  91023. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  91024. if (mesh === void 0) { mesh = null; }
  91025. var result = BABYLON.Vector3.Zero();
  91026. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  91027. return result;
  91028. };
  91029. /**
  91030. * Get the local position of a point that is in world space and copy it to the result param
  91031. * @param position The world position
  91032. * @param mesh The mesh that this bone is attached to
  91033. * @param result The vector3 that the local position should be copied to
  91034. */
  91035. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  91036. if (mesh === void 0) { mesh = null; }
  91037. var wm = null;
  91038. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91039. if (mesh) {
  91040. wm = mesh.getWorldMatrix();
  91041. }
  91042. this._skeleton.computeAbsoluteTransforms();
  91043. var tmat = Bone._tmpMats[0];
  91044. tmat.copyFrom(this.getAbsoluteTransform());
  91045. if (mesh && wm) {
  91046. tmat.multiplyToRef(wm, tmat);
  91047. }
  91048. tmat.invert();
  91049. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  91050. };
  91051. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91052. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  91053. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91054. return Bone;
  91055. }(BABYLON.Node));
  91056. BABYLON.Bone = Bone;
  91057. })(BABYLON || (BABYLON = {}));
  91058. //# sourceMappingURL=babylon.bone.js.map
  91059. var BABYLON;
  91060. (function (BABYLON) {
  91061. /**
  91062. * Class used to apply inverse kinematics to bones
  91063. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  91064. */
  91065. var BoneIKController = /** @class */ (function () {
  91066. /**
  91067. * Creates a new BoneIKController
  91068. * @param mesh defines the mesh to control
  91069. * @param bone defines the bone to control
  91070. * @param options defines options to set up the controller
  91071. */
  91072. function BoneIKController(mesh, bone, options) {
  91073. /**
  91074. * Gets or sets the target position
  91075. */
  91076. this.targetPosition = BABYLON.Vector3.Zero();
  91077. /**
  91078. * Gets or sets the pole target position
  91079. */
  91080. this.poleTargetPosition = BABYLON.Vector3.Zero();
  91081. /**
  91082. * Gets or sets the pole target local offset
  91083. */
  91084. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  91085. /**
  91086. * Gets or sets the pole angle
  91087. */
  91088. this.poleAngle = 0;
  91089. /**
  91090. * 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)
  91091. */
  91092. this.slerpAmount = 1;
  91093. this._bone1Quat = BABYLON.Quaternion.Identity();
  91094. this._bone1Mat = BABYLON.Matrix.Identity();
  91095. this._bone2Ang = Math.PI;
  91096. this._maxAngle = Math.PI;
  91097. this._rightHandedSystem = false;
  91098. this._bendAxis = BABYLON.Vector3.Right();
  91099. this._slerping = false;
  91100. this._adjustRoll = 0;
  91101. this._bone2 = bone;
  91102. this._bone1 = bone.getParent();
  91103. if (!this._bone1) {
  91104. return;
  91105. }
  91106. this.mesh = mesh;
  91107. var bonePos = bone.getPosition();
  91108. if (bone.getAbsoluteTransform().determinant() > 0) {
  91109. this._rightHandedSystem = true;
  91110. this._bendAxis.x = 0;
  91111. this._bendAxis.y = 0;
  91112. this._bendAxis.z = -1;
  91113. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  91114. this._adjustRoll = Math.PI * .5;
  91115. this._bendAxis.z = 1;
  91116. }
  91117. }
  91118. if (this._bone1.length) {
  91119. var boneScale1 = this._bone1.getScale();
  91120. var boneScale2 = this._bone2.getScale();
  91121. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  91122. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  91123. }
  91124. else if (this._bone1.children[0]) {
  91125. mesh.computeWorldMatrix(true);
  91126. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  91127. var pos2 = this._bone2.getAbsolutePosition(mesh);
  91128. var pos3 = this._bone1.getAbsolutePosition(mesh);
  91129. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  91130. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  91131. }
  91132. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  91133. this.maxAngle = Math.PI;
  91134. if (options) {
  91135. if (options.targetMesh) {
  91136. this.targetMesh = options.targetMesh;
  91137. this.targetMesh.computeWorldMatrix(true);
  91138. }
  91139. if (options.poleTargetMesh) {
  91140. this.poleTargetMesh = options.poleTargetMesh;
  91141. this.poleTargetMesh.computeWorldMatrix(true);
  91142. }
  91143. else if (options.poleTargetBone) {
  91144. this.poleTargetBone = options.poleTargetBone;
  91145. }
  91146. else if (this._bone1.getParent()) {
  91147. this.poleTargetBone = this._bone1.getParent();
  91148. }
  91149. if (options.poleTargetLocalOffset) {
  91150. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  91151. }
  91152. if (options.poleAngle) {
  91153. this.poleAngle = options.poleAngle;
  91154. }
  91155. if (options.bendAxis) {
  91156. this._bendAxis.copyFrom(options.bendAxis);
  91157. }
  91158. if (options.maxAngle) {
  91159. this.maxAngle = options.maxAngle;
  91160. }
  91161. if (options.slerpAmount) {
  91162. this.slerpAmount = options.slerpAmount;
  91163. }
  91164. }
  91165. }
  91166. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  91167. /**
  91168. * Gets or sets maximum allowed angle
  91169. */
  91170. get: function () {
  91171. return this._maxAngle;
  91172. },
  91173. set: function (value) {
  91174. this._setMaxAngle(value);
  91175. },
  91176. enumerable: true,
  91177. configurable: true
  91178. });
  91179. BoneIKController.prototype._setMaxAngle = function (ang) {
  91180. if (ang < 0) {
  91181. ang = 0;
  91182. }
  91183. if (ang > Math.PI || ang == undefined) {
  91184. ang = Math.PI;
  91185. }
  91186. this._maxAngle = ang;
  91187. var a = this._bone1Length;
  91188. var b = this._bone2Length;
  91189. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  91190. };
  91191. /**
  91192. * Force the controller to update the bones
  91193. */
  91194. BoneIKController.prototype.update = function () {
  91195. var bone1 = this._bone1;
  91196. if (!bone1) {
  91197. return;
  91198. }
  91199. var target = this.targetPosition;
  91200. var poleTarget = this.poleTargetPosition;
  91201. var mat1 = BoneIKController._tmpMats[0];
  91202. var mat2 = BoneIKController._tmpMats[1];
  91203. if (this.targetMesh) {
  91204. target.copyFrom(this.targetMesh.getAbsolutePosition());
  91205. }
  91206. if (this.poleTargetBone) {
  91207. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  91208. }
  91209. else if (this.poleTargetMesh) {
  91210. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  91211. }
  91212. var bonePos = BoneIKController._tmpVecs[0];
  91213. var zaxis = BoneIKController._tmpVecs[1];
  91214. var xaxis = BoneIKController._tmpVecs[2];
  91215. var yaxis = BoneIKController._tmpVecs[3];
  91216. var upAxis = BoneIKController._tmpVecs[4];
  91217. var _tmpQuat = BoneIKController._tmpQuat;
  91218. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  91219. poleTarget.subtractToRef(bonePos, upAxis);
  91220. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  91221. upAxis.y = 1;
  91222. }
  91223. else {
  91224. upAxis.normalize();
  91225. }
  91226. target.subtractToRef(bonePos, yaxis);
  91227. yaxis.normalize();
  91228. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  91229. zaxis.normalize();
  91230. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  91231. xaxis.normalize();
  91232. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  91233. var a = this._bone1Length;
  91234. var b = this._bone2Length;
  91235. var c = BABYLON.Vector3.Distance(bonePos, target);
  91236. if (this._maxReach > 0) {
  91237. c = Math.min(this._maxReach, c);
  91238. }
  91239. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  91240. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  91241. if (acosa > 1) {
  91242. acosa = 1;
  91243. }
  91244. if (acosb > 1) {
  91245. acosb = 1;
  91246. }
  91247. if (acosa < -1) {
  91248. acosa = -1;
  91249. }
  91250. if (acosb < -1) {
  91251. acosb = -1;
  91252. }
  91253. var angA = Math.acos(acosa);
  91254. var angB = Math.acos(acosb);
  91255. var angC = -angA - angB;
  91256. if (this._rightHandedSystem) {
  91257. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  91258. mat2.multiplyToRef(mat1, mat1);
  91259. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  91260. mat2.multiplyToRef(mat1, mat1);
  91261. }
  91262. else {
  91263. var _tmpVec = BoneIKController._tmpVecs[5];
  91264. _tmpVec.copyFrom(this._bendAxis);
  91265. _tmpVec.x *= -1;
  91266. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  91267. mat2.multiplyToRef(mat1, mat1);
  91268. }
  91269. if (this.poleAngle) {
  91270. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  91271. mat1.multiplyToRef(mat2, mat1);
  91272. }
  91273. if (this._bone1) {
  91274. if (this.slerpAmount < 1) {
  91275. if (!this._slerping) {
  91276. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  91277. }
  91278. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  91279. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  91280. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  91281. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  91282. this._slerping = true;
  91283. }
  91284. else {
  91285. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  91286. this._bone1Mat.copyFrom(mat1);
  91287. this._slerping = false;
  91288. }
  91289. }
  91290. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  91291. this._bone2Ang = angC;
  91292. };
  91293. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91294. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  91295. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91296. return BoneIKController;
  91297. }());
  91298. BABYLON.BoneIKController = BoneIKController;
  91299. })(BABYLON || (BABYLON = {}));
  91300. //# sourceMappingURL=babylon.boneIKController.js.map
  91301. var BABYLON;
  91302. (function (BABYLON) {
  91303. /**
  91304. * Class used to make a bone look toward a point in space
  91305. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  91306. */
  91307. var BoneLookController = /** @class */ (function () {
  91308. /**
  91309. * Create a BoneLookController
  91310. * @param mesh the mesh that the bone belongs to
  91311. * @param bone the bone that will be looking to the target
  91312. * @param target the target Vector3 to look at
  91313. * @param settings optional settings:
  91314. * * maxYaw: the maximum angle the bone will yaw to
  91315. * * minYaw: the minimum angle the bone will yaw to
  91316. * * maxPitch: the maximum angle the bone will pitch to
  91317. * * minPitch: the minimum angle the bone will yaw to
  91318. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  91319. * * upAxis: the up axis of the coordinate system
  91320. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  91321. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  91322. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  91323. * * adjustYaw: used to make an adjustment to the yaw of the bone
  91324. * * adjustPitch: used to make an adjustment to the pitch of the bone
  91325. * * adjustRoll: used to make an adjustment to the roll of the bone
  91326. **/
  91327. function BoneLookController(mesh, bone, target, options) {
  91328. /**
  91329. * The up axis of the coordinate system that is used when the bone is rotated
  91330. */
  91331. this.upAxis = BABYLON.Vector3.Up();
  91332. /**
  91333. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  91334. */
  91335. this.upAxisSpace = BABYLON.Space.LOCAL;
  91336. /**
  91337. * Used to make an adjustment to the yaw of the bone
  91338. */
  91339. this.adjustYaw = 0;
  91340. /**
  91341. * Used to make an adjustment to the pitch of the bone
  91342. */
  91343. this.adjustPitch = 0;
  91344. /**
  91345. * Used to make an adjustment to the roll of the bone
  91346. */
  91347. this.adjustRoll = 0;
  91348. /**
  91349. * 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)
  91350. */
  91351. this.slerpAmount = 1;
  91352. this._boneQuat = BABYLON.Quaternion.Identity();
  91353. this._slerping = false;
  91354. this._firstFrameSkipped = false;
  91355. this._fowardAxis = BABYLON.Vector3.Forward();
  91356. this.mesh = mesh;
  91357. this.bone = bone;
  91358. this.target = target;
  91359. if (options) {
  91360. if (options.adjustYaw) {
  91361. this.adjustYaw = options.adjustYaw;
  91362. }
  91363. if (options.adjustPitch) {
  91364. this.adjustPitch = options.adjustPitch;
  91365. }
  91366. if (options.adjustRoll) {
  91367. this.adjustRoll = options.adjustRoll;
  91368. }
  91369. if (options.maxYaw != null) {
  91370. this.maxYaw = options.maxYaw;
  91371. }
  91372. else {
  91373. this.maxYaw = Math.PI;
  91374. }
  91375. if (options.minYaw != null) {
  91376. this.minYaw = options.minYaw;
  91377. }
  91378. else {
  91379. this.minYaw = -Math.PI;
  91380. }
  91381. if (options.maxPitch != null) {
  91382. this.maxPitch = options.maxPitch;
  91383. }
  91384. else {
  91385. this.maxPitch = Math.PI;
  91386. }
  91387. if (options.minPitch != null) {
  91388. this.minPitch = options.minPitch;
  91389. }
  91390. else {
  91391. this.minPitch = -Math.PI;
  91392. }
  91393. if (options.slerpAmount != null) {
  91394. this.slerpAmount = options.slerpAmount;
  91395. }
  91396. if (options.upAxis != null) {
  91397. this.upAxis = options.upAxis;
  91398. }
  91399. if (options.upAxisSpace != null) {
  91400. this.upAxisSpace = options.upAxisSpace;
  91401. }
  91402. if (options.yawAxis != null || options.pitchAxis != null) {
  91403. var newYawAxis = BABYLON.Axis.Y;
  91404. var newPitchAxis = BABYLON.Axis.X;
  91405. if (options.yawAxis != null) {
  91406. newYawAxis = options.yawAxis.clone();
  91407. newYawAxis.normalize();
  91408. }
  91409. if (options.pitchAxis != null) {
  91410. newPitchAxis = options.pitchAxis.clone();
  91411. newPitchAxis.normalize();
  91412. }
  91413. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  91414. this._transformYawPitch = BABYLON.Matrix.Identity();
  91415. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  91416. this._transformYawPitchInv = this._transformYawPitch.clone();
  91417. this._transformYawPitch.invert();
  91418. }
  91419. }
  91420. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  91421. this.upAxisSpace = BABYLON.Space.LOCAL;
  91422. }
  91423. }
  91424. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  91425. /**
  91426. * Gets or sets the minimum yaw angle that the bone can look to
  91427. */
  91428. get: function () {
  91429. return this._minYaw;
  91430. },
  91431. set: function (value) {
  91432. this._minYaw = value;
  91433. this._minYawSin = Math.sin(value);
  91434. this._minYawCos = Math.cos(value);
  91435. if (this._maxYaw != null) {
  91436. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91437. this._yawRange = this._maxYaw - this._minYaw;
  91438. }
  91439. },
  91440. enumerable: true,
  91441. configurable: true
  91442. });
  91443. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  91444. /**
  91445. * Gets or sets the maximum yaw angle that the bone can look to
  91446. */
  91447. get: function () {
  91448. return this._maxYaw;
  91449. },
  91450. set: function (value) {
  91451. this._maxYaw = value;
  91452. this._maxYawSin = Math.sin(value);
  91453. this._maxYawCos = Math.cos(value);
  91454. if (this._minYaw != null) {
  91455. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91456. this._yawRange = this._maxYaw - this._minYaw;
  91457. }
  91458. },
  91459. enumerable: true,
  91460. configurable: true
  91461. });
  91462. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  91463. /**
  91464. * Gets or sets the minimum pitch angle that the bone can look to
  91465. */
  91466. get: function () {
  91467. return this._minPitch;
  91468. },
  91469. set: function (value) {
  91470. this._minPitch = value;
  91471. this._minPitchTan = Math.tan(value);
  91472. },
  91473. enumerable: true,
  91474. configurable: true
  91475. });
  91476. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  91477. /**
  91478. * Gets or sets the maximum pitch angle that the bone can look to
  91479. */
  91480. get: function () {
  91481. return this._maxPitch;
  91482. },
  91483. set: function (value) {
  91484. this._maxPitch = value;
  91485. this._maxPitchTan = Math.tan(value);
  91486. },
  91487. enumerable: true,
  91488. configurable: true
  91489. });
  91490. /**
  91491. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  91492. */
  91493. BoneLookController.prototype.update = function () {
  91494. //skip the first frame when slerping so that the mesh rotation is correct
  91495. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  91496. this._firstFrameSkipped = true;
  91497. return;
  91498. }
  91499. var bone = this.bone;
  91500. var bonePos = BoneLookController._tmpVecs[0];
  91501. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  91502. var target = this.target;
  91503. var _tmpMat1 = BoneLookController._tmpMats[0];
  91504. var _tmpMat2 = BoneLookController._tmpMats[1];
  91505. var mesh = this.mesh;
  91506. var parentBone = bone.getParent();
  91507. var upAxis = BoneLookController._tmpVecs[1];
  91508. upAxis.copyFrom(this.upAxis);
  91509. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  91510. if (this._transformYawPitch) {
  91511. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  91512. }
  91513. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  91514. }
  91515. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  91516. mesh.getDirectionToRef(upAxis, upAxis);
  91517. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  91518. upAxis.normalize();
  91519. }
  91520. }
  91521. var checkYaw = false;
  91522. var checkPitch = false;
  91523. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  91524. checkYaw = true;
  91525. }
  91526. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  91527. checkPitch = true;
  91528. }
  91529. if (checkYaw || checkPitch) {
  91530. var spaceMat = BoneLookController._tmpMats[2];
  91531. var spaceMatInv = BoneLookController._tmpMats[3];
  91532. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  91533. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  91534. }
  91535. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  91536. spaceMat.copyFrom(mesh.getWorldMatrix());
  91537. }
  91538. else {
  91539. var forwardAxis = BoneLookController._tmpVecs[2];
  91540. forwardAxis.copyFrom(this._fowardAxis);
  91541. if (this._transformYawPitch) {
  91542. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  91543. }
  91544. if (parentBone) {
  91545. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  91546. }
  91547. else {
  91548. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  91549. }
  91550. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  91551. rightAxis.normalize();
  91552. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  91553. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  91554. }
  91555. spaceMat.invertToRef(spaceMatInv);
  91556. var xzlen = null;
  91557. if (checkPitch) {
  91558. var localTarget = BoneLookController._tmpVecs[3];
  91559. target.subtractToRef(bonePos, localTarget);
  91560. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91561. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91562. var pitch = Math.atan2(localTarget.y, xzlen);
  91563. var newPitch = pitch;
  91564. if (pitch > this._maxPitch) {
  91565. localTarget.y = this._maxPitchTan * xzlen;
  91566. newPitch = this._maxPitch;
  91567. }
  91568. else if (pitch < this._minPitch) {
  91569. localTarget.y = this._minPitchTan * xzlen;
  91570. newPitch = this._minPitch;
  91571. }
  91572. if (pitch != newPitch) {
  91573. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91574. localTarget.addInPlace(bonePos);
  91575. target = localTarget;
  91576. }
  91577. }
  91578. if (checkYaw) {
  91579. var localTarget = BoneLookController._tmpVecs[4];
  91580. target.subtractToRef(bonePos, localTarget);
  91581. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91582. var yaw = Math.atan2(localTarget.x, localTarget.z);
  91583. var newYaw = yaw;
  91584. if (yaw > this._maxYaw || yaw < this._minYaw) {
  91585. if (xzlen == null) {
  91586. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91587. }
  91588. if (this._yawRange > Math.PI) {
  91589. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  91590. localTarget.z = this._maxYawCos * xzlen;
  91591. localTarget.x = this._maxYawSin * xzlen;
  91592. newYaw = this._maxYaw;
  91593. }
  91594. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  91595. localTarget.z = this._minYawCos * xzlen;
  91596. localTarget.x = this._minYawSin * xzlen;
  91597. newYaw = this._minYaw;
  91598. }
  91599. }
  91600. else {
  91601. if (yaw > this._maxYaw) {
  91602. localTarget.z = this._maxYawCos * xzlen;
  91603. localTarget.x = this._maxYawSin * xzlen;
  91604. newYaw = this._maxYaw;
  91605. }
  91606. else if (yaw < this._minYaw) {
  91607. localTarget.z = this._minYawCos * xzlen;
  91608. localTarget.x = this._minYawSin * xzlen;
  91609. newYaw = this._minYaw;
  91610. }
  91611. }
  91612. }
  91613. if (this._slerping && this._yawRange > Math.PI) {
  91614. //are we going to be crossing into the min/max region?
  91615. var boneFwd = BoneLookController._tmpVecs[8];
  91616. boneFwd.copyFrom(BABYLON.Axis.Z);
  91617. if (this._transformYawPitch) {
  91618. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  91619. }
  91620. var boneRotMat = BoneLookController._tmpMats[4];
  91621. this._boneQuat.toRotationMatrix(boneRotMat);
  91622. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  91623. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  91624. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  91625. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  91626. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  91627. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  91628. if (angBtwTar > angBtwMidYaw) {
  91629. if (xzlen == null) {
  91630. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91631. }
  91632. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  91633. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  91634. if (angBtwMin < angBtwMax) {
  91635. newYaw = boneYaw + Math.PI * .75;
  91636. localTarget.z = Math.cos(newYaw) * xzlen;
  91637. localTarget.x = Math.sin(newYaw) * xzlen;
  91638. }
  91639. else {
  91640. newYaw = boneYaw - Math.PI * .75;
  91641. localTarget.z = Math.cos(newYaw) * xzlen;
  91642. localTarget.x = Math.sin(newYaw) * xzlen;
  91643. }
  91644. }
  91645. }
  91646. if (yaw != newYaw) {
  91647. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91648. localTarget.addInPlace(bonePos);
  91649. target = localTarget;
  91650. }
  91651. }
  91652. }
  91653. var zaxis = BoneLookController._tmpVecs[5];
  91654. var xaxis = BoneLookController._tmpVecs[6];
  91655. var yaxis = BoneLookController._tmpVecs[7];
  91656. var _tmpQuat = BoneLookController._tmpQuat;
  91657. target.subtractToRef(bonePos, zaxis);
  91658. zaxis.normalize();
  91659. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  91660. xaxis.normalize();
  91661. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  91662. yaxis.normalize();
  91663. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  91664. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  91665. return;
  91666. }
  91667. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  91668. return;
  91669. }
  91670. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  91671. return;
  91672. }
  91673. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  91674. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  91675. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  91676. }
  91677. if (this.slerpAmount < 1) {
  91678. if (!this._slerping) {
  91679. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  91680. }
  91681. if (this._transformYawPitch) {
  91682. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91683. }
  91684. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  91685. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  91686. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  91687. this._slerping = true;
  91688. }
  91689. else {
  91690. if (this._transformYawPitch) {
  91691. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91692. }
  91693. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  91694. this._slerping = false;
  91695. }
  91696. };
  91697. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  91698. var angDiff = ang2 - ang1;
  91699. angDiff %= Math.PI * 2;
  91700. if (angDiff > Math.PI) {
  91701. angDiff -= Math.PI * 2;
  91702. }
  91703. else if (angDiff < -Math.PI) {
  91704. angDiff += Math.PI * 2;
  91705. }
  91706. return angDiff;
  91707. };
  91708. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  91709. ang1 %= (2 * Math.PI);
  91710. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91711. ang2 %= (2 * Math.PI);
  91712. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91713. var ab = 0;
  91714. if (ang1 < ang2) {
  91715. ab = ang2 - ang1;
  91716. }
  91717. else {
  91718. ab = ang1 - ang2;
  91719. }
  91720. if (ab > Math.PI) {
  91721. ab = Math.PI * 2 - ab;
  91722. }
  91723. return ab;
  91724. };
  91725. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  91726. ang %= (2 * Math.PI);
  91727. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  91728. ang1 %= (2 * Math.PI);
  91729. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91730. ang2 %= (2 * Math.PI);
  91731. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91732. if (ang1 < ang2) {
  91733. if (ang > ang1 && ang < ang2) {
  91734. return true;
  91735. }
  91736. }
  91737. else {
  91738. if (ang > ang2 && ang < ang1) {
  91739. return true;
  91740. }
  91741. }
  91742. return false;
  91743. };
  91744. 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()];
  91745. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  91746. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91747. return BoneLookController;
  91748. }());
  91749. BABYLON.BoneLookController = BoneLookController;
  91750. })(BABYLON || (BABYLON = {}));
  91751. //# sourceMappingURL=babylon.boneLookController.js.map
  91752. var BABYLON;
  91753. (function (BABYLON) {
  91754. /**
  91755. * Class used to handle skinning animations
  91756. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91757. */
  91758. var Skeleton = /** @class */ (function () {
  91759. /**
  91760. * Creates a new skeleton
  91761. * @param name defines the skeleton name
  91762. * @param id defines the skeleton Id
  91763. * @param scene defines the hosting scene
  91764. */
  91765. function Skeleton(
  91766. /** defines the skeleton name */
  91767. name,
  91768. /** defines the skeleton Id */
  91769. id, scene) {
  91770. this.name = name;
  91771. this.id = id;
  91772. /**
  91773. * Gets the list of child bones
  91774. */
  91775. this.bones = new Array();
  91776. /**
  91777. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  91778. */
  91779. this.needInitialSkinMatrix = false;
  91780. this._isDirty = true;
  91781. this._meshesWithPoseMatrix = new Array();
  91782. this._identity = BABYLON.Matrix.Identity();
  91783. this._ranges = {};
  91784. this._lastAbsoluteTransformsUpdateId = -1;
  91785. /**
  91786. * Specifies if the skeleton should be serialized
  91787. */
  91788. this.doNotSerialize = false;
  91789. this._animationPropertiesOverride = null;
  91790. // Events
  91791. /**
  91792. * An observable triggered before computing the skeleton's matrices
  91793. */
  91794. this.onBeforeComputeObservable = new BABYLON.Observable();
  91795. this.bones = [];
  91796. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91797. scene.skeletons.push(this);
  91798. //make sure it will recalculate the matrix next time prepare is called.
  91799. this._isDirty = true;
  91800. }
  91801. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  91802. /**
  91803. * Gets or sets the animation properties override
  91804. */
  91805. get: function () {
  91806. if (!this._animationPropertiesOverride) {
  91807. return this._scene.animationPropertiesOverride;
  91808. }
  91809. return this._animationPropertiesOverride;
  91810. },
  91811. set: function (value) {
  91812. this._animationPropertiesOverride = value;
  91813. },
  91814. enumerable: true,
  91815. configurable: true
  91816. });
  91817. // Members
  91818. /**
  91819. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  91820. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  91821. * @returns a Float32Array containing matrices data
  91822. */
  91823. Skeleton.prototype.getTransformMatrices = function (mesh) {
  91824. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  91825. return mesh._bonesTransformMatrices;
  91826. }
  91827. if (!this._transformMatrices) {
  91828. this.prepare();
  91829. }
  91830. return this._transformMatrices;
  91831. };
  91832. /**
  91833. * Gets the current hosting scene
  91834. * @returns a scene object
  91835. */
  91836. Skeleton.prototype.getScene = function () {
  91837. return this._scene;
  91838. };
  91839. // Methods
  91840. /**
  91841. * Gets a string representing the current skeleton data
  91842. * @param fullDetails defines a boolean indicating if we want a verbose version
  91843. * @returns a string representing the current skeleton data
  91844. */
  91845. Skeleton.prototype.toString = function (fullDetails) {
  91846. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  91847. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  91848. if (fullDetails) {
  91849. ret += ", Ranges: {";
  91850. var first = true;
  91851. for (var name_1 in this._ranges) {
  91852. if (first) {
  91853. ret += ", ";
  91854. first = false;
  91855. }
  91856. ret += name_1;
  91857. }
  91858. ret += "}";
  91859. }
  91860. return ret;
  91861. };
  91862. /**
  91863. * Get bone's index searching by name
  91864. * @param name defines bone's name to search for
  91865. * @return the indice of the bone. Returns -1 if not found
  91866. */
  91867. Skeleton.prototype.getBoneIndexByName = function (name) {
  91868. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  91869. if (this.bones[boneIndex].name === name) {
  91870. return boneIndex;
  91871. }
  91872. }
  91873. return -1;
  91874. };
  91875. /**
  91876. * Creater a new animation range
  91877. * @param name defines the name of the range
  91878. * @param from defines the start key
  91879. * @param to defines the end key
  91880. */
  91881. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  91882. // check name not already in use
  91883. if (!this._ranges[name]) {
  91884. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  91885. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91886. if (this.bones[i].animations[0]) {
  91887. this.bones[i].animations[0].createRange(name, from, to);
  91888. }
  91889. }
  91890. }
  91891. };
  91892. /**
  91893. * Delete a specific animation range
  91894. * @param name defines the name of the range
  91895. * @param deleteFrames defines if frames must be removed as well
  91896. */
  91897. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  91898. if (deleteFrames === void 0) { deleteFrames = true; }
  91899. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91900. if (this.bones[i].animations[0]) {
  91901. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  91902. }
  91903. }
  91904. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  91905. };
  91906. /**
  91907. * Gets a specific animation range
  91908. * @param name defines the name of the range to look for
  91909. * @returns the requested animation range or null if not found
  91910. */
  91911. Skeleton.prototype.getAnimationRange = function (name) {
  91912. return this._ranges[name];
  91913. };
  91914. /**
  91915. * Gets the list of all animation ranges defined on this skeleton
  91916. * @returns an array
  91917. */
  91918. Skeleton.prototype.getAnimationRanges = function () {
  91919. var animationRanges = [];
  91920. var name;
  91921. var i = 0;
  91922. for (name in this._ranges) {
  91923. animationRanges[i] = this._ranges[name];
  91924. i++;
  91925. }
  91926. return animationRanges;
  91927. };
  91928. /**
  91929. * Copy animation range from a source skeleton.
  91930. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  91931. * @param source defines the source skeleton
  91932. * @param name defines the name of the range to copy
  91933. * @param rescaleAsRequired defines if rescaling must be applied if required
  91934. * @returns true if operation was successful
  91935. */
  91936. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  91937. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91938. if (this._ranges[name] || !source.getAnimationRange(name)) {
  91939. return false;
  91940. }
  91941. var ret = true;
  91942. var frameOffset = this._getHighestAnimationFrame() + 1;
  91943. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  91944. var boneDict = {};
  91945. var sourceBones = source.bones;
  91946. var nBones;
  91947. var i;
  91948. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  91949. boneDict[sourceBones[i].name] = sourceBones[i];
  91950. }
  91951. if (this.bones.length !== sourceBones.length) {
  91952. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  91953. ret = false;
  91954. }
  91955. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  91956. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  91957. var boneName = this.bones[i].name;
  91958. var sourceBone = boneDict[boneName];
  91959. if (sourceBone) {
  91960. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  91961. }
  91962. else {
  91963. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  91964. ret = false;
  91965. }
  91966. }
  91967. // do not call createAnimationRange(), since it also is done to bones, which was already done
  91968. var range = source.getAnimationRange(name);
  91969. if (range) {
  91970. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  91971. }
  91972. return ret;
  91973. };
  91974. /**
  91975. * Forces the skeleton to go to rest pose
  91976. */
  91977. Skeleton.prototype.returnToRest = function () {
  91978. for (var index = 0; index < this.bones.length; index++) {
  91979. this.bones[index].returnToRest();
  91980. }
  91981. };
  91982. Skeleton.prototype._getHighestAnimationFrame = function () {
  91983. var ret = 0;
  91984. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91985. if (this.bones[i].animations[0]) {
  91986. var highest = this.bones[i].animations[0].getHighestFrame();
  91987. if (ret < highest) {
  91988. ret = highest;
  91989. }
  91990. }
  91991. }
  91992. return ret;
  91993. };
  91994. /**
  91995. * Begin a specific animation range
  91996. * @param name defines the name of the range to start
  91997. * @param loop defines if looping must be turned on (false by default)
  91998. * @param speedRatio defines the speed ratio to apply (1 by default)
  91999. * @param onAnimationEnd defines a callback which will be called when animation will end
  92000. * @returns a new animatable
  92001. */
  92002. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  92003. var range = this.getAnimationRange(name);
  92004. if (!range) {
  92005. return null;
  92006. }
  92007. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  92008. };
  92009. /** @hidden */
  92010. Skeleton.prototype._markAsDirty = function () {
  92011. this._isDirty = true;
  92012. };
  92013. /** @hidden */
  92014. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  92015. this._meshesWithPoseMatrix.push(mesh);
  92016. };
  92017. /** @hidden */
  92018. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  92019. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  92020. if (index > -1) {
  92021. this._meshesWithPoseMatrix.splice(index, 1);
  92022. }
  92023. };
  92024. /** @hidden */
  92025. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  92026. this.onBeforeComputeObservable.notifyObservers(this);
  92027. for (var index = 0; index < this.bones.length; index++) {
  92028. var bone = this.bones[index];
  92029. var parentBone = bone.getParent();
  92030. if (parentBone) {
  92031. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  92032. }
  92033. else {
  92034. if (initialSkinMatrix) {
  92035. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  92036. }
  92037. else {
  92038. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  92039. }
  92040. }
  92041. if (bone._index !== -1) {
  92042. var mappedIndex = bone._index === null ? index : bone._index;
  92043. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  92044. }
  92045. }
  92046. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  92047. };
  92048. /**
  92049. * Build all resources required to render a skeleton
  92050. */
  92051. Skeleton.prototype.prepare = function () {
  92052. if (!this._isDirty) {
  92053. return;
  92054. }
  92055. if (this.needInitialSkinMatrix) {
  92056. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  92057. var mesh = this._meshesWithPoseMatrix[index];
  92058. var poseMatrix = mesh.getPoseMatrix();
  92059. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  92060. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  92061. }
  92062. if (this._synchronizedWithMesh !== mesh) {
  92063. this._synchronizedWithMesh = mesh;
  92064. // Prepare bones
  92065. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  92066. var bone = this.bones[boneIndex];
  92067. if (!bone.getParent()) {
  92068. var matrix = bone.getBaseMatrix();
  92069. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  92070. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  92071. }
  92072. }
  92073. }
  92074. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  92075. }
  92076. }
  92077. else {
  92078. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  92079. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  92080. }
  92081. this._computeTransformMatrices(this._transformMatrices, null);
  92082. }
  92083. this._isDirty = false;
  92084. this._scene._activeBones.addCount(this.bones.length, false);
  92085. };
  92086. /**
  92087. * Gets the list of animatables currently running for this skeleton
  92088. * @returns an array of animatables
  92089. */
  92090. Skeleton.prototype.getAnimatables = function () {
  92091. if (!this._animatables || this._animatables.length !== this.bones.length) {
  92092. this._animatables = [];
  92093. for (var index = 0; index < this.bones.length; index++) {
  92094. this._animatables.push(this.bones[index]);
  92095. }
  92096. }
  92097. return this._animatables;
  92098. };
  92099. /**
  92100. * Clone the current skeleton
  92101. * @param name defines the name of the new skeleton
  92102. * @param id defines the id of the enw skeleton
  92103. * @returns the new skeleton
  92104. */
  92105. Skeleton.prototype.clone = function (name, id) {
  92106. var result = new Skeleton(name, id || name, this._scene);
  92107. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  92108. for (var index = 0; index < this.bones.length; index++) {
  92109. var source = this.bones[index];
  92110. var parentBone = null;
  92111. var parent_1 = source.getParent();
  92112. if (parent_1) {
  92113. var parentIndex = this.bones.indexOf(parent_1);
  92114. parentBone = result.bones[parentIndex];
  92115. }
  92116. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  92117. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  92118. }
  92119. if (this._ranges) {
  92120. result._ranges = {};
  92121. for (var rangeName in this._ranges) {
  92122. var range = this._ranges[rangeName];
  92123. if (range) {
  92124. result._ranges[rangeName] = range.clone();
  92125. }
  92126. }
  92127. }
  92128. this._isDirty = true;
  92129. return result;
  92130. };
  92131. /**
  92132. * Enable animation blending for this skeleton
  92133. * @param blendingSpeed defines the blending speed to apply
  92134. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  92135. */
  92136. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  92137. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  92138. this.bones.forEach(function (bone) {
  92139. bone.animations.forEach(function (animation) {
  92140. animation.enableBlending = true;
  92141. animation.blendingSpeed = blendingSpeed;
  92142. });
  92143. });
  92144. };
  92145. /**
  92146. * Releases all resources associated with the current skeleton
  92147. */
  92148. Skeleton.prototype.dispose = function () {
  92149. this._meshesWithPoseMatrix = [];
  92150. // Animations
  92151. this.getScene().stopAnimation(this);
  92152. // Remove from scene
  92153. this.getScene().removeSkeleton(this);
  92154. };
  92155. /**
  92156. * Serialize the skeleton in a JSON object
  92157. * @returns a JSON object
  92158. */
  92159. Skeleton.prototype.serialize = function () {
  92160. var serializationObject = {};
  92161. serializationObject.name = this.name;
  92162. serializationObject.id = this.id;
  92163. if (this.dimensionsAtRest) {
  92164. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  92165. }
  92166. serializationObject.bones = [];
  92167. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  92168. for (var index = 0; index < this.bones.length; index++) {
  92169. var bone = this.bones[index];
  92170. var parent_2 = bone.getParent();
  92171. var serializedBone = {
  92172. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  92173. name: bone.name,
  92174. matrix: bone.getBaseMatrix().toArray(),
  92175. rest: bone.getRestPose().toArray()
  92176. };
  92177. serializationObject.bones.push(serializedBone);
  92178. if (bone.length) {
  92179. serializedBone.length = bone.length;
  92180. }
  92181. if (bone.metadata) {
  92182. serializedBone.metadata = bone.metadata;
  92183. }
  92184. if (bone.animations && bone.animations.length > 0) {
  92185. serializedBone.animation = bone.animations[0].serialize();
  92186. }
  92187. serializationObject.ranges = [];
  92188. for (var name in this._ranges) {
  92189. var source = this._ranges[name];
  92190. if (!source) {
  92191. continue;
  92192. }
  92193. var range = {};
  92194. range.name = name;
  92195. range.from = source.from;
  92196. range.to = source.to;
  92197. serializationObject.ranges.push(range);
  92198. }
  92199. }
  92200. return serializationObject;
  92201. };
  92202. /**
  92203. * Creates a new skeleton from serialized data
  92204. * @param parsedSkeleton defines the serialized data
  92205. * @param scene defines the hosting scene
  92206. * @returns a new skeleton
  92207. */
  92208. Skeleton.Parse = function (parsedSkeleton, scene) {
  92209. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  92210. if (parsedSkeleton.dimensionsAtRest) {
  92211. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  92212. }
  92213. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  92214. var index;
  92215. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  92216. var parsedBone = parsedSkeleton.bones[index];
  92217. var parentBone = null;
  92218. if (parsedBone.parentBoneIndex > -1) {
  92219. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  92220. }
  92221. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  92222. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  92223. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  92224. bone.id = parsedBone.id;
  92225. }
  92226. if (parsedBone.length) {
  92227. bone.length = parsedBone.length;
  92228. }
  92229. if (parsedBone.metadata) {
  92230. bone.metadata = parsedBone.metadata;
  92231. }
  92232. if (parsedBone.animation) {
  92233. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  92234. }
  92235. }
  92236. // placed after bones, so createAnimationRange can cascade down
  92237. if (parsedSkeleton.ranges) {
  92238. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  92239. var data = parsedSkeleton.ranges[index];
  92240. skeleton.createAnimationRange(data.name, data.from, data.to);
  92241. }
  92242. }
  92243. return skeleton;
  92244. };
  92245. /**
  92246. * Compute all node absolute transforms
  92247. * @param forceUpdate defines if computation must be done even if cache is up to date
  92248. */
  92249. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  92250. if (forceUpdate === void 0) { forceUpdate = false; }
  92251. var renderId = this._scene.getRenderId();
  92252. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  92253. this.bones[0].computeAbsoluteTransforms();
  92254. this._lastAbsoluteTransformsUpdateId = renderId;
  92255. }
  92256. };
  92257. /**
  92258. * Gets the root pose matrix
  92259. * @returns a matrix
  92260. */
  92261. Skeleton.prototype.getPoseMatrix = function () {
  92262. var poseMatrix = null;
  92263. if (this._meshesWithPoseMatrix.length > 0) {
  92264. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  92265. }
  92266. return poseMatrix;
  92267. };
  92268. /**
  92269. * Sorts bones per internal index
  92270. */
  92271. Skeleton.prototype.sortBones = function () {
  92272. var bones = new Array();
  92273. var visited = new Array(this.bones.length);
  92274. for (var index = 0; index < this.bones.length; index++) {
  92275. this._sortBones(index, bones, visited);
  92276. }
  92277. this.bones = bones;
  92278. };
  92279. Skeleton.prototype._sortBones = function (index, bones, visited) {
  92280. if (visited[index]) {
  92281. return;
  92282. }
  92283. visited[index] = true;
  92284. var bone = this.bones[index];
  92285. if (bone._index === undefined) {
  92286. bone._index = index;
  92287. }
  92288. var parentBone = bone.getParent();
  92289. if (parentBone) {
  92290. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  92291. }
  92292. bones.push(bone);
  92293. };
  92294. return Skeleton;
  92295. }());
  92296. BABYLON.Skeleton = Skeleton;
  92297. })(BABYLON || (BABYLON = {}));
  92298. //# sourceMappingURL=babylon.skeleton.js.map
  92299. var BABYLON;
  92300. (function (BABYLON) {
  92301. /**
  92302. * This groups tools to convert HDR texture to native colors array.
  92303. */
  92304. var HDRTools = /** @class */ (function () {
  92305. function HDRTools() {
  92306. }
  92307. HDRTools.Ldexp = function (mantissa, exponent) {
  92308. if (exponent > 1023) {
  92309. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  92310. }
  92311. if (exponent < -1074) {
  92312. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  92313. }
  92314. return mantissa * Math.pow(2, exponent);
  92315. };
  92316. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  92317. if (exponent > 0) { /*nonzero pixel*/
  92318. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  92319. float32array[index + 0] = red * exponent;
  92320. float32array[index + 1] = green * exponent;
  92321. float32array[index + 2] = blue * exponent;
  92322. }
  92323. else {
  92324. float32array[index + 0] = 0;
  92325. float32array[index + 1] = 0;
  92326. float32array[index + 2] = 0;
  92327. }
  92328. };
  92329. HDRTools.readStringLine = function (uint8array, startIndex) {
  92330. var line = "";
  92331. var character = "";
  92332. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  92333. character = String.fromCharCode(uint8array[i]);
  92334. if (character == "\n") {
  92335. break;
  92336. }
  92337. line += character;
  92338. }
  92339. return line;
  92340. };
  92341. /**
  92342. * Reads header information from an RGBE texture stored in a native array.
  92343. * More information on this format are available here:
  92344. * https://en.wikipedia.org/wiki/RGBE_image_format
  92345. *
  92346. * @param uint8array The binary file stored in native array.
  92347. * @return The header information.
  92348. */
  92349. HDRTools.RGBE_ReadHeader = function (uint8array) {
  92350. var height = 0;
  92351. var width = 0;
  92352. var line = this.readStringLine(uint8array, 0);
  92353. if (line[0] != '#' || line[1] != '?') {
  92354. throw "Bad HDR Format.";
  92355. }
  92356. var endOfHeader = false;
  92357. var findFormat = false;
  92358. var lineIndex = 0;
  92359. do {
  92360. lineIndex += (line.length + 1);
  92361. line = this.readStringLine(uint8array, lineIndex);
  92362. if (line == "FORMAT=32-bit_rle_rgbe") {
  92363. findFormat = true;
  92364. }
  92365. else if (line.length == 0) {
  92366. endOfHeader = true;
  92367. }
  92368. } while (!endOfHeader);
  92369. if (!findFormat) {
  92370. throw "HDR Bad header format, unsupported FORMAT";
  92371. }
  92372. lineIndex += (line.length + 1);
  92373. line = this.readStringLine(uint8array, lineIndex);
  92374. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  92375. var match = sizeRegexp.exec(line);
  92376. // TODO. Support +Y and -X if needed.
  92377. if (!match || match.length < 3) {
  92378. throw "HDR Bad header format, no size";
  92379. }
  92380. width = parseInt(match[2]);
  92381. height = parseInt(match[1]);
  92382. if (width < 8 || width > 0x7fff) {
  92383. throw "HDR Bad header format, unsupported size";
  92384. }
  92385. lineIndex += (line.length + 1);
  92386. return {
  92387. height: height,
  92388. width: width,
  92389. dataPosition: lineIndex
  92390. };
  92391. };
  92392. /**
  92393. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  92394. * This RGBE texture needs to store the information as a panorama.
  92395. *
  92396. * More information on this format are available here:
  92397. * https://en.wikipedia.org/wiki/RGBE_image_format
  92398. *
  92399. * @param buffer The binary file stored in an array buffer.
  92400. * @param size The expected size of the extracted cubemap.
  92401. * @return The Cube Map information.
  92402. */
  92403. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  92404. var uint8array = new Uint8Array(buffer);
  92405. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  92406. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92407. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  92408. return cubeMapData;
  92409. };
  92410. /**
  92411. * Returns the pixels data extracted from an RGBE texture.
  92412. * This pixels will be stored left to right up to down in the R G B order in one array.
  92413. *
  92414. * More information on this format are available here:
  92415. * https://en.wikipedia.org/wiki/RGBE_image_format
  92416. *
  92417. * @param uint8array The binary file stored in an array buffer.
  92418. * @param hdrInfo The header information of the file.
  92419. * @return The pixels data in RGB right to left up to down order.
  92420. */
  92421. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  92422. // Keep for multi format supports.
  92423. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92424. };
  92425. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  92426. var num_scanlines = hdrInfo.height;
  92427. var scanline_width = hdrInfo.width;
  92428. var a, b, c, d, count;
  92429. var dataIndex = hdrInfo.dataPosition;
  92430. var index = 0, endIndex = 0, i = 0;
  92431. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  92432. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  92433. // 3 channels of 4 bytes per pixel in float.
  92434. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  92435. var resultArray = new Float32Array(resultBuffer);
  92436. // read in each successive scanline
  92437. while (num_scanlines > 0) {
  92438. a = uint8array[dataIndex++];
  92439. b = uint8array[dataIndex++];
  92440. c = uint8array[dataIndex++];
  92441. d = uint8array[dataIndex++];
  92442. if (a != 2 || b != 2 || (c & 0x80)) {
  92443. // this file is not run length encoded
  92444. throw "HDR Bad header format, not RLE";
  92445. }
  92446. if (((c << 8) | d) != scanline_width) {
  92447. throw "HDR Bad header format, wrong scan line width";
  92448. }
  92449. index = 0;
  92450. // read each of the four channels for the scanline into the buffer
  92451. for (i = 0; i < 4; i++) {
  92452. endIndex = (i + 1) * scanline_width;
  92453. while (index < endIndex) {
  92454. a = uint8array[dataIndex++];
  92455. b = uint8array[dataIndex++];
  92456. if (a > 128) {
  92457. // a run of the same value
  92458. count = a - 128;
  92459. if ((count == 0) || (count > endIndex - index)) {
  92460. throw "HDR Bad Format, bad scanline data (run)";
  92461. }
  92462. while (count-- > 0) {
  92463. scanLineArray[index++] = b;
  92464. }
  92465. }
  92466. else {
  92467. // a non-run
  92468. count = a;
  92469. if ((count == 0) || (count > endIndex - index)) {
  92470. throw "HDR Bad Format, bad scanline data (non-run)";
  92471. }
  92472. scanLineArray[index++] = b;
  92473. if (--count > 0) {
  92474. for (var j = 0; j < count; j++) {
  92475. scanLineArray[index++] = uint8array[dataIndex++];
  92476. }
  92477. }
  92478. }
  92479. }
  92480. }
  92481. // now convert data from buffer into floats
  92482. for (i = 0; i < scanline_width; i++) {
  92483. a = scanLineArray[i];
  92484. b = scanLineArray[i + scanline_width];
  92485. c = scanLineArray[i + 2 * scanline_width];
  92486. d = scanLineArray[i + 3 * scanline_width];
  92487. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  92488. }
  92489. num_scanlines--;
  92490. }
  92491. return resultArray;
  92492. };
  92493. return HDRTools;
  92494. }());
  92495. BABYLON.HDRTools = HDRTools;
  92496. })(BABYLON || (BABYLON = {}));
  92497. //# sourceMappingURL=babylon.hdr.js.map
  92498. var BABYLON;
  92499. (function (BABYLON) {
  92500. /**
  92501. * This represents a texture coming from an HDR input.
  92502. *
  92503. * The only supported format is currently panorama picture stored in RGBE format.
  92504. * Example of such files can be found on HDRLib: http://hdrlib.com/
  92505. */
  92506. var HDRCubeTexture = /** @class */ (function (_super) {
  92507. __extends(HDRCubeTexture, _super);
  92508. /**
  92509. * Instantiates an HDRTexture from the following parameters.
  92510. *
  92511. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  92512. * @param scene The scene the texture will be used in
  92513. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  92514. * @param noMipmap Forces to not generate the mipmap if true
  92515. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  92516. * @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)
  92517. * @param reserved Reserved flag for internal use.
  92518. */
  92519. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  92520. if (noMipmap === void 0) { noMipmap = false; }
  92521. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92522. if (gammaSpace === void 0) { gammaSpace = false; }
  92523. if (reserved === void 0) { reserved = false; }
  92524. if (onLoad === void 0) { onLoad = null; }
  92525. if (onError === void 0) { onError = null; }
  92526. var _this = _super.call(this, scene) || this;
  92527. _this._generateHarmonics = true;
  92528. _this._onLoad = null;
  92529. _this._onError = null;
  92530. /**
  92531. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  92532. */
  92533. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  92534. _this._isBlocking = true;
  92535. _this._rotationY = 0;
  92536. /**
  92537. * Gets or sets the center of the bounding box associated with the cube texture
  92538. * It must define where the camera used to render the texture was set
  92539. */
  92540. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  92541. if (!url) {
  92542. return _this;
  92543. }
  92544. _this.name = url;
  92545. _this.url = url;
  92546. _this.hasAlpha = false;
  92547. _this.isCube = true;
  92548. _this._textureMatrix = BABYLON.Matrix.Identity();
  92549. _this._onLoad = onLoad;
  92550. _this._onError = onError;
  92551. _this.gammaSpace = gammaSpace;
  92552. _this._noMipmap = noMipmap;
  92553. _this._size = size;
  92554. _this._texture = _this._getFromCache(url, _this._noMipmap);
  92555. if (!_this._texture) {
  92556. if (!scene.useDelayedTextureLoading) {
  92557. _this.loadTexture();
  92558. }
  92559. else {
  92560. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  92561. }
  92562. }
  92563. return _this;
  92564. }
  92565. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  92566. /**
  92567. * Gets wether or not the texture is blocking during loading.
  92568. */
  92569. get: function () {
  92570. return this._isBlocking;
  92571. },
  92572. /**
  92573. * Sets wether or not the texture is blocking during loading.
  92574. */
  92575. set: function (value) {
  92576. this._isBlocking = value;
  92577. },
  92578. enumerable: true,
  92579. configurable: true
  92580. });
  92581. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  92582. /**
  92583. * Gets texture matrix rotation angle around Y axis radians.
  92584. */
  92585. get: function () {
  92586. return this._rotationY;
  92587. },
  92588. /**
  92589. * Sets texture matrix rotation angle around Y axis in radians.
  92590. */
  92591. set: function (value) {
  92592. this._rotationY = value;
  92593. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  92594. },
  92595. enumerable: true,
  92596. configurable: true
  92597. });
  92598. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  92599. get: function () {
  92600. return this._boundingBoxSize;
  92601. },
  92602. /**
  92603. * Gets or sets the size of the bounding box associated with the cube texture
  92604. * When defined, the cubemap will switch to local mode
  92605. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  92606. * @example https://www.babylonjs-playground.com/#RNASML
  92607. */
  92608. set: function (value) {
  92609. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  92610. return;
  92611. }
  92612. this._boundingBoxSize = value;
  92613. var scene = this.getScene();
  92614. if (scene) {
  92615. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  92616. }
  92617. },
  92618. enumerable: true,
  92619. configurable: true
  92620. });
  92621. /**
  92622. * Occurs when the file is raw .hdr file.
  92623. */
  92624. HDRCubeTexture.prototype.loadTexture = function () {
  92625. var _this = this;
  92626. var callback = function (buffer) {
  92627. _this.lodGenerationOffset = 0.0;
  92628. _this.lodGenerationScale = 0.8;
  92629. var scene = _this.getScene();
  92630. if (!scene) {
  92631. return null;
  92632. }
  92633. // Extract the raw linear data.
  92634. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  92635. // Generate harmonics if needed.
  92636. if (_this._generateHarmonics) {
  92637. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  92638. _this.sphericalPolynomial = sphericalPolynomial;
  92639. }
  92640. var results = [];
  92641. var byteArray = null;
  92642. // Push each faces.
  92643. for (var j = 0; j < 6; j++) {
  92644. // Create uintarray fallback.
  92645. if (!scene.getEngine().getCaps().textureFloat) {
  92646. // 3 channels of 1 bytes per pixel in bytes.
  92647. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  92648. byteArray = new Uint8Array(byteBuffer);
  92649. }
  92650. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  92651. // If special cases.
  92652. if (_this.gammaSpace || byteArray) {
  92653. for (var i = 0; i < _this._size * _this._size; i++) {
  92654. // Put in gamma space if requested.
  92655. if (_this.gammaSpace) {
  92656. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  92657. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  92658. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  92659. }
  92660. // Convert to int texture for fallback.
  92661. if (byteArray) {
  92662. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  92663. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  92664. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  92665. // May use luminance instead if the result is not accurate.
  92666. var max = Math.max(Math.max(r, g), b);
  92667. if (max > 255) {
  92668. var scale = 255 / max;
  92669. r *= scale;
  92670. g *= scale;
  92671. b *= scale;
  92672. }
  92673. byteArray[(i * 3) + 0] = r;
  92674. byteArray[(i * 3) + 1] = g;
  92675. byteArray[(i * 3) + 2] = b;
  92676. }
  92677. }
  92678. }
  92679. if (byteArray) {
  92680. results.push(byteArray);
  92681. }
  92682. else {
  92683. results.push(dataFace);
  92684. }
  92685. }
  92686. return results;
  92687. };
  92688. var scene = this.getScene();
  92689. if (scene) {
  92690. 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);
  92691. }
  92692. };
  92693. HDRCubeTexture.prototype.clone = function () {
  92694. var scene = this.getScene();
  92695. if (!scene) {
  92696. return this;
  92697. }
  92698. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  92699. // Base texture
  92700. newTexture.level = this.level;
  92701. newTexture.wrapU = this.wrapU;
  92702. newTexture.wrapV = this.wrapV;
  92703. newTexture.coordinatesIndex = this.coordinatesIndex;
  92704. newTexture.coordinatesMode = this.coordinatesMode;
  92705. return newTexture;
  92706. };
  92707. // Methods
  92708. HDRCubeTexture.prototype.delayLoad = function () {
  92709. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  92710. return;
  92711. }
  92712. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  92713. this._texture = this._getFromCache(this.url, this._noMipmap);
  92714. if (!this._texture) {
  92715. this.loadTexture();
  92716. }
  92717. };
  92718. /**
  92719. * Get the texture reflection matrix used to rotate/transform the reflection.
  92720. * @returns the reflection matrix
  92721. */
  92722. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  92723. return this._textureMatrix;
  92724. };
  92725. /**
  92726. * Set the texture reflection matrix used to rotate/transform the reflection.
  92727. * @param value Define the reflection matrix to set
  92728. */
  92729. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  92730. this._textureMatrix = value;
  92731. };
  92732. /**
  92733. * Parses a JSON representation of an HDR Texture in order to create the texture
  92734. * @param parsedTexture Define the JSON representation
  92735. * @param scene Define the scene the texture should be created in
  92736. * @param rootUrl Define the root url in case we need to load relative dependencies
  92737. * @returns the newly created texture after parsing
  92738. */
  92739. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  92740. var texture = null;
  92741. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  92742. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  92743. texture.name = parsedTexture.name;
  92744. texture.hasAlpha = parsedTexture.hasAlpha;
  92745. texture.level = parsedTexture.level;
  92746. texture.coordinatesMode = parsedTexture.coordinatesMode;
  92747. texture.isBlocking = parsedTexture.isBlocking;
  92748. }
  92749. if (texture) {
  92750. if (parsedTexture.boundingBoxPosition) {
  92751. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  92752. }
  92753. if (parsedTexture.boundingBoxSize) {
  92754. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  92755. }
  92756. if (parsedTexture.rotationY) {
  92757. texture.rotationY = parsedTexture.rotationY;
  92758. }
  92759. }
  92760. return texture;
  92761. };
  92762. HDRCubeTexture.prototype.serialize = function () {
  92763. if (!this.name) {
  92764. return null;
  92765. }
  92766. var serializationObject = {};
  92767. serializationObject.name = this.name;
  92768. serializationObject.hasAlpha = this.hasAlpha;
  92769. serializationObject.isCube = true;
  92770. serializationObject.level = this.level;
  92771. serializationObject.size = this._size;
  92772. serializationObject.coordinatesMode = this.coordinatesMode;
  92773. serializationObject.useInGammaSpace = this.gammaSpace;
  92774. serializationObject.generateHarmonics = this._generateHarmonics;
  92775. serializationObject.customType = "BABYLON.HDRCubeTexture";
  92776. serializationObject.noMipmap = this._noMipmap;
  92777. serializationObject.isBlocking = this._isBlocking;
  92778. serializationObject.rotationY = this._rotationY;
  92779. return serializationObject;
  92780. };
  92781. HDRCubeTexture._facesMapping = [
  92782. "right",
  92783. "left",
  92784. "up",
  92785. "down",
  92786. "front",
  92787. "back"
  92788. ];
  92789. return HDRCubeTexture;
  92790. }(BABYLON.BaseTexture));
  92791. BABYLON.HDRCubeTexture = HDRCubeTexture;
  92792. })(BABYLON || (BABYLON = {}));
  92793. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  92794. var BABYLON;
  92795. (function (BABYLON) {
  92796. /**
  92797. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  92798. */
  92799. var PanoramaToCubeMapTools = /** @class */ (function () {
  92800. function PanoramaToCubeMapTools() {
  92801. }
  92802. /**
  92803. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  92804. *
  92805. * @param float32Array The source data.
  92806. * @param inputWidth The width of the input panorama.
  92807. * @param inputHeight The height of the input panorama.
  92808. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  92809. * @return The cubemap data
  92810. */
  92811. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  92812. if (!float32Array) {
  92813. throw "ConvertPanoramaToCubemap: input cannot be null";
  92814. }
  92815. if (float32Array.length != inputWidth * inputHeight * 3) {
  92816. throw "ConvertPanoramaToCubemap: input size is wrong";
  92817. }
  92818. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  92819. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  92820. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  92821. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  92822. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  92823. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  92824. return {
  92825. front: textureFront,
  92826. back: textureBack,
  92827. left: textureLeft,
  92828. right: textureRight,
  92829. up: textureUp,
  92830. down: textureDown,
  92831. size: size,
  92832. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  92833. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  92834. gammaSpace: false,
  92835. };
  92836. };
  92837. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  92838. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  92839. var textureArray = new Float32Array(buffer);
  92840. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  92841. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  92842. var dy = 1 / texSize;
  92843. var fy = 0;
  92844. for (var y = 0; y < texSize; y++) {
  92845. var xv1 = faceData[0];
  92846. var xv2 = faceData[2];
  92847. for (var x = 0; x < texSize; x++) {
  92848. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  92849. v.normalize();
  92850. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  92851. // 3 channels per pixels
  92852. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  92853. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  92854. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  92855. xv1 = xv1.add(rotDX1);
  92856. xv2 = xv2.add(rotDX2);
  92857. }
  92858. fy += dy;
  92859. }
  92860. return textureArray;
  92861. };
  92862. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  92863. var theta = Math.atan2(vDir.z, vDir.x);
  92864. var phi = Math.acos(vDir.y);
  92865. while (theta < -Math.PI) {
  92866. theta += 2 * Math.PI;
  92867. }
  92868. while (theta > Math.PI) {
  92869. theta -= 2 * Math.PI;
  92870. }
  92871. var dx = theta / Math.PI;
  92872. var dy = phi / Math.PI;
  92873. // recenter.
  92874. dx = dx * 0.5 + 0.5;
  92875. var px = Math.round(dx * inputWidth);
  92876. if (px < 0) {
  92877. px = 0;
  92878. }
  92879. else if (px >= inputWidth) {
  92880. px = inputWidth - 1;
  92881. }
  92882. var py = Math.round(dy * inputHeight);
  92883. if (py < 0) {
  92884. py = 0;
  92885. }
  92886. else if (py >= inputHeight) {
  92887. py = inputHeight - 1;
  92888. }
  92889. var inputY = (inputHeight - py - 1);
  92890. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  92891. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  92892. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  92893. return {
  92894. r: r,
  92895. g: g,
  92896. b: b
  92897. };
  92898. };
  92899. PanoramaToCubeMapTools.FACE_FRONT = [
  92900. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92901. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92902. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92903. new BABYLON.Vector3(1.0, 1.0, -1.0)
  92904. ];
  92905. PanoramaToCubeMapTools.FACE_BACK = [
  92906. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92907. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92908. new BABYLON.Vector3(1.0, 1.0, 1.0),
  92909. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  92910. ];
  92911. PanoramaToCubeMapTools.FACE_RIGHT = [
  92912. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92913. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92914. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92915. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92916. ];
  92917. PanoramaToCubeMapTools.FACE_LEFT = [
  92918. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92919. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92920. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92921. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  92922. ];
  92923. PanoramaToCubeMapTools.FACE_DOWN = [
  92924. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92925. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92926. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92927. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92928. ];
  92929. PanoramaToCubeMapTools.FACE_UP = [
  92930. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92931. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92932. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92933. new BABYLON.Vector3(1.0, -1.0, -1.0)
  92934. ];
  92935. return PanoramaToCubeMapTools;
  92936. }());
  92937. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  92938. })(BABYLON || (BABYLON = {}));
  92939. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  92940. var BABYLON;
  92941. (function (BABYLON) {
  92942. /**
  92943. * Vector2 wth index property
  92944. */
  92945. var IndexedVector2 = /** @class */ (function (_super) {
  92946. __extends(IndexedVector2, _super);
  92947. function IndexedVector2(original,
  92948. /** Index of the vector2 */
  92949. index) {
  92950. var _this = _super.call(this, original.x, original.y) || this;
  92951. _this.index = index;
  92952. return _this;
  92953. }
  92954. return IndexedVector2;
  92955. }(BABYLON.Vector2));
  92956. /**
  92957. * Defines points to create a polygon
  92958. */
  92959. var PolygonPoints = /** @class */ (function () {
  92960. function PolygonPoints() {
  92961. this.elements = new Array();
  92962. }
  92963. PolygonPoints.prototype.add = function (originalPoints) {
  92964. var _this = this;
  92965. var result = new Array();
  92966. originalPoints.forEach(function (point) {
  92967. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  92968. var newPoint = new IndexedVector2(point, _this.elements.length);
  92969. result.push(newPoint);
  92970. _this.elements.push(newPoint);
  92971. }
  92972. });
  92973. return result;
  92974. };
  92975. PolygonPoints.prototype.computeBounds = function () {
  92976. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  92977. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  92978. this.elements.forEach(function (point) {
  92979. // x
  92980. if (point.x < lmin.x) {
  92981. lmin.x = point.x;
  92982. }
  92983. else if (point.x > lmax.x) {
  92984. lmax.x = point.x;
  92985. }
  92986. // y
  92987. if (point.y < lmin.y) {
  92988. lmin.y = point.y;
  92989. }
  92990. else if (point.y > lmax.y) {
  92991. lmax.y = point.y;
  92992. }
  92993. });
  92994. return {
  92995. min: lmin,
  92996. max: lmax,
  92997. width: lmax.x - lmin.x,
  92998. height: lmax.y - lmin.y
  92999. };
  93000. };
  93001. return PolygonPoints;
  93002. }());
  93003. /**
  93004. * Polygon
  93005. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  93006. */
  93007. var Polygon = /** @class */ (function () {
  93008. function Polygon() {
  93009. }
  93010. /**
  93011. * Creates a rectangle
  93012. * @param xmin bottom X coord
  93013. * @param ymin bottom Y coord
  93014. * @param xmax top X coord
  93015. * @param ymax top Y coord
  93016. * @returns points that make the resulting rectation
  93017. */
  93018. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  93019. return [
  93020. new BABYLON.Vector2(xmin, ymin),
  93021. new BABYLON.Vector2(xmax, ymin),
  93022. new BABYLON.Vector2(xmax, ymax),
  93023. new BABYLON.Vector2(xmin, ymax)
  93024. ];
  93025. };
  93026. /**
  93027. * Creates a circle
  93028. * @param radius radius of circle
  93029. * @param cx scale in x
  93030. * @param cy scale in y
  93031. * @param numberOfSides number of sides that make up the circle
  93032. * @returns points that make the resulting circle
  93033. */
  93034. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  93035. if (cx === void 0) { cx = 0; }
  93036. if (cy === void 0) { cy = 0; }
  93037. if (numberOfSides === void 0) { numberOfSides = 32; }
  93038. var result = new Array();
  93039. var angle = 0;
  93040. var increment = (Math.PI * 2) / numberOfSides;
  93041. for (var i = 0; i < numberOfSides; i++) {
  93042. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  93043. angle -= increment;
  93044. }
  93045. return result;
  93046. };
  93047. /**
  93048. * Creates a polygon from input string
  93049. * @param input Input polygon data
  93050. * @returns the parsed points
  93051. */
  93052. Polygon.Parse = function (input) {
  93053. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  93054. var i, result = [];
  93055. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  93056. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  93057. }
  93058. return result;
  93059. };
  93060. /**
  93061. * Starts building a polygon from x and y coordinates
  93062. * @param x x coordinate
  93063. * @param y y coordinate
  93064. * @returns the started path2
  93065. */
  93066. Polygon.StartingAt = function (x, y) {
  93067. return BABYLON.Path2.StartingAt(x, y);
  93068. };
  93069. return Polygon;
  93070. }());
  93071. BABYLON.Polygon = Polygon;
  93072. /**
  93073. * Builds a polygon
  93074. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  93075. */
  93076. var PolygonMeshBuilder = /** @class */ (function () {
  93077. /**
  93078. * Creates a PolygonMeshBuilder
  93079. * @param name name of the builder
  93080. * @param contours Path of the polygon
  93081. * @param scene scene to add to
  93082. */
  93083. function PolygonMeshBuilder(name, contours, scene) {
  93084. this._points = new PolygonPoints();
  93085. this._outlinepoints = new PolygonPoints();
  93086. this._holes = new Array();
  93087. this._epoints = new Array();
  93088. this._eholes = new Array();
  93089. this._name = name;
  93090. this._scene = scene;
  93091. var points;
  93092. if (contours instanceof BABYLON.Path2) {
  93093. points = contours.getPoints();
  93094. }
  93095. else {
  93096. points = contours;
  93097. }
  93098. this._addToepoint(points);
  93099. this._points.add(points);
  93100. this._outlinepoints.add(points);
  93101. if (typeof earcut === 'undefined') {
  93102. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  93103. }
  93104. }
  93105. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  93106. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  93107. var p = points_1[_i];
  93108. this._epoints.push(p.x, p.y);
  93109. }
  93110. };
  93111. /**
  93112. * Adds a whole within the polygon
  93113. * @param hole Array of points defining the hole
  93114. * @returns this
  93115. */
  93116. PolygonMeshBuilder.prototype.addHole = function (hole) {
  93117. this._points.add(hole);
  93118. var holepoints = new PolygonPoints();
  93119. holepoints.add(hole);
  93120. this._holes.push(holepoints);
  93121. this._eholes.push(this._epoints.length / 2);
  93122. this._addToepoint(hole);
  93123. return this;
  93124. };
  93125. /**
  93126. * Creates the polygon
  93127. * @param updatable If the mesh should be updatable
  93128. * @param depth The depth of the mesh created
  93129. * @returns the created mesh
  93130. */
  93131. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  93132. var _this = this;
  93133. if (updatable === void 0) { updatable = false; }
  93134. if (depth === void 0) { depth = 0; }
  93135. var result = new BABYLON.Mesh(this._name, this._scene);
  93136. var normals = new Array();
  93137. var positions = new Array();
  93138. var uvs = new Array();
  93139. var bounds = this._points.computeBounds();
  93140. this._points.elements.forEach(function (p) {
  93141. normals.push(0, 1.0, 0);
  93142. positions.push(p.x, 0, p.y);
  93143. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  93144. });
  93145. var indices = new Array();
  93146. var res = earcut(this._epoints, this._eholes, 2);
  93147. for (var i = 0; i < res.length; i++) {
  93148. indices.push(res[i]);
  93149. }
  93150. if (depth > 0) {
  93151. var positionscount = (positions.length / 3); //get the current pointcount
  93152. this._points.elements.forEach(function (p) {
  93153. normals.push(0, -1.0, 0);
  93154. positions.push(p.x, -depth, p.y);
  93155. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  93156. });
  93157. var totalCount = indices.length;
  93158. for (var i = 0; i < totalCount; i += 3) {
  93159. var i0 = indices[i + 0];
  93160. var i1 = indices[i + 1];
  93161. var i2 = indices[i + 2];
  93162. indices.push(i2 + positionscount);
  93163. indices.push(i1 + positionscount);
  93164. indices.push(i0 + positionscount);
  93165. }
  93166. //Add the sides
  93167. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  93168. this._holes.forEach(function (hole) {
  93169. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  93170. });
  93171. }
  93172. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  93173. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  93174. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  93175. result.setIndices(indices);
  93176. return result;
  93177. };
  93178. /**
  93179. * Adds a side to the polygon
  93180. * @param positions points that make the polygon
  93181. * @param normals normals of the polygon
  93182. * @param uvs uvs of the polygon
  93183. * @param indices indices of the polygon
  93184. * @param bounds bounds of the polygon
  93185. * @param points points of the polygon
  93186. * @param depth depth of the polygon
  93187. * @param flip flip of the polygon
  93188. */
  93189. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  93190. var StartIndex = positions.length / 3;
  93191. var ulength = 0;
  93192. for (var i = 0; i < points.elements.length; i++) {
  93193. var p = points.elements[i];
  93194. var p1;
  93195. if ((i + 1) > points.elements.length - 1) {
  93196. p1 = points.elements[0];
  93197. }
  93198. else {
  93199. p1 = points.elements[i + 1];
  93200. }
  93201. positions.push(p.x, 0, p.y);
  93202. positions.push(p.x, -depth, p.y);
  93203. positions.push(p1.x, 0, p1.y);
  93204. positions.push(p1.x, -depth, p1.y);
  93205. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  93206. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  93207. var v3 = v2.subtract(v1);
  93208. var v4 = new BABYLON.Vector3(0, 1, 0);
  93209. var vn = BABYLON.Vector3.Cross(v3, v4);
  93210. vn = vn.normalize();
  93211. uvs.push(ulength / bounds.width, 0);
  93212. uvs.push(ulength / bounds.width, 1);
  93213. ulength += v3.length();
  93214. uvs.push((ulength / bounds.width), 0);
  93215. uvs.push((ulength / bounds.width), 1);
  93216. if (!flip) {
  93217. normals.push(-vn.x, -vn.y, -vn.z);
  93218. normals.push(-vn.x, -vn.y, -vn.z);
  93219. normals.push(-vn.x, -vn.y, -vn.z);
  93220. normals.push(-vn.x, -vn.y, -vn.z);
  93221. indices.push(StartIndex);
  93222. indices.push(StartIndex + 1);
  93223. indices.push(StartIndex + 2);
  93224. indices.push(StartIndex + 1);
  93225. indices.push(StartIndex + 3);
  93226. indices.push(StartIndex + 2);
  93227. }
  93228. else {
  93229. normals.push(vn.x, vn.y, vn.z);
  93230. normals.push(vn.x, vn.y, vn.z);
  93231. normals.push(vn.x, vn.y, vn.z);
  93232. normals.push(vn.x, vn.y, vn.z);
  93233. indices.push(StartIndex);
  93234. indices.push(StartIndex + 2);
  93235. indices.push(StartIndex + 1);
  93236. indices.push(StartIndex + 1);
  93237. indices.push(StartIndex + 2);
  93238. indices.push(StartIndex + 3);
  93239. }
  93240. StartIndex += 4;
  93241. }
  93242. };
  93243. return PolygonMeshBuilder;
  93244. }());
  93245. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  93246. })(BABYLON || (BABYLON = {}));
  93247. //# sourceMappingURL=babylon.polygonMesh.js.map
  93248. var BABYLON;
  93249. (function (BABYLON) {
  93250. /**
  93251. * Unique ID when we import meshes from Babylon to CSG
  93252. */
  93253. var currentCSGMeshId = 0;
  93254. /**
  93255. * Represents a vertex of a polygon. Use your own vertex class instead of this
  93256. * one to provide additional features like texture coordinates and vertex
  93257. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  93258. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  93259. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  93260. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  93261. * is not used anywhere else.
  93262. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  93263. */
  93264. var Vertex = /** @class */ (function () {
  93265. /**
  93266. * Initializes the vertex
  93267. * @param pos The position of the vertex
  93268. * @param normal The normal of the vertex
  93269. * @param uv The texture coordinate of the vertex
  93270. */
  93271. function Vertex(
  93272. /**
  93273. * The position of the vertex
  93274. */
  93275. pos,
  93276. /**
  93277. * The normal of the vertex
  93278. */
  93279. normal,
  93280. /**
  93281. * The texture coordinate of the vertex
  93282. */
  93283. uv) {
  93284. this.pos = pos;
  93285. this.normal = normal;
  93286. this.uv = uv;
  93287. }
  93288. /**
  93289. * Make a clone, or deep copy, of the vertex
  93290. * @returns A new Vertex
  93291. */
  93292. Vertex.prototype.clone = function () {
  93293. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  93294. };
  93295. /**
  93296. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  93297. * orientation of a polygon is flipped.
  93298. */
  93299. Vertex.prototype.flip = function () {
  93300. this.normal = this.normal.scale(-1);
  93301. };
  93302. /**
  93303. * Create a new vertex between this vertex and `other` by linearly
  93304. * interpolating all properties using a parameter of `t`. Subclasses should
  93305. * override this to interpolate additional properties.
  93306. * @param other the vertex to interpolate against
  93307. * @param t The factor used to linearly interpolate between the vertices
  93308. */
  93309. Vertex.prototype.interpolate = function (other, t) {
  93310. 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));
  93311. };
  93312. return Vertex;
  93313. }());
  93314. /**
  93315. * Represents a plane in 3D space.
  93316. */
  93317. var Plane = /** @class */ (function () {
  93318. /**
  93319. * Initializes the plane
  93320. * @param normal The normal for the plane
  93321. * @param w
  93322. */
  93323. function Plane(normal, w) {
  93324. this.normal = normal;
  93325. this.w = w;
  93326. }
  93327. /**
  93328. * Construct a plane from three points
  93329. * @param a Point a
  93330. * @param b Point b
  93331. * @param c Point c
  93332. */
  93333. Plane.FromPoints = function (a, b, c) {
  93334. var v0 = c.subtract(a);
  93335. var v1 = b.subtract(a);
  93336. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  93337. return null;
  93338. }
  93339. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  93340. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  93341. };
  93342. /**
  93343. * Clone, or make a deep copy of the plane
  93344. * @returns a new Plane
  93345. */
  93346. Plane.prototype.clone = function () {
  93347. return new Plane(this.normal.clone(), this.w);
  93348. };
  93349. /**
  93350. * Flip the face of the plane
  93351. */
  93352. Plane.prototype.flip = function () {
  93353. this.normal.scaleInPlace(-1);
  93354. this.w = -this.w;
  93355. };
  93356. /**
  93357. * Split `polygon` by this plane if needed, then put the polygon or polygon
  93358. * fragments in the appropriate lists. Coplanar polygons go into either
  93359. `* coplanarFront` or `coplanarBack` depending on their orientation with
  93360. * respect to this plane. Polygons in front or in back of this plane go into
  93361. * either `front` or `back`
  93362. * @param polygon The polygon to be split
  93363. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  93364. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  93365. * @param front Will contain the polygons in front of the plane
  93366. * @param back Will contain the polygons begind the plane
  93367. */
  93368. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  93369. var COPLANAR = 0;
  93370. var FRONT = 1;
  93371. var BACK = 2;
  93372. var SPANNING = 3;
  93373. // Classify each point as well as the entire polygon into one of the above
  93374. // four classes.
  93375. var polygonType = 0;
  93376. var types = [];
  93377. var i;
  93378. var t;
  93379. for (i = 0; i < polygon.vertices.length; i++) {
  93380. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  93381. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  93382. polygonType |= type;
  93383. types.push(type);
  93384. }
  93385. // Put the polygon in the correct list, splitting it when necessary
  93386. switch (polygonType) {
  93387. case COPLANAR:
  93388. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  93389. break;
  93390. case FRONT:
  93391. front.push(polygon);
  93392. break;
  93393. case BACK:
  93394. back.push(polygon);
  93395. break;
  93396. case SPANNING:
  93397. var f = [], b = [];
  93398. for (i = 0; i < polygon.vertices.length; i++) {
  93399. var j = (i + 1) % polygon.vertices.length;
  93400. var ti = types[i], tj = types[j];
  93401. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  93402. if (ti !== BACK) {
  93403. f.push(vi);
  93404. }
  93405. if (ti !== FRONT) {
  93406. b.push(ti !== BACK ? vi.clone() : vi);
  93407. }
  93408. if ((ti | tj) === SPANNING) {
  93409. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  93410. var v = vi.interpolate(vj, t);
  93411. f.push(v);
  93412. b.push(v.clone());
  93413. }
  93414. }
  93415. var poly;
  93416. if (f.length >= 3) {
  93417. poly = new Polygon(f, polygon.shared);
  93418. if (poly.plane) {
  93419. front.push(poly);
  93420. }
  93421. }
  93422. if (b.length >= 3) {
  93423. poly = new Polygon(b, polygon.shared);
  93424. if (poly.plane) {
  93425. back.push(poly);
  93426. }
  93427. }
  93428. break;
  93429. }
  93430. };
  93431. /**
  93432. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  93433. * point is on the plane
  93434. */
  93435. Plane.EPSILON = 1e-5;
  93436. return Plane;
  93437. }());
  93438. /**
  93439. * Represents a convex polygon. The vertices used to initialize a polygon must
  93440. * be coplanar and form a convex loop.
  93441. *
  93442. * Each convex polygon has a `shared` property, which is shared between all
  93443. * polygons that are clones of each other or were split from the same polygon.
  93444. * This can be used to define per-polygon properties (such as surface color)
  93445. */
  93446. var Polygon = /** @class */ (function () {
  93447. /**
  93448. * Initializes the polygon
  93449. * @param vertices The vertices of the polygon
  93450. * @param shared The properties shared across all polygons
  93451. */
  93452. function Polygon(vertices, shared) {
  93453. this.vertices = vertices;
  93454. this.shared = shared;
  93455. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  93456. }
  93457. /**
  93458. * Clones, or makes a deep copy, or the polygon
  93459. */
  93460. Polygon.prototype.clone = function () {
  93461. var vertices = this.vertices.map(function (v) { return v.clone(); });
  93462. return new Polygon(vertices, this.shared);
  93463. };
  93464. /**
  93465. * Flips the faces of the polygon
  93466. */
  93467. Polygon.prototype.flip = function () {
  93468. this.vertices.reverse().map(function (v) { v.flip(); });
  93469. this.plane.flip();
  93470. };
  93471. return Polygon;
  93472. }());
  93473. /**
  93474. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  93475. * by picking a polygon to split along. That polygon (and all other coplanar
  93476. * polygons) are added directly to that node and the other polygons are added to
  93477. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  93478. * no distinction between internal and leaf nodes
  93479. */
  93480. var Node = /** @class */ (function () {
  93481. /**
  93482. * Initializes the node
  93483. * @param polygons A collection of polygons held in the node
  93484. */
  93485. function Node(polygons) {
  93486. this.plane = null;
  93487. this.front = null;
  93488. this.back = null;
  93489. this.polygons = new Array();
  93490. if (polygons) {
  93491. this.build(polygons);
  93492. }
  93493. }
  93494. /**
  93495. * Clones, or makes a deep copy, of the node
  93496. * @returns The cloned node
  93497. */
  93498. Node.prototype.clone = function () {
  93499. var node = new Node();
  93500. node.plane = this.plane && this.plane.clone();
  93501. node.front = this.front && this.front.clone();
  93502. node.back = this.back && this.back.clone();
  93503. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  93504. return node;
  93505. };
  93506. /**
  93507. * Convert solid space to empty space and empty space to solid space
  93508. */
  93509. Node.prototype.invert = function () {
  93510. for (var i = 0; i < this.polygons.length; i++) {
  93511. this.polygons[i].flip();
  93512. }
  93513. if (this.plane) {
  93514. this.plane.flip();
  93515. }
  93516. if (this.front) {
  93517. this.front.invert();
  93518. }
  93519. if (this.back) {
  93520. this.back.invert();
  93521. }
  93522. var temp = this.front;
  93523. this.front = this.back;
  93524. this.back = temp;
  93525. };
  93526. /**
  93527. * Recursively remove all polygons in `polygons` that are inside this BSP
  93528. * tree.
  93529. * @param polygons Polygons to remove from the BSP
  93530. * @returns Polygons clipped from the BSP
  93531. */
  93532. Node.prototype.clipPolygons = function (polygons) {
  93533. if (!this.plane) {
  93534. return polygons.slice();
  93535. }
  93536. var front = new Array(), back = new Array();
  93537. for (var i = 0; i < polygons.length; i++) {
  93538. this.plane.splitPolygon(polygons[i], front, back, front, back);
  93539. }
  93540. if (this.front) {
  93541. front = this.front.clipPolygons(front);
  93542. }
  93543. if (this.back) {
  93544. back = this.back.clipPolygons(back);
  93545. }
  93546. else {
  93547. back = [];
  93548. }
  93549. return front.concat(back);
  93550. };
  93551. /**
  93552. * Remove all polygons in this BSP tree that are inside the other BSP tree
  93553. * `bsp`.
  93554. * @param bsp BSP containing polygons to remove from this BSP
  93555. */
  93556. Node.prototype.clipTo = function (bsp) {
  93557. this.polygons = bsp.clipPolygons(this.polygons);
  93558. if (this.front) {
  93559. this.front.clipTo(bsp);
  93560. }
  93561. if (this.back) {
  93562. this.back.clipTo(bsp);
  93563. }
  93564. };
  93565. /**
  93566. * Return a list of all polygons in this BSP tree
  93567. * @returns List of all polygons in this BSP tree
  93568. */
  93569. Node.prototype.allPolygons = function () {
  93570. var polygons = this.polygons.slice();
  93571. if (this.front) {
  93572. polygons = polygons.concat(this.front.allPolygons());
  93573. }
  93574. if (this.back) {
  93575. polygons = polygons.concat(this.back.allPolygons());
  93576. }
  93577. return polygons;
  93578. };
  93579. /**
  93580. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  93581. * new polygons are filtered down to the bottom of the tree and become new
  93582. * nodes there. Each set of polygons is partitioned using the first polygon
  93583. * (no heuristic is used to pick a good split)
  93584. * @param polygons Polygons used to construct the BSP tree
  93585. */
  93586. Node.prototype.build = function (polygons) {
  93587. if (!polygons.length) {
  93588. return;
  93589. }
  93590. if (!this.plane) {
  93591. this.plane = polygons[0].plane.clone();
  93592. }
  93593. var front = new Array(), back = new Array();
  93594. for (var i = 0; i < polygons.length; i++) {
  93595. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  93596. }
  93597. if (front.length) {
  93598. if (!this.front) {
  93599. this.front = new Node();
  93600. }
  93601. this.front.build(front);
  93602. }
  93603. if (back.length) {
  93604. if (!this.back) {
  93605. this.back = new Node();
  93606. }
  93607. this.back.build(back);
  93608. }
  93609. };
  93610. return Node;
  93611. }());
  93612. /**
  93613. * Class for building Constructive Solid Geometry
  93614. */
  93615. var CSG = /** @class */ (function () {
  93616. function CSG() {
  93617. this.polygons = new Array();
  93618. }
  93619. /**
  93620. * Convert the BABYLON.Mesh to BABYLON.CSG
  93621. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  93622. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  93623. */
  93624. CSG.FromMesh = function (mesh) {
  93625. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  93626. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  93627. if (mesh instanceof BABYLON.Mesh) {
  93628. mesh.computeWorldMatrix(true);
  93629. matrix = mesh.getWorldMatrix();
  93630. meshPosition = mesh.position.clone();
  93631. meshRotation = mesh.rotation.clone();
  93632. if (mesh.rotationQuaternion) {
  93633. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  93634. }
  93635. meshScaling = mesh.scaling.clone();
  93636. }
  93637. else {
  93638. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  93639. }
  93640. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93641. var subMeshes = mesh.subMeshes;
  93642. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  93643. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  93644. vertices = [];
  93645. for (var j = 0; j < 3; j++) {
  93646. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  93647. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  93648. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  93649. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  93650. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  93651. vertex = new Vertex(position, normal, uv);
  93652. vertices.push(vertex);
  93653. }
  93654. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  93655. // To handle the case of degenerated triangle
  93656. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  93657. if (polygon.plane) {
  93658. polygons.push(polygon);
  93659. }
  93660. }
  93661. }
  93662. var csg = CSG.FromPolygons(polygons);
  93663. csg.matrix = matrix;
  93664. csg.position = meshPosition;
  93665. csg.rotation = meshRotation;
  93666. csg.scaling = meshScaling;
  93667. csg.rotationQuaternion = meshRotationQuaternion;
  93668. currentCSGMeshId++;
  93669. return csg;
  93670. };
  93671. /**
  93672. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  93673. * @param polygons Polygons used to construct a BABYLON.CSG solid
  93674. */
  93675. CSG.FromPolygons = function (polygons) {
  93676. var csg = new CSG();
  93677. csg.polygons = polygons;
  93678. return csg;
  93679. };
  93680. /**
  93681. * Clones, or makes a deep copy, of the BABYLON.CSG
  93682. * @returns A new BABYLON.CSG
  93683. */
  93684. CSG.prototype.clone = function () {
  93685. var csg = new CSG();
  93686. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  93687. csg.copyTransformAttributes(this);
  93688. return csg;
  93689. };
  93690. /**
  93691. * Unions this CSG with another CSG
  93692. * @param csg The CSG to union against this CSG
  93693. * @returns The unioned CSG
  93694. */
  93695. CSG.prototype.union = function (csg) {
  93696. var a = new Node(this.clone().polygons);
  93697. var b = new Node(csg.clone().polygons);
  93698. a.clipTo(b);
  93699. b.clipTo(a);
  93700. b.invert();
  93701. b.clipTo(a);
  93702. b.invert();
  93703. a.build(b.allPolygons());
  93704. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93705. };
  93706. /**
  93707. * Unions this CSG with another CSG in place
  93708. * @param csg The CSG to union against this CSG
  93709. */
  93710. CSG.prototype.unionInPlace = function (csg) {
  93711. var a = new Node(this.polygons);
  93712. var b = new Node(csg.polygons);
  93713. a.clipTo(b);
  93714. b.clipTo(a);
  93715. b.invert();
  93716. b.clipTo(a);
  93717. b.invert();
  93718. a.build(b.allPolygons());
  93719. this.polygons = a.allPolygons();
  93720. };
  93721. /**
  93722. * Subtracts this CSG with another CSG
  93723. * @param csg The CSG to subtract against this CSG
  93724. * @returns A new BABYLON.CSG
  93725. */
  93726. CSG.prototype.subtract = function (csg) {
  93727. var a = new Node(this.clone().polygons);
  93728. var b = new Node(csg.clone().polygons);
  93729. a.invert();
  93730. a.clipTo(b);
  93731. b.clipTo(a);
  93732. b.invert();
  93733. b.clipTo(a);
  93734. b.invert();
  93735. a.build(b.allPolygons());
  93736. a.invert();
  93737. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93738. };
  93739. /**
  93740. * Subtracts this CSG with another CSG in place
  93741. * @param csg The CSG to subtact against this CSG
  93742. */
  93743. CSG.prototype.subtractInPlace = function (csg) {
  93744. var a = new Node(this.polygons);
  93745. var b = new Node(csg.polygons);
  93746. a.invert();
  93747. a.clipTo(b);
  93748. b.clipTo(a);
  93749. b.invert();
  93750. b.clipTo(a);
  93751. b.invert();
  93752. a.build(b.allPolygons());
  93753. a.invert();
  93754. this.polygons = a.allPolygons();
  93755. };
  93756. /**
  93757. * Intersect this CSG with another CSG
  93758. * @param csg The CSG to intersect against this CSG
  93759. * @returns A new BABYLON.CSG
  93760. */
  93761. CSG.prototype.intersect = function (csg) {
  93762. var a = new Node(this.clone().polygons);
  93763. var b = new Node(csg.clone().polygons);
  93764. a.invert();
  93765. b.clipTo(a);
  93766. b.invert();
  93767. a.clipTo(b);
  93768. b.clipTo(a);
  93769. a.build(b.allPolygons());
  93770. a.invert();
  93771. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93772. };
  93773. /**
  93774. * Intersects this CSG with another CSG in place
  93775. * @param csg The CSG to intersect against this CSG
  93776. */
  93777. CSG.prototype.intersectInPlace = function (csg) {
  93778. var a = new Node(this.polygons);
  93779. var b = new Node(csg.polygons);
  93780. a.invert();
  93781. b.clipTo(a);
  93782. b.invert();
  93783. a.clipTo(b);
  93784. b.clipTo(a);
  93785. a.build(b.allPolygons());
  93786. a.invert();
  93787. this.polygons = a.allPolygons();
  93788. };
  93789. /**
  93790. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  93791. * not modified.
  93792. * @returns A new BABYLON.CSG solid with solid and empty space switched
  93793. */
  93794. CSG.prototype.inverse = function () {
  93795. var csg = this.clone();
  93796. csg.inverseInPlace();
  93797. return csg;
  93798. };
  93799. /**
  93800. * Inverses the BABYLON.CSG in place
  93801. */
  93802. CSG.prototype.inverseInPlace = function () {
  93803. this.polygons.map(function (p) { p.flip(); });
  93804. };
  93805. /**
  93806. * This is used to keep meshes transformations so they can be restored
  93807. * when we build back a Babylon Mesh
  93808. * NB : All CSG operations are performed in world coordinates
  93809. * @param csg The BABYLON.CSG to copy the transform attributes from
  93810. * @returns This BABYLON.CSG
  93811. */
  93812. CSG.prototype.copyTransformAttributes = function (csg) {
  93813. this.matrix = csg.matrix;
  93814. this.position = csg.position;
  93815. this.rotation = csg.rotation;
  93816. this.scaling = csg.scaling;
  93817. this.rotationQuaternion = csg.rotationQuaternion;
  93818. return this;
  93819. };
  93820. /**
  93821. * Build Raw mesh from CSG
  93822. * Coordinates here are in world space
  93823. * @param name The name of the mesh geometry
  93824. * @param scene The BABYLON.Scene
  93825. * @param keepSubMeshes Specifies if the submeshes should be kept
  93826. * @returns A new BABYLON.Mesh
  93827. */
  93828. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  93829. var matrix = this.matrix.clone();
  93830. matrix.invert();
  93831. 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;
  93832. if (keepSubMeshes) {
  93833. // Sort Polygons, since subMeshes are indices range
  93834. polygons.sort(function (a, b) {
  93835. if (a.shared.meshId === b.shared.meshId) {
  93836. return a.shared.subMeshId - b.shared.subMeshId;
  93837. }
  93838. else {
  93839. return a.shared.meshId - b.shared.meshId;
  93840. }
  93841. });
  93842. }
  93843. for (var i = 0, il = polygons.length; i < il; i++) {
  93844. polygon = polygons[i];
  93845. // Building SubMeshes
  93846. if (!subMesh_dict[polygon.shared.meshId]) {
  93847. subMesh_dict[polygon.shared.meshId] = {};
  93848. }
  93849. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  93850. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  93851. indexStart: +Infinity,
  93852. indexEnd: -Infinity,
  93853. materialIndex: polygon.shared.materialIndex
  93854. };
  93855. }
  93856. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  93857. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  93858. polygonIndices[0] = 0;
  93859. polygonIndices[1] = j - 1;
  93860. polygonIndices[2] = j;
  93861. for (var k = 0; k < 3; k++) {
  93862. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  93863. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  93864. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  93865. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  93866. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  93867. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  93868. // Check if 2 points can be merged
  93869. if (!(typeof vertex_idx !== 'undefined' &&
  93870. normals[vertex_idx * 3] === localNormal.x &&
  93871. normals[vertex_idx * 3 + 1] === localNormal.y &&
  93872. normals[vertex_idx * 3 + 2] === localNormal.z &&
  93873. uvs[vertex_idx * 2] === uv.x &&
  93874. uvs[vertex_idx * 2 + 1] === uv.y)) {
  93875. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  93876. uvs.push(uv.x, uv.y);
  93877. normals.push(normal.x, normal.y, normal.z);
  93878. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  93879. }
  93880. indices.push(vertex_idx);
  93881. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  93882. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  93883. currentIndex++;
  93884. }
  93885. }
  93886. }
  93887. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  93888. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  93889. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  93890. mesh.setIndices(indices, null);
  93891. if (keepSubMeshes) {
  93892. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  93893. var materialIndexOffset = 0, materialMaxIndex;
  93894. mesh.subMeshes = new Array();
  93895. for (var m in subMesh_dict) {
  93896. materialMaxIndex = -1;
  93897. for (var sm in subMesh_dict[m]) {
  93898. subMesh_obj = subMesh_dict[m][sm];
  93899. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  93900. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  93901. }
  93902. materialIndexOffset += ++materialMaxIndex;
  93903. }
  93904. }
  93905. return mesh;
  93906. };
  93907. /**
  93908. * Build Mesh from CSG taking material and transforms into account
  93909. * @param name The name of the BABYLON.Mesh
  93910. * @param material The material of the BABYLON.Mesh
  93911. * @param scene The BABYLON.Scene
  93912. * @param keepSubMeshes Specifies if submeshes should be kept
  93913. * @returns The new BABYLON.Mesh
  93914. */
  93915. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  93916. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  93917. mesh.material = material;
  93918. mesh.position.copyFrom(this.position);
  93919. mesh.rotation.copyFrom(this.rotation);
  93920. if (this.rotationQuaternion) {
  93921. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  93922. }
  93923. mesh.scaling.copyFrom(this.scaling);
  93924. mesh.computeWorldMatrix(true);
  93925. return mesh;
  93926. };
  93927. return CSG;
  93928. }());
  93929. BABYLON.CSG = CSG;
  93930. })(BABYLON || (BABYLON = {}));
  93931. //# sourceMappingURL=babylon.csg.js.map
  93932. var BABYLON;
  93933. (function (BABYLON) {
  93934. /**
  93935. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93936. * It controls one of the indiviual texture used in the effect.
  93937. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93938. */
  93939. var LensFlare = /** @class */ (function () {
  93940. /**
  93941. * Instantiates a new Lens Flare.
  93942. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93943. * It controls one of the indiviual texture used in the effect.
  93944. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93945. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  93946. * @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.
  93947. * @param color Define the lens color
  93948. * @param imgUrl Define the lens texture url
  93949. * @param system Define the `lensFlareSystem` this flare is part of
  93950. */
  93951. function LensFlare(
  93952. /**
  93953. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  93954. */
  93955. size,
  93956. /**
  93957. * 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.
  93958. */
  93959. position, color, imgUrl, system) {
  93960. this.size = size;
  93961. this.position = position;
  93962. /**
  93963. * Define the alpha mode to render this particular lens.
  93964. */
  93965. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  93966. this.color = color || new BABYLON.Color3(1, 1, 1);
  93967. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  93968. this._system = system;
  93969. system.lensFlares.push(this);
  93970. }
  93971. /**
  93972. * Creates a new Lens Flare.
  93973. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93974. * It controls one of the indiviual texture used in the effect.
  93975. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93976. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  93977. * @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.
  93978. * @param color Define the lens color
  93979. * @param imgUrl Define the lens texture url
  93980. * @param system Define the `lensFlareSystem` this flare is part of
  93981. * @returns The newly created Lens Flare
  93982. */
  93983. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  93984. return new LensFlare(size, position, color, imgUrl, system);
  93985. };
  93986. /**
  93987. * Dispose and release the lens flare with its associated resources.
  93988. */
  93989. LensFlare.prototype.dispose = function () {
  93990. if (this.texture) {
  93991. this.texture.dispose();
  93992. }
  93993. // Remove from scene
  93994. var index = this._system.lensFlares.indexOf(this);
  93995. this._system.lensFlares.splice(index, 1);
  93996. };
  93997. return LensFlare;
  93998. }());
  93999. BABYLON.LensFlare = LensFlare;
  94000. })(BABYLON || (BABYLON = {}));
  94001. //# sourceMappingURL=babylon.lensFlare.js.map
  94002. var BABYLON;
  94003. (function (BABYLON) {
  94004. // Adds the parser to the scene parsers.
  94005. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  94006. // Lens flares
  94007. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  94008. if (!container.lensFlareSystems) {
  94009. container.lensFlareSystems = new Array();
  94010. }
  94011. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  94012. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  94013. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  94014. container.lensFlareSystems.push(lf);
  94015. }
  94016. }
  94017. });
  94018. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  94019. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  94020. if (this.lensFlareSystems[index].name === name) {
  94021. return this.lensFlareSystems[index];
  94022. }
  94023. }
  94024. return null;
  94025. };
  94026. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  94027. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  94028. if (this.lensFlareSystems[index].id === id) {
  94029. return this.lensFlareSystems[index];
  94030. }
  94031. }
  94032. return null;
  94033. };
  94034. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  94035. var index = this.lensFlareSystems.indexOf(toRemove);
  94036. if (index !== -1) {
  94037. this.lensFlareSystems.splice(index, 1);
  94038. }
  94039. return index;
  94040. };
  94041. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  94042. this.lensFlareSystems.push(newLensFlareSystem);
  94043. };
  94044. /**
  94045. * Defines the lens flare scene component responsible to manage any lens flares
  94046. * in a given scene.
  94047. */
  94048. var LensFlareSystemSceneComponent = /** @class */ (function () {
  94049. /**
  94050. * Creates a new instance of the component for the given scene
  94051. * @param scene Defines the scene to register the component in
  94052. */
  94053. function LensFlareSystemSceneComponent(scene) {
  94054. /**
  94055. * The component name helpfull to identify the component in the list of scene components.
  94056. */
  94057. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  94058. this.scene = scene;
  94059. scene.lensFlareSystems = new Array();
  94060. }
  94061. /**
  94062. * Registers the component in a given scene
  94063. */
  94064. LensFlareSystemSceneComponent.prototype.register = function () {
  94065. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  94066. };
  94067. /**
  94068. * Rebuilds the elements related to this component in case of
  94069. * context lost for instance.
  94070. */
  94071. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  94072. // Nothing to do for lens flare
  94073. };
  94074. /**
  94075. * Adds all the element from the container to the scene
  94076. * @param container the container holding the elements
  94077. */
  94078. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  94079. var _this = this;
  94080. if (!container.lensFlareSystems) {
  94081. return;
  94082. }
  94083. container.lensFlareSystems.forEach(function (o) {
  94084. _this.scene.addLensFlareSystem(o);
  94085. });
  94086. };
  94087. /**
  94088. * Removes all the elements in the container from the scene
  94089. * @param container contains the elements to remove
  94090. */
  94091. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  94092. var _this = this;
  94093. if (!container.lensFlareSystems) {
  94094. return;
  94095. }
  94096. container.lensFlareSystems.forEach(function (o) {
  94097. _this.scene.removeLensFlareSystem(o);
  94098. });
  94099. };
  94100. /**
  94101. * Serializes the component data to the specified json object
  94102. * @param serializationObject The object to serialize to
  94103. */
  94104. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  94105. // Lens flares
  94106. serializationObject.lensFlareSystems = [];
  94107. var lensFlareSystems = this.scene.lensFlareSystems;
  94108. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  94109. var lensFlareSystem = lensFlareSystems_1[_i];
  94110. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  94111. }
  94112. };
  94113. /**
  94114. * Disposes the component and the associated ressources.
  94115. */
  94116. LensFlareSystemSceneComponent.prototype.dispose = function () {
  94117. var lensFlareSystems = this.scene.lensFlareSystems;
  94118. while (lensFlareSystems.length) {
  94119. lensFlareSystems[0].dispose();
  94120. }
  94121. };
  94122. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  94123. // Lens flares
  94124. if (this.scene.lensFlaresEnabled) {
  94125. var lensFlareSystems = this.scene.lensFlareSystems;
  94126. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  94127. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  94128. var lensFlareSystem = lensFlareSystems_2[_i];
  94129. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  94130. lensFlareSystem.render();
  94131. }
  94132. }
  94133. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  94134. }
  94135. };
  94136. return LensFlareSystemSceneComponent;
  94137. }());
  94138. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  94139. })(BABYLON || (BABYLON = {}));
  94140. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  94141. var BABYLON;
  94142. (function (BABYLON) {
  94143. /**
  94144. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  94145. * It is usually composed of several `BABYLON.lensFlare`.
  94146. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94147. */
  94148. var LensFlareSystem = /** @class */ (function () {
  94149. /**
  94150. * Instantiates a lens flare system.
  94151. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  94152. * It is usually composed of several `BABYLON.lensFlare`.
  94153. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94154. * @param name Define the name of the lens flare system in the scene
  94155. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  94156. * @param scene Define the scene the lens flare system belongs to
  94157. */
  94158. function LensFlareSystem(
  94159. /**
  94160. * Define the name of the lens flare system
  94161. */
  94162. name, emitter, scene) {
  94163. this.name = name;
  94164. /**
  94165. * List of lens flares used in this system.
  94166. */
  94167. this.lensFlares = new Array();
  94168. /**
  94169. * Define a limit from the border the lens flare can be visible.
  94170. */
  94171. this.borderLimit = 300;
  94172. /**
  94173. * Define a viewport border we do not want to see the lens flare in.
  94174. */
  94175. this.viewportBorder = 0;
  94176. /**
  94177. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  94178. */
  94179. this.layerMask = 0x0FFFFFFF;
  94180. this._vertexBuffers = {};
  94181. this._isEnabled = true;
  94182. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94183. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  94184. if (!component) {
  94185. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  94186. scene._addComponent(component);
  94187. }
  94188. this._emitter = emitter;
  94189. this.id = name;
  94190. scene.lensFlareSystems.push(this);
  94191. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  94192. var engine = scene.getEngine();
  94193. // VBO
  94194. var vertices = [];
  94195. vertices.push(1, 1);
  94196. vertices.push(-1, 1);
  94197. vertices.push(-1, -1);
  94198. vertices.push(1, -1);
  94199. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94200. // Indices
  94201. var indices = [];
  94202. indices.push(0);
  94203. indices.push(1);
  94204. indices.push(2);
  94205. indices.push(0);
  94206. indices.push(2);
  94207. indices.push(3);
  94208. this._indexBuffer = engine.createIndexBuffer(indices);
  94209. // Effects
  94210. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  94211. }
  94212. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  94213. /**
  94214. * Define if the lens flare system is enabled.
  94215. */
  94216. get: function () {
  94217. return this._isEnabled;
  94218. },
  94219. set: function (value) {
  94220. this._isEnabled = value;
  94221. },
  94222. enumerable: true,
  94223. configurable: true
  94224. });
  94225. /**
  94226. * Get the scene the effects belongs to.
  94227. * @returns the scene holding the lens flare system
  94228. */
  94229. LensFlareSystem.prototype.getScene = function () {
  94230. return this._scene;
  94231. };
  94232. /**
  94233. * Get the emitter of the lens flare system.
  94234. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  94235. * @returns the emitter of the lens flare system
  94236. */
  94237. LensFlareSystem.prototype.getEmitter = function () {
  94238. return this._emitter;
  94239. };
  94240. /**
  94241. * Set the emitter of the lens flare system.
  94242. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  94243. * @param newEmitter Define the new emitter of the system
  94244. */
  94245. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  94246. this._emitter = newEmitter;
  94247. };
  94248. /**
  94249. * Get the lens flare system emitter position.
  94250. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  94251. * @returns the position
  94252. */
  94253. LensFlareSystem.prototype.getEmitterPosition = function () {
  94254. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  94255. };
  94256. /**
  94257. * @hidden
  94258. */
  94259. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  94260. var position = this.getEmitterPosition();
  94261. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  94262. this._positionX = position.x;
  94263. this._positionY = position.y;
  94264. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  94265. if (this.viewportBorder > 0) {
  94266. globalViewport.x -= this.viewportBorder;
  94267. globalViewport.y -= this.viewportBorder;
  94268. globalViewport.width += this.viewportBorder * 2;
  94269. globalViewport.height += this.viewportBorder * 2;
  94270. position.x += this.viewportBorder;
  94271. position.y += this.viewportBorder;
  94272. this._positionX += this.viewportBorder;
  94273. this._positionY += this.viewportBorder;
  94274. }
  94275. if (position.z > 0) {
  94276. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  94277. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  94278. return true;
  94279. }
  94280. }
  94281. return true;
  94282. }
  94283. return false;
  94284. };
  94285. /** @hidden */
  94286. LensFlareSystem.prototype._isVisible = function () {
  94287. if (!this._isEnabled || !this._scene.activeCamera) {
  94288. return false;
  94289. }
  94290. var emitterPosition = this.getEmitterPosition();
  94291. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  94292. var distance = direction.length();
  94293. direction.normalize();
  94294. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  94295. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  94296. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  94297. };
  94298. /**
  94299. * @hidden
  94300. */
  94301. LensFlareSystem.prototype.render = function () {
  94302. if (!this._effect.isReady() || !this._scene.activeCamera) {
  94303. return false;
  94304. }
  94305. var engine = this._scene.getEngine();
  94306. var viewport = this._scene.activeCamera.viewport;
  94307. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  94308. // Position
  94309. if (!this.computeEffectivePosition(globalViewport)) {
  94310. return false;
  94311. }
  94312. // Visibility
  94313. if (!this._isVisible()) {
  94314. return false;
  94315. }
  94316. // Intensity
  94317. var awayX;
  94318. var awayY;
  94319. if (this._positionX < this.borderLimit + globalViewport.x) {
  94320. awayX = this.borderLimit + globalViewport.x - this._positionX;
  94321. }
  94322. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  94323. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  94324. }
  94325. else {
  94326. awayX = 0;
  94327. }
  94328. if (this._positionY < this.borderLimit + globalViewport.y) {
  94329. awayY = this.borderLimit + globalViewport.y - this._positionY;
  94330. }
  94331. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  94332. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  94333. }
  94334. else {
  94335. awayY = 0;
  94336. }
  94337. var away = (awayX > awayY) ? awayX : awayY;
  94338. away -= this.viewportBorder;
  94339. if (away > this.borderLimit) {
  94340. away = this.borderLimit;
  94341. }
  94342. var intensity = 1.0 - (away / this.borderLimit);
  94343. if (intensity < 0) {
  94344. return false;
  94345. }
  94346. if (intensity > 1.0) {
  94347. intensity = 1.0;
  94348. }
  94349. if (this.viewportBorder > 0) {
  94350. globalViewport.x += this.viewportBorder;
  94351. globalViewport.y += this.viewportBorder;
  94352. globalViewport.width -= this.viewportBorder * 2;
  94353. globalViewport.height -= this.viewportBorder * 2;
  94354. this._positionX -= this.viewportBorder;
  94355. this._positionY -= this.viewportBorder;
  94356. }
  94357. // Position
  94358. var centerX = globalViewport.x + globalViewport.width / 2;
  94359. var centerY = globalViewport.y + globalViewport.height / 2;
  94360. var distX = centerX - this._positionX;
  94361. var distY = centerY - this._positionY;
  94362. // Effects
  94363. engine.enableEffect(this._effect);
  94364. engine.setState(false);
  94365. engine.setDepthBuffer(false);
  94366. // VBOs
  94367. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  94368. // Flares
  94369. for (var index = 0; index < this.lensFlares.length; index++) {
  94370. var flare = this.lensFlares[index];
  94371. engine.setAlphaMode(flare.alphaMode);
  94372. var x = centerX - (distX * flare.position);
  94373. var y = centerY - (distY * flare.position);
  94374. var cw = flare.size;
  94375. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  94376. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  94377. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  94378. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  94379. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  94380. // Texture
  94381. this._effect.setTexture("textureSampler", flare.texture);
  94382. // Color
  94383. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  94384. // Draw order
  94385. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94386. }
  94387. engine.setDepthBuffer(true);
  94388. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94389. return true;
  94390. };
  94391. /**
  94392. * Dispose and release the lens flare with its associated resources.
  94393. */
  94394. LensFlareSystem.prototype.dispose = function () {
  94395. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94396. if (vertexBuffer) {
  94397. vertexBuffer.dispose();
  94398. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94399. }
  94400. if (this._indexBuffer) {
  94401. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94402. this._indexBuffer = null;
  94403. }
  94404. while (this.lensFlares.length) {
  94405. this.lensFlares[0].dispose();
  94406. }
  94407. // Remove from scene
  94408. var index = this._scene.lensFlareSystems.indexOf(this);
  94409. this._scene.lensFlareSystems.splice(index, 1);
  94410. };
  94411. /**
  94412. * Parse a lens flare system from a JSON repressentation
  94413. * @param parsedLensFlareSystem Define the JSON to parse
  94414. * @param scene Define the scene the parsed system should be instantiated in
  94415. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  94416. * @returns the parsed system
  94417. */
  94418. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  94419. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  94420. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  94421. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  94422. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  94423. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  94424. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  94425. var parsedFlare = parsedLensFlareSystem.flares[index];
  94426. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  94427. }
  94428. return lensFlareSystem;
  94429. };
  94430. /**
  94431. * Serialize the current Lens Flare System into a JSON representation.
  94432. * @returns the serialized JSON
  94433. */
  94434. LensFlareSystem.prototype.serialize = function () {
  94435. var serializationObject = {};
  94436. serializationObject.id = this.id;
  94437. serializationObject.name = this.name;
  94438. serializationObject.emitterId = this.getEmitter().id;
  94439. serializationObject.borderLimit = this.borderLimit;
  94440. serializationObject.flares = [];
  94441. for (var index = 0; index < this.lensFlares.length; index++) {
  94442. var flare = this.lensFlares[index];
  94443. serializationObject.flares.push({
  94444. size: flare.size,
  94445. position: flare.position,
  94446. color: flare.color.asArray(),
  94447. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  94448. });
  94449. }
  94450. return serializationObject;
  94451. };
  94452. return LensFlareSystem;
  94453. }());
  94454. BABYLON.LensFlareSystem = LensFlareSystem;
  94455. })(BABYLON || (BABYLON = {}));
  94456. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  94457. var BABYLON;
  94458. (function (BABYLON) {
  94459. /**
  94460. * This is a holder class for the physics joint created by the physics plugin
  94461. * It holds a set of functions to control the underlying joint
  94462. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94463. */
  94464. var PhysicsJoint = /** @class */ (function () {
  94465. /**
  94466. * Initializes the physics joint
  94467. * @param type The type of the physics joint
  94468. * @param jointData The data for the physics joint
  94469. */
  94470. function PhysicsJoint(
  94471. /**
  94472. * The type of the physics joint
  94473. */
  94474. type,
  94475. /**
  94476. * The data for the physics joint
  94477. */
  94478. jointData) {
  94479. this.type = type;
  94480. this.jointData = jointData;
  94481. jointData.nativeParams = jointData.nativeParams || {};
  94482. }
  94483. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  94484. /**
  94485. * Gets the physics joint
  94486. */
  94487. get: function () {
  94488. return this._physicsJoint;
  94489. },
  94490. /**
  94491. * Sets the physics joint
  94492. */
  94493. set: function (newJoint) {
  94494. if (this._physicsJoint) {
  94495. //remove from the wolrd
  94496. }
  94497. this._physicsJoint = newJoint;
  94498. },
  94499. enumerable: true,
  94500. configurable: true
  94501. });
  94502. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  94503. /**
  94504. * Sets the physics plugin
  94505. */
  94506. set: function (physicsPlugin) {
  94507. this._physicsPlugin = physicsPlugin;
  94508. },
  94509. enumerable: true,
  94510. configurable: true
  94511. });
  94512. /**
  94513. * Execute a function that is physics-plugin specific.
  94514. * @param {Function} func the function that will be executed.
  94515. * It accepts two parameters: the physics world and the physics joint
  94516. */
  94517. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  94518. func(this._physicsPlugin.world, this._physicsJoint);
  94519. };
  94520. //TODO check if the native joints are the same
  94521. //Joint Types
  94522. /**
  94523. * Distance-Joint type
  94524. */
  94525. PhysicsJoint.DistanceJoint = 0;
  94526. /**
  94527. * Hinge-Joint type
  94528. */
  94529. PhysicsJoint.HingeJoint = 1;
  94530. /**
  94531. * Ball-and-Socket joint type
  94532. */
  94533. PhysicsJoint.BallAndSocketJoint = 2;
  94534. /**
  94535. * Wheel-Joint type
  94536. */
  94537. PhysicsJoint.WheelJoint = 3;
  94538. /**
  94539. * Slider-Joint type
  94540. */
  94541. PhysicsJoint.SliderJoint = 4;
  94542. //OIMO
  94543. /**
  94544. * Prismatic-Joint type
  94545. */
  94546. PhysicsJoint.PrismaticJoint = 5;
  94547. //
  94548. /**
  94549. * Universal-Joint type
  94550. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  94551. */
  94552. PhysicsJoint.UniversalJoint = 6;
  94553. /**
  94554. * Hinge-Joint 2 type
  94555. */
  94556. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  94557. //Cannon
  94558. /**
  94559. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  94560. */
  94561. PhysicsJoint.PointToPointJoint = 8;
  94562. //Cannon only at the moment
  94563. /**
  94564. * Spring-Joint type
  94565. */
  94566. PhysicsJoint.SpringJoint = 9;
  94567. /**
  94568. * Lock-Joint type
  94569. */
  94570. PhysicsJoint.LockJoint = 10;
  94571. return PhysicsJoint;
  94572. }());
  94573. BABYLON.PhysicsJoint = PhysicsJoint;
  94574. /**
  94575. * A class representing a physics distance joint
  94576. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94577. */
  94578. var DistanceJoint = /** @class */ (function (_super) {
  94579. __extends(DistanceJoint, _super);
  94580. /**
  94581. *
  94582. * @param jointData The data for the Distance-Joint
  94583. */
  94584. function DistanceJoint(jointData) {
  94585. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  94586. }
  94587. /**
  94588. * Update the predefined distance.
  94589. * @param maxDistance The maximum preferred distance
  94590. * @param minDistance The minimum preferred distance
  94591. */
  94592. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  94593. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  94594. };
  94595. return DistanceJoint;
  94596. }(PhysicsJoint));
  94597. BABYLON.DistanceJoint = DistanceJoint;
  94598. /**
  94599. * Represents a Motor-Enabled Joint
  94600. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94601. */
  94602. var MotorEnabledJoint = /** @class */ (function (_super) {
  94603. __extends(MotorEnabledJoint, _super);
  94604. /**
  94605. * Initializes the Motor-Enabled Joint
  94606. * @param type The type of the joint
  94607. * @param jointData The physica joint data for the joint
  94608. */
  94609. function MotorEnabledJoint(type, jointData) {
  94610. return _super.call(this, type, jointData) || this;
  94611. }
  94612. /**
  94613. * Set the motor values.
  94614. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94615. * @param force the force to apply
  94616. * @param maxForce max force for this motor.
  94617. */
  94618. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  94619. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94620. };
  94621. /**
  94622. * Set the motor's limits.
  94623. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94624. * @param upperLimit The upper limit of the motor
  94625. * @param lowerLimit The lower limit of the motor
  94626. */
  94627. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94628. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94629. };
  94630. return MotorEnabledJoint;
  94631. }(PhysicsJoint));
  94632. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  94633. /**
  94634. * This class represents a single physics Hinge-Joint
  94635. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94636. */
  94637. var HingeJoint = /** @class */ (function (_super) {
  94638. __extends(HingeJoint, _super);
  94639. /**
  94640. * Initializes the Hinge-Joint
  94641. * @param jointData The joint data for the Hinge-Joint
  94642. */
  94643. function HingeJoint(jointData) {
  94644. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  94645. }
  94646. /**
  94647. * Set the motor values.
  94648. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94649. * @param {number} force the force to apply
  94650. * @param {number} maxForce max force for this motor.
  94651. */
  94652. HingeJoint.prototype.setMotor = function (force, maxForce) {
  94653. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94654. };
  94655. /**
  94656. * Set the motor's limits.
  94657. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94658. * @param upperLimit The upper limit of the motor
  94659. * @param lowerLimit The lower limit of the motor
  94660. */
  94661. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94662. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94663. };
  94664. return HingeJoint;
  94665. }(MotorEnabledJoint));
  94666. BABYLON.HingeJoint = HingeJoint;
  94667. /**
  94668. * This class represents a dual hinge physics joint (same as wheel joint)
  94669. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94670. */
  94671. var Hinge2Joint = /** @class */ (function (_super) {
  94672. __extends(Hinge2Joint, _super);
  94673. /**
  94674. * Initializes the Hinge2-Joint
  94675. * @param jointData The joint data for the Hinge2-Joint
  94676. */
  94677. function Hinge2Joint(jointData) {
  94678. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  94679. }
  94680. /**
  94681. * Set the motor values.
  94682. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94683. * @param {number} force the force to apply
  94684. * @param {number} maxForce max force for this motor.
  94685. * @param {motorIndex} the motor's index, 0 or 1.
  94686. */
  94687. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  94688. if (motorIndex === void 0) { motorIndex = 0; }
  94689. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  94690. };
  94691. /**
  94692. * Set the motor limits.
  94693. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94694. * @param {number} upperLimit the upper limit
  94695. * @param {number} lowerLimit lower limit
  94696. * @param {motorIndex} the motor's index, 0 or 1.
  94697. */
  94698. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  94699. if (motorIndex === void 0) { motorIndex = 0; }
  94700. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  94701. };
  94702. return Hinge2Joint;
  94703. }(MotorEnabledJoint));
  94704. BABYLON.Hinge2Joint = Hinge2Joint;
  94705. })(BABYLON || (BABYLON = {}));
  94706. //# sourceMappingURL=babylon.physicsJoint.js.map
  94707. var BABYLON;
  94708. (function (BABYLON) {
  94709. /**
  94710. * Represents a physics imposter
  94711. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94712. */
  94713. var PhysicsImpostor = /** @class */ (function () {
  94714. /**
  94715. * Initializes the physics imposter
  94716. * @param object The physics-enabled object used as the physics imposter
  94717. * @param type The type of the physics imposter
  94718. * @param _options The options for the physics imposter
  94719. * @param _scene The Babylon scene
  94720. */
  94721. function PhysicsImpostor(
  94722. /**
  94723. * The physics-enabled object used as the physics imposter
  94724. */
  94725. object,
  94726. /**
  94727. * The type of the physics imposter
  94728. */
  94729. type, _options, _scene) {
  94730. if (_options === void 0) { _options = { mass: 0 }; }
  94731. var _this = this;
  94732. this.object = object;
  94733. this.type = type;
  94734. this._options = _options;
  94735. this._scene = _scene;
  94736. this._bodyUpdateRequired = false;
  94737. this._onBeforePhysicsStepCallbacks = new Array();
  94738. this._onAfterPhysicsStepCallbacks = new Array();
  94739. this._onPhysicsCollideCallbacks = [];
  94740. this._deltaPosition = BABYLON.Vector3.Zero();
  94741. this._isDisposed = false;
  94742. //temp variables for parent rotation calculations
  94743. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  94744. this._tmpQuat = new BABYLON.Quaternion();
  94745. this._tmpQuat2 = new BABYLON.Quaternion();
  94746. /**
  94747. * this function is executed by the physics engine.
  94748. */
  94749. this.beforeStep = function () {
  94750. if (!_this._physicsEngine) {
  94751. return;
  94752. }
  94753. _this.object.translate(_this._deltaPosition, -1);
  94754. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  94755. _this.object.computeWorldMatrix(false);
  94756. if (_this.object.parent && _this.object.rotationQuaternion) {
  94757. _this.getParentsRotation();
  94758. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  94759. }
  94760. else {
  94761. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  94762. }
  94763. if (!_this._options.disableBidirectionalTransformation) {
  94764. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  94765. }
  94766. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  94767. func(_this);
  94768. });
  94769. };
  94770. /**
  94771. * this function is executed by the physics engine
  94772. */
  94773. this.afterStep = function () {
  94774. if (!_this._physicsEngine) {
  94775. return;
  94776. }
  94777. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  94778. func(_this);
  94779. });
  94780. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  94781. // object has now its world rotation. needs to be converted to local.
  94782. if (_this.object.parent && _this.object.rotationQuaternion) {
  94783. _this.getParentsRotation();
  94784. _this._tmpQuat.conjugateInPlace();
  94785. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  94786. }
  94787. // take the position set and make it the absolute position of this object.
  94788. _this.object.setAbsolutePosition(_this.object.position);
  94789. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  94790. _this.object.translate(_this._deltaPosition, 1);
  94791. };
  94792. /**
  94793. * Legacy collision detection event support
  94794. */
  94795. this.onCollideEvent = null;
  94796. /**
  94797. * event and body object due to cannon's event-based architecture.
  94798. */
  94799. this.onCollide = function (e) {
  94800. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  94801. return;
  94802. }
  94803. if (!_this._physicsEngine) {
  94804. return;
  94805. }
  94806. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  94807. if (otherImpostor) {
  94808. // Legacy collision detection event support
  94809. if (_this.onCollideEvent) {
  94810. _this.onCollideEvent(_this, otherImpostor);
  94811. }
  94812. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  94813. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  94814. }).forEach(function (obj) {
  94815. obj.callback(_this, otherImpostor);
  94816. });
  94817. }
  94818. };
  94819. //sanity check!
  94820. if (!this.object) {
  94821. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  94822. return;
  94823. }
  94824. //legacy support for old syntax.
  94825. if (!this._scene && object.getScene) {
  94826. this._scene = object.getScene();
  94827. }
  94828. if (!this._scene) {
  94829. return;
  94830. }
  94831. this._physicsEngine = this._scene.getPhysicsEngine();
  94832. if (!this._physicsEngine) {
  94833. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  94834. }
  94835. else {
  94836. //set the object's quaternion, if not set
  94837. if (!this.object.rotationQuaternion) {
  94838. if (this.object.rotation) {
  94839. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  94840. }
  94841. else {
  94842. this.object.rotationQuaternion = new BABYLON.Quaternion();
  94843. }
  94844. }
  94845. //default options params
  94846. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  94847. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  94848. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  94849. this._joints = [];
  94850. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  94851. if (!this.object.parent || this._options.ignoreParent) {
  94852. this._init();
  94853. }
  94854. else if (this.object.parent.physicsImpostor) {
  94855. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  94856. }
  94857. }
  94858. }
  94859. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  94860. /**
  94861. * Specifies if the physics imposter is disposed
  94862. */
  94863. get: function () {
  94864. return this._isDisposed;
  94865. },
  94866. enumerable: true,
  94867. configurable: true
  94868. });
  94869. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  94870. /**
  94871. * Gets the mass of the physics imposter
  94872. */
  94873. get: function () {
  94874. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  94875. },
  94876. set: function (value) {
  94877. this.setMass(value);
  94878. },
  94879. enumerable: true,
  94880. configurable: true
  94881. });
  94882. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  94883. /**
  94884. * Gets the coefficient of friction
  94885. */
  94886. get: function () {
  94887. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  94888. },
  94889. /**
  94890. * Sets the coefficient of friction
  94891. */
  94892. set: function (value) {
  94893. if (!this._physicsEngine) {
  94894. return;
  94895. }
  94896. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  94897. },
  94898. enumerable: true,
  94899. configurable: true
  94900. });
  94901. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  94902. /**
  94903. * Gets the coefficient of restitution
  94904. */
  94905. get: function () {
  94906. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  94907. },
  94908. /**
  94909. * Sets the coefficient of restitution
  94910. */
  94911. set: function (value) {
  94912. if (!this._physicsEngine) {
  94913. return;
  94914. }
  94915. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  94916. },
  94917. enumerable: true,
  94918. configurable: true
  94919. });
  94920. /**
  94921. * This function will completly initialize this impostor.
  94922. * It will create a new body - but only if this mesh has no parent.
  94923. * If it has, this impostor will not be used other than to define the impostor
  94924. * of the child mesh.
  94925. * @hidden
  94926. */
  94927. PhysicsImpostor.prototype._init = function () {
  94928. if (!this._physicsEngine) {
  94929. return;
  94930. }
  94931. this._physicsEngine.removeImpostor(this);
  94932. this.physicsBody = null;
  94933. this._parent = this._parent || this._getPhysicsParent();
  94934. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  94935. this._physicsEngine.addImpostor(this);
  94936. }
  94937. };
  94938. PhysicsImpostor.prototype._getPhysicsParent = function () {
  94939. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  94940. var parentMesh = this.object.parent;
  94941. return parentMesh.physicsImpostor;
  94942. }
  94943. return null;
  94944. };
  94945. /**
  94946. * Should a new body be generated.
  94947. * @returns boolean specifying if body initialization is required
  94948. */
  94949. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  94950. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  94951. };
  94952. /**
  94953. * Sets the updated scaling
  94954. * @param updated Specifies if the scaling is updated
  94955. */
  94956. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  94957. this.forceUpdate();
  94958. };
  94959. /**
  94960. * Force a regeneration of this or the parent's impostor's body.
  94961. * Use under cautious - This will remove all joints already implemented.
  94962. */
  94963. PhysicsImpostor.prototype.forceUpdate = function () {
  94964. this._init();
  94965. if (this.parent && !this._options.ignoreParent) {
  94966. this.parent.forceUpdate();
  94967. }
  94968. };
  94969. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  94970. /*public get mesh(): AbstractMesh {
  94971. return this._mesh;
  94972. }*/
  94973. /**
  94974. * Gets the body that holds this impostor. Either its own, or its parent.
  94975. */
  94976. get: function () {
  94977. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  94978. },
  94979. /**
  94980. * Set the physics body. Used mainly by the physics engine/plugin
  94981. */
  94982. set: function (physicsBody) {
  94983. if (this._physicsBody && this._physicsEngine) {
  94984. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  94985. }
  94986. this._physicsBody = physicsBody;
  94987. this.resetUpdateFlags();
  94988. },
  94989. enumerable: true,
  94990. configurable: true
  94991. });
  94992. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  94993. /**
  94994. * Get the parent of the physics imposter
  94995. * @returns Physics imposter or null
  94996. */
  94997. get: function () {
  94998. return !this._options.ignoreParent && this._parent ? this._parent : null;
  94999. },
  95000. /**
  95001. * Sets the parent of the physics imposter
  95002. */
  95003. set: function (value) {
  95004. this._parent = value;
  95005. },
  95006. enumerable: true,
  95007. configurable: true
  95008. });
  95009. /**
  95010. * Resets the update flags
  95011. */
  95012. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  95013. this._bodyUpdateRequired = false;
  95014. };
  95015. /**
  95016. * Gets the object extend size
  95017. * @returns the object extend size
  95018. */
  95019. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  95020. if (this.object.getBoundingInfo) {
  95021. var q = this.object.rotationQuaternion;
  95022. //reset rotation
  95023. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  95024. //calculate the world matrix with no rotation
  95025. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  95026. var boundingInfo = this.object.getBoundingInfo();
  95027. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  95028. //bring back the rotation
  95029. this.object.rotationQuaternion = q;
  95030. //calculate the world matrix with the new rotation
  95031. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  95032. return size;
  95033. }
  95034. else {
  95035. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  95036. }
  95037. };
  95038. /**
  95039. * Gets the object center
  95040. * @returns The object center
  95041. */
  95042. PhysicsImpostor.prototype.getObjectCenter = function () {
  95043. if (this.object.getBoundingInfo) {
  95044. var boundingInfo = this.object.getBoundingInfo();
  95045. return boundingInfo.boundingBox.centerWorld;
  95046. }
  95047. else {
  95048. return this.object.position;
  95049. }
  95050. };
  95051. /**
  95052. * Get a specific parametes from the options parameter
  95053. * @param paramName The object parameter name
  95054. * @returns The object parameter
  95055. */
  95056. PhysicsImpostor.prototype.getParam = function (paramName) {
  95057. return this._options[paramName];
  95058. };
  95059. /**
  95060. * Sets a specific parameter in the options given to the physics plugin
  95061. * @param paramName The parameter name
  95062. * @param value The value of the parameter
  95063. */
  95064. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  95065. this._options[paramName] = value;
  95066. this._bodyUpdateRequired = true;
  95067. };
  95068. /**
  95069. * Specifically change the body's mass option. Won't recreate the physics body object
  95070. * @param mass The mass of the physics imposter
  95071. */
  95072. PhysicsImpostor.prototype.setMass = function (mass) {
  95073. if (this.getParam("mass") !== mass) {
  95074. this.setParam("mass", mass);
  95075. }
  95076. if (this._physicsEngine) {
  95077. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  95078. }
  95079. };
  95080. /**
  95081. * Gets the linear velocity
  95082. * @returns linear velocity or null
  95083. */
  95084. PhysicsImpostor.prototype.getLinearVelocity = function () {
  95085. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  95086. };
  95087. /**
  95088. * Sets the linear velocity
  95089. * @param velocity linear velocity or null
  95090. */
  95091. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  95092. if (this._physicsEngine) {
  95093. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  95094. }
  95095. };
  95096. /**
  95097. * Gets the angular velocity
  95098. * @returns angular velocity or null
  95099. */
  95100. PhysicsImpostor.prototype.getAngularVelocity = function () {
  95101. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  95102. };
  95103. /**
  95104. * Sets the angular velocity
  95105. * @param velocity The velocity or null
  95106. */
  95107. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  95108. if (this._physicsEngine) {
  95109. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  95110. }
  95111. };
  95112. /**
  95113. * Execute a function with the physics plugin native code
  95114. * Provide a function the will have two variables - the world object and the physics body object
  95115. * @param func The function to execute with the physics plugin native code
  95116. */
  95117. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  95118. if (this._physicsEngine) {
  95119. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  95120. }
  95121. };
  95122. /**
  95123. * Register a function that will be executed before the physics world is stepping forward
  95124. * @param func The function to execute before the physics world is stepped forward
  95125. */
  95126. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  95127. this._onBeforePhysicsStepCallbacks.push(func);
  95128. };
  95129. /**
  95130. * Unregister a function that will be executed before the physics world is stepping forward
  95131. * @param func The function to execute before the physics world is stepped forward
  95132. */
  95133. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  95134. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  95135. if (index > -1) {
  95136. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  95137. }
  95138. else {
  95139. BABYLON.Tools.Warn("Function to remove was not found");
  95140. }
  95141. };
  95142. /**
  95143. * Register a function that will be executed after the physics step
  95144. * @param func The function to execute after physics step
  95145. */
  95146. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  95147. this._onAfterPhysicsStepCallbacks.push(func);
  95148. };
  95149. /**
  95150. * Unregisters a function that will be executed after the physics step
  95151. * @param func The function to execute after physics step
  95152. */
  95153. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  95154. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  95155. if (index > -1) {
  95156. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  95157. }
  95158. else {
  95159. BABYLON.Tools.Warn("Function to remove was not found");
  95160. }
  95161. };
  95162. /**
  95163. * register a function that will be executed when this impostor collides against a different body
  95164. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  95165. * @param func Callback that is executed on collision
  95166. */
  95167. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  95168. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  95169. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  95170. };
  95171. /**
  95172. * Unregisters the physics imposter on contact
  95173. * @param collideAgainst The physics object to collide against
  95174. * @param func Callback to execute on collision
  95175. */
  95176. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  95177. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  95178. var index = -1;
  95179. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  95180. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  95181. // chcek the arrays match
  95182. var sameList = cbDef.otherImpostors.every(function (impostor) {
  95183. return collidedAgainstList.indexOf(impostor) > -1;
  95184. });
  95185. if (sameList) {
  95186. index = idx;
  95187. }
  95188. return sameList;
  95189. }
  95190. return false;
  95191. });
  95192. if (found) {
  95193. this._onPhysicsCollideCallbacks.splice(index, 1);
  95194. }
  95195. else {
  95196. BABYLON.Tools.Warn("Function to remove was not found");
  95197. }
  95198. };
  95199. /**
  95200. * Get the parent rotation
  95201. * @returns The parent rotation
  95202. */
  95203. PhysicsImpostor.prototype.getParentsRotation = function () {
  95204. var parent = this.object.parent;
  95205. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  95206. while (parent) {
  95207. if (parent.rotationQuaternion) {
  95208. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  95209. }
  95210. else {
  95211. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  95212. }
  95213. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  95214. parent = parent.parent;
  95215. }
  95216. return this._tmpQuat;
  95217. };
  95218. /**
  95219. * Apply a force
  95220. * @param force The force to apply
  95221. * @param contactPoint The contact point for the force
  95222. * @returns The physics imposter
  95223. */
  95224. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  95225. if (this._physicsEngine) {
  95226. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  95227. }
  95228. return this;
  95229. };
  95230. /**
  95231. * Apply an impulse
  95232. * @param force The impulse force
  95233. * @param contactPoint The contact point for the impulse force
  95234. * @returns The physics imposter
  95235. */
  95236. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  95237. if (this._physicsEngine) {
  95238. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  95239. }
  95240. return this;
  95241. };
  95242. /**
  95243. * A help function to create a joint
  95244. * @param otherImpostor A physics imposter used to create a joint
  95245. * @param jointType The type of joint
  95246. * @param jointData The data for the joint
  95247. * @returns The physics imposter
  95248. */
  95249. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  95250. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  95251. this.addJoint(otherImpostor, joint);
  95252. return this;
  95253. };
  95254. /**
  95255. * Add a joint to this impostor with a different impostor
  95256. * @param otherImpostor A physics imposter used to add a joint
  95257. * @param joint The joint to add
  95258. * @returns The physics imposter
  95259. */
  95260. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  95261. this._joints.push({
  95262. otherImpostor: otherImpostor,
  95263. joint: joint
  95264. });
  95265. if (this._physicsEngine) {
  95266. this._physicsEngine.addJoint(this, otherImpostor, joint);
  95267. }
  95268. return this;
  95269. };
  95270. /**
  95271. * Will keep this body still, in a sleep mode.
  95272. * @returns the physics imposter
  95273. */
  95274. PhysicsImpostor.prototype.sleep = function () {
  95275. if (this._physicsEngine) {
  95276. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  95277. }
  95278. return this;
  95279. };
  95280. /**
  95281. * Wake the body up.
  95282. * @returns The physics imposter
  95283. */
  95284. PhysicsImpostor.prototype.wakeUp = function () {
  95285. if (this._physicsEngine) {
  95286. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  95287. }
  95288. return this;
  95289. };
  95290. /**
  95291. * Clones the physics imposter
  95292. * @param newObject The physics imposter clones to this physics-enabled object
  95293. * @returns A nullable physics imposter
  95294. */
  95295. PhysicsImpostor.prototype.clone = function (newObject) {
  95296. if (!newObject) {
  95297. return null;
  95298. }
  95299. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  95300. };
  95301. /**
  95302. * Disposes the physics imposter
  95303. */
  95304. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  95305. var _this = this;
  95306. //no dispose if no physics engine is available.
  95307. if (!this._physicsEngine) {
  95308. return;
  95309. }
  95310. this._joints.forEach(function (j) {
  95311. if (_this._physicsEngine) {
  95312. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  95313. }
  95314. });
  95315. //dispose the physics body
  95316. this._physicsEngine.removeImpostor(this);
  95317. if (this.parent) {
  95318. this.parent.forceUpdate();
  95319. }
  95320. else {
  95321. /*this._object.getChildMeshes().forEach(function(mesh) {
  95322. if (mesh.physicsImpostor) {
  95323. if (disposeChildren) {
  95324. mesh.physicsImpostor.dispose();
  95325. mesh.physicsImpostor = null;
  95326. }
  95327. }
  95328. })*/
  95329. }
  95330. this._isDisposed = true;
  95331. };
  95332. /**
  95333. * Sets the delta position
  95334. * @param position The delta position amount
  95335. */
  95336. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  95337. this._deltaPosition.copyFrom(position);
  95338. };
  95339. /**
  95340. * Sets the delta rotation
  95341. * @param rotation The delta rotation amount
  95342. */
  95343. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  95344. if (!this._deltaRotation) {
  95345. this._deltaRotation = new BABYLON.Quaternion();
  95346. }
  95347. this._deltaRotation.copyFrom(rotation);
  95348. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  95349. };
  95350. /**
  95351. * Gets the box size of the physics imposter and stores the result in the input parameter
  95352. * @param result Stores the box size
  95353. * @returns The physics imposter
  95354. */
  95355. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  95356. if (this._physicsEngine) {
  95357. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  95358. }
  95359. return this;
  95360. };
  95361. /**
  95362. * Gets the radius of the physics imposter
  95363. * @returns Radius of the physics imposter
  95364. */
  95365. PhysicsImpostor.prototype.getRadius = function () {
  95366. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  95367. };
  95368. /**
  95369. * Sync a bone with this impostor
  95370. * @param bone The bone to sync to the impostor.
  95371. * @param boneMesh The mesh that the bone is influencing.
  95372. * @param jointPivot The pivot of the joint / bone in local space.
  95373. * @param distToJoint Optional distance from the impostor to the joint.
  95374. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95375. */
  95376. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  95377. var tempVec = PhysicsImpostor._tmpVecs[0];
  95378. var mesh = this.object;
  95379. if (mesh.rotationQuaternion) {
  95380. if (adjustRotation) {
  95381. var tempQuat = PhysicsImpostor._tmpQuat;
  95382. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  95383. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  95384. }
  95385. else {
  95386. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  95387. }
  95388. }
  95389. tempVec.x = 0;
  95390. tempVec.y = 0;
  95391. tempVec.z = 0;
  95392. if (jointPivot) {
  95393. tempVec.x = jointPivot.x;
  95394. tempVec.y = jointPivot.y;
  95395. tempVec.z = jointPivot.z;
  95396. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  95397. if (distToJoint === undefined || distToJoint === null) {
  95398. distToJoint = jointPivot.length();
  95399. }
  95400. tempVec.x *= distToJoint;
  95401. tempVec.y *= distToJoint;
  95402. tempVec.z *= distToJoint;
  95403. }
  95404. if (bone.getParent()) {
  95405. tempVec.addInPlace(mesh.getAbsolutePosition());
  95406. bone.setAbsolutePosition(tempVec, boneMesh);
  95407. }
  95408. else {
  95409. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  95410. boneMesh.position.x -= tempVec.x;
  95411. boneMesh.position.y -= tempVec.y;
  95412. boneMesh.position.z -= tempVec.z;
  95413. }
  95414. };
  95415. /**
  95416. * Sync impostor to a bone
  95417. * @param bone The bone that the impostor will be synced to.
  95418. * @param boneMesh The mesh that the bone is influencing.
  95419. * @param jointPivot The pivot of the joint / bone in local space.
  95420. * @param distToJoint Optional distance from the impostor to the joint.
  95421. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95422. * @param boneAxis Optional vector3 axis the bone is aligned with
  95423. */
  95424. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  95425. var mesh = this.object;
  95426. if (mesh.rotationQuaternion) {
  95427. if (adjustRotation) {
  95428. var tempQuat = PhysicsImpostor._tmpQuat;
  95429. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  95430. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  95431. }
  95432. else {
  95433. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  95434. }
  95435. }
  95436. var pos = PhysicsImpostor._tmpVecs[0];
  95437. var boneDir = PhysicsImpostor._tmpVecs[1];
  95438. if (!boneAxis) {
  95439. boneAxis = PhysicsImpostor._tmpVecs[2];
  95440. boneAxis.x = 0;
  95441. boneAxis.y = 1;
  95442. boneAxis.z = 0;
  95443. }
  95444. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  95445. bone.getAbsolutePositionToRef(boneMesh, pos);
  95446. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  95447. distToJoint = jointPivot.length();
  95448. }
  95449. if (distToJoint !== undefined && distToJoint !== null) {
  95450. pos.x += boneDir.x * distToJoint;
  95451. pos.y += boneDir.y * distToJoint;
  95452. pos.z += boneDir.z * distToJoint;
  95453. }
  95454. mesh.setAbsolutePosition(pos);
  95455. };
  95456. /**
  95457. * The default object size of the imposter
  95458. */
  95459. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  95460. /**
  95461. * The identity quaternion of the imposter
  95462. */
  95463. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  95464. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  95465. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  95466. //Impostor types
  95467. /**
  95468. * No-Imposter type
  95469. */
  95470. PhysicsImpostor.NoImpostor = 0;
  95471. /**
  95472. * Sphere-Imposter type
  95473. */
  95474. PhysicsImpostor.SphereImpostor = 1;
  95475. /**
  95476. * Box-Imposter type
  95477. */
  95478. PhysicsImpostor.BoxImpostor = 2;
  95479. /**
  95480. * Plane-Imposter type
  95481. */
  95482. PhysicsImpostor.PlaneImpostor = 3;
  95483. /**
  95484. * Mesh-imposter type
  95485. */
  95486. PhysicsImpostor.MeshImpostor = 4;
  95487. /**
  95488. * Cylinder-Imposter type
  95489. */
  95490. PhysicsImpostor.CylinderImpostor = 7;
  95491. /**
  95492. * Particle-Imposter type
  95493. */
  95494. PhysicsImpostor.ParticleImpostor = 8;
  95495. /**
  95496. * Heightmap-Imposter type
  95497. */
  95498. PhysicsImpostor.HeightmapImpostor = 9;
  95499. return PhysicsImpostor;
  95500. }());
  95501. BABYLON.PhysicsImpostor = PhysicsImpostor;
  95502. })(BABYLON || (BABYLON = {}));
  95503. //# sourceMappingURL=babylon.physicsImpostor.js.map
  95504. var BABYLON;
  95505. (function (BABYLON) {
  95506. /**
  95507. * Class used to control physics engine
  95508. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95509. */
  95510. var PhysicsEngine = /** @class */ (function () {
  95511. /**
  95512. * Creates a new Physics Engine
  95513. * @param gravity defines the gravity vector used by the simulation
  95514. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  95515. */
  95516. function PhysicsEngine(gravity, _physicsPlugin) {
  95517. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  95518. this._physicsPlugin = _physicsPlugin;
  95519. this._impostors = [];
  95520. this._joints = [];
  95521. if (!this._physicsPlugin.isSupported()) {
  95522. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  95523. + "Please make sure it is included.");
  95524. }
  95525. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  95526. this.setGravity(gravity);
  95527. this.setTimeStep();
  95528. }
  95529. /**
  95530. * Sets the gravity vector used by the simulation
  95531. * @param gravity defines the gravity vector to use
  95532. */
  95533. PhysicsEngine.prototype.setGravity = function (gravity) {
  95534. this.gravity = gravity;
  95535. this._physicsPlugin.setGravity(this.gravity);
  95536. };
  95537. /**
  95538. * Set the time step of the physics engine.
  95539. * Default is 1/60.
  95540. * To slow it down, enter 1/600 for example.
  95541. * To speed it up, 1/30
  95542. * @param newTimeStep defines the new timestep to apply to this world.
  95543. */
  95544. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  95545. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  95546. this._physicsPlugin.setTimeStep(newTimeStep);
  95547. };
  95548. /**
  95549. * Get the time step of the physics engine.
  95550. * @returns the current time step
  95551. */
  95552. PhysicsEngine.prototype.getTimeStep = function () {
  95553. return this._physicsPlugin.getTimeStep();
  95554. };
  95555. /**
  95556. * Release all resources
  95557. */
  95558. PhysicsEngine.prototype.dispose = function () {
  95559. this._impostors.forEach(function (impostor) {
  95560. impostor.dispose();
  95561. });
  95562. this._physicsPlugin.dispose();
  95563. };
  95564. /**
  95565. * Gets the name of the current physics plugin
  95566. * @returns the name of the plugin
  95567. */
  95568. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  95569. return this._physicsPlugin.name;
  95570. };
  95571. /**
  95572. * Adding a new impostor for the impostor tracking.
  95573. * This will be done by the impostor itself.
  95574. * @param impostor the impostor to add
  95575. */
  95576. PhysicsEngine.prototype.addImpostor = function (impostor) {
  95577. impostor.uniqueId = this._impostors.push(impostor);
  95578. //if no parent, generate the body
  95579. if (!impostor.parent) {
  95580. this._physicsPlugin.generatePhysicsBody(impostor);
  95581. }
  95582. };
  95583. /**
  95584. * Remove an impostor from the engine.
  95585. * This impostor and its mesh will not longer be updated by the physics engine.
  95586. * @param impostor the impostor to remove
  95587. */
  95588. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  95589. var index = this._impostors.indexOf(impostor);
  95590. if (index > -1) {
  95591. var removed = this._impostors.splice(index, 1);
  95592. //Is it needed?
  95593. if (removed.length) {
  95594. //this will also remove it from the world.
  95595. removed[0].physicsBody = null;
  95596. }
  95597. }
  95598. };
  95599. /**
  95600. * Add a joint to the physics engine
  95601. * @param mainImpostor defines the main impostor to which the joint is added.
  95602. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  95603. * @param joint defines the joint that will connect both impostors.
  95604. */
  95605. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  95606. var impostorJoint = {
  95607. mainImpostor: mainImpostor,
  95608. connectedImpostor: connectedImpostor,
  95609. joint: joint
  95610. };
  95611. joint.physicsPlugin = this._physicsPlugin;
  95612. this._joints.push(impostorJoint);
  95613. this._physicsPlugin.generateJoint(impostorJoint);
  95614. };
  95615. /**
  95616. * Removes a joint from the simulation
  95617. * @param mainImpostor defines the impostor used with the joint
  95618. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  95619. * @param joint defines the joint to remove
  95620. */
  95621. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  95622. var matchingJoints = this._joints.filter(function (impostorJoint) {
  95623. return (impostorJoint.connectedImpostor === connectedImpostor
  95624. && impostorJoint.joint === joint
  95625. && impostorJoint.mainImpostor === mainImpostor);
  95626. });
  95627. if (matchingJoints.length) {
  95628. this._physicsPlugin.removeJoint(matchingJoints[0]);
  95629. //TODO remove it from the list as well
  95630. }
  95631. };
  95632. /**
  95633. * Called by the scene. No need to call it.
  95634. * @param delta defines the timespam between frames
  95635. */
  95636. PhysicsEngine.prototype._step = function (delta) {
  95637. var _this = this;
  95638. //check if any mesh has no body / requires an update
  95639. this._impostors.forEach(function (impostor) {
  95640. if (impostor.isBodyInitRequired()) {
  95641. _this._physicsPlugin.generatePhysicsBody(impostor);
  95642. }
  95643. });
  95644. if (delta > 0.1) {
  95645. delta = 0.1;
  95646. }
  95647. else if (delta <= 0) {
  95648. delta = 1.0 / 60.0;
  95649. }
  95650. this._physicsPlugin.executeStep(delta, this._impostors);
  95651. };
  95652. /**
  95653. * Gets the current plugin used to run the simulation
  95654. * @returns current plugin
  95655. */
  95656. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  95657. return this._physicsPlugin;
  95658. };
  95659. /**
  95660. * Gets the list of physic impostors
  95661. * @returns an array of PhysicsImpostor
  95662. */
  95663. PhysicsEngine.prototype.getImpostors = function () {
  95664. return this._impostors;
  95665. };
  95666. /**
  95667. * Gets the impostor for a physics enabled object
  95668. * @param object defines the object impersonated by the impostor
  95669. * @returns the PhysicsImpostor or null if not found
  95670. */
  95671. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  95672. for (var i = 0; i < this._impostors.length; ++i) {
  95673. if (this._impostors[i].object === object) {
  95674. return this._impostors[i];
  95675. }
  95676. }
  95677. return null;
  95678. };
  95679. /**
  95680. * Gets the impostor for a physics body object
  95681. * @param body defines physics body used by the impostor
  95682. * @returns the PhysicsImpostor or null if not found
  95683. */
  95684. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  95685. for (var i = 0; i < this._impostors.length; ++i) {
  95686. if (this._impostors[i].physicsBody === body) {
  95687. return this._impostors[i];
  95688. }
  95689. }
  95690. return null;
  95691. };
  95692. /**
  95693. * Global value used to control the smallest number supported by the simulation
  95694. */
  95695. PhysicsEngine.Epsilon = 0.001;
  95696. return PhysicsEngine;
  95697. }());
  95698. BABYLON.PhysicsEngine = PhysicsEngine;
  95699. })(BABYLON || (BABYLON = {}));
  95700. //# sourceMappingURL=babylon.physicsEngine.js.map
  95701. var BABYLON;
  95702. (function (BABYLON) {
  95703. /**
  95704. * A helper for physics simulations
  95705. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95706. */
  95707. var PhysicsHelper = /** @class */ (function () {
  95708. /**
  95709. * Initializes the Physics helper
  95710. * @param scene Babylon.js scene
  95711. */
  95712. function PhysicsHelper(scene) {
  95713. this._scene = scene;
  95714. this._physicsEngine = this._scene.getPhysicsEngine();
  95715. if (!this._physicsEngine) {
  95716. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  95717. }
  95718. }
  95719. /**
  95720. * Applies a radial explosion impulse
  95721. * @param origin the origin of the explosion
  95722. * @param radius the explosion radius
  95723. * @param strength the explosion strength
  95724. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95725. * @returns A physics radial explosion event, or null
  95726. */
  95727. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  95728. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95729. if (!this._physicsEngine) {
  95730. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  95731. return null;
  95732. }
  95733. var impostors = this._physicsEngine.getImpostors();
  95734. if (impostors.length === 0) {
  95735. return null;
  95736. }
  95737. var event = new PhysicsRadialExplosionEvent(this._scene);
  95738. impostors.forEach(function (impostor) {
  95739. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95740. if (!impostorForceAndContactPoint) {
  95741. return;
  95742. }
  95743. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95744. });
  95745. event.dispose(false);
  95746. return event;
  95747. };
  95748. /**
  95749. * Applies a radial explosion force
  95750. * @param origin the origin of the explosion
  95751. * @param radius the explosion radius
  95752. * @param strength the explosion strength
  95753. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95754. * @returns A physics radial explosion event, or null
  95755. */
  95756. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  95757. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95758. if (!this._physicsEngine) {
  95759. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95760. return null;
  95761. }
  95762. var impostors = this._physicsEngine.getImpostors();
  95763. if (impostors.length === 0) {
  95764. return null;
  95765. }
  95766. var event = new PhysicsRadialExplosionEvent(this._scene);
  95767. impostors.forEach(function (impostor) {
  95768. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95769. if (!impostorForceAndContactPoint) {
  95770. return;
  95771. }
  95772. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95773. });
  95774. event.dispose(false);
  95775. return event;
  95776. };
  95777. /**
  95778. * Creates a gravitational field
  95779. * @param origin the origin of the explosion
  95780. * @param radius the explosion radius
  95781. * @param strength the explosion strength
  95782. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95783. * @returns A physics gravitational field event, or null
  95784. */
  95785. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  95786. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95787. if (!this._physicsEngine) {
  95788. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95789. return null;
  95790. }
  95791. var impostors = this._physicsEngine.getImpostors();
  95792. if (impostors.length === 0) {
  95793. return null;
  95794. }
  95795. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  95796. event.dispose(false);
  95797. return event;
  95798. };
  95799. /**
  95800. * Creates a physics updraft event
  95801. * @param origin the origin of the updraft
  95802. * @param radius the radius of the updraft
  95803. * @param strength the strength of the updraft
  95804. * @param height the height of the updraft
  95805. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  95806. * @returns A physics updraft event, or null
  95807. */
  95808. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  95809. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  95810. if (!this._physicsEngine) {
  95811. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95812. return null;
  95813. }
  95814. if (this._physicsEngine.getImpostors().length === 0) {
  95815. return null;
  95816. }
  95817. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  95818. event.dispose(false);
  95819. return event;
  95820. };
  95821. /**
  95822. * Creates a physics vortex event
  95823. * @param origin the of the vortex
  95824. * @param radius the radius of the vortex
  95825. * @param strength the strength of the vortex
  95826. * @param height the height of the vortex
  95827. * @returns a Physics vortex event, or null
  95828. * A physics vortex event or null
  95829. */
  95830. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  95831. if (!this._physicsEngine) {
  95832. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95833. return null;
  95834. }
  95835. if (this._physicsEngine.getImpostors().length === 0) {
  95836. return null;
  95837. }
  95838. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  95839. event.dispose(false);
  95840. return event;
  95841. };
  95842. return PhysicsHelper;
  95843. }());
  95844. BABYLON.PhysicsHelper = PhysicsHelper;
  95845. /**
  95846. * Represents a physics radial explosion event
  95847. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95848. */
  95849. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  95850. /**
  95851. * Initializes a radial explosioin event
  95852. * @param scene BabylonJS scene
  95853. */
  95854. function PhysicsRadialExplosionEvent(scene) {
  95855. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  95856. this._rays = [];
  95857. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  95858. this._scene = scene;
  95859. }
  95860. /**
  95861. * Returns the data related to the radial explosion event (sphere & rays).
  95862. * @returns The radial explosion event data
  95863. */
  95864. PhysicsRadialExplosionEvent.prototype.getData = function () {
  95865. this._dataFetched = true;
  95866. return {
  95867. sphere: this._sphere,
  95868. rays: this._rays,
  95869. };
  95870. };
  95871. /**
  95872. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  95873. * @param impostor A physics imposter
  95874. * @param origin the origin of the explosion
  95875. * @param radius the explosion radius
  95876. * @param strength the explosion strength
  95877. * @param falloff possible options: Constant & Linear
  95878. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  95879. */
  95880. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  95881. if (impostor.mass === 0) {
  95882. return null;
  95883. }
  95884. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  95885. return null;
  95886. }
  95887. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  95888. return null;
  95889. }
  95890. var impostorObjectCenter = impostor.getObjectCenter();
  95891. var direction = impostorObjectCenter.subtract(origin);
  95892. var ray = new BABYLON.Ray(origin, direction, radius);
  95893. this._rays.push(ray);
  95894. var hit = ray.intersectsMesh(impostor.object);
  95895. var contactPoint = hit.pickedPoint;
  95896. if (!contactPoint) {
  95897. return null;
  95898. }
  95899. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  95900. if (distanceFromOrigin > radius) {
  95901. return null;
  95902. }
  95903. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  95904. ? strength
  95905. : strength * (1 - (distanceFromOrigin / radius));
  95906. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  95907. return { force: force, contactPoint: contactPoint };
  95908. };
  95909. /**
  95910. * Disposes the sphere.
  95911. * @param force Specifies if the sphere should be disposed by force
  95912. */
  95913. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  95914. var _this = this;
  95915. if (force === void 0) { force = true; }
  95916. if (force) {
  95917. this._sphere.dispose();
  95918. }
  95919. else {
  95920. setTimeout(function () {
  95921. if (!_this._dataFetched) {
  95922. _this._sphere.dispose();
  95923. }
  95924. }, 0);
  95925. }
  95926. };
  95927. /*** Helpers ***/
  95928. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  95929. if (!this._sphere) {
  95930. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  95931. this._sphere.isVisible = false;
  95932. }
  95933. };
  95934. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  95935. var impostorObject = impostor.object;
  95936. this._prepareSphere();
  95937. this._sphere.position = origin;
  95938. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  95939. this._sphere._updateBoundingInfo();
  95940. this._sphere.computeWorldMatrix(true);
  95941. return this._sphere.intersectsMesh(impostorObject, true);
  95942. };
  95943. return PhysicsRadialExplosionEvent;
  95944. }());
  95945. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  95946. /**
  95947. * Represents a gravitational field event
  95948. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95949. */
  95950. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  95951. /**
  95952. * Initializes the physics gravitational field event
  95953. * @param physicsHelper A physics helper
  95954. * @param scene BabylonJS scene
  95955. * @param origin The origin position of the gravitational field event
  95956. * @param radius The radius of the gravitational field event
  95957. * @param strength The strength of the gravitational field event
  95958. * @param falloff The falloff for the gravitational field event
  95959. */
  95960. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  95961. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95962. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95963. this._physicsHelper = physicsHelper;
  95964. this._scene = scene;
  95965. this._origin = origin;
  95966. this._radius = radius;
  95967. this._strength = strength;
  95968. this._falloff = falloff;
  95969. this._tickCallback = this._tick.bind(this);
  95970. }
  95971. /**
  95972. * Returns the data related to the gravitational field event (sphere).
  95973. * @returns A gravitational field event
  95974. */
  95975. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  95976. this._dataFetched = true;
  95977. return {
  95978. sphere: this._sphere,
  95979. };
  95980. };
  95981. /**
  95982. * Enables the gravitational field.
  95983. */
  95984. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  95985. this._tickCallback.call(this);
  95986. this._scene.registerBeforeRender(this._tickCallback);
  95987. };
  95988. /**
  95989. * Disables the gravitational field.
  95990. */
  95991. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  95992. this._scene.unregisterBeforeRender(this._tickCallback);
  95993. };
  95994. /**
  95995. * Disposes the sphere.
  95996. * @param force The force to dispose from the gravitational field event
  95997. */
  95998. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  95999. var _this = this;
  96000. if (force === void 0) { force = true; }
  96001. if (force) {
  96002. this._sphere.dispose();
  96003. }
  96004. else {
  96005. setTimeout(function () {
  96006. if (!_this._dataFetched) {
  96007. _this._sphere.dispose();
  96008. }
  96009. }, 0);
  96010. }
  96011. };
  96012. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  96013. // Since the params won't change, we fetch the event only once
  96014. if (this._sphere) {
  96015. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  96016. }
  96017. else {
  96018. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  96019. if (radialExplosionEvent) {
  96020. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  96021. }
  96022. }
  96023. };
  96024. return PhysicsGravitationalFieldEvent;
  96025. }());
  96026. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  96027. /**
  96028. * Represents a physics updraft event
  96029. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96030. */
  96031. var PhysicsUpdraftEvent = /** @class */ (function () {
  96032. /**
  96033. * Initializes the physics updraft event
  96034. * @param _scene BabylonJS scene
  96035. * @param _origin The origin position of the updraft
  96036. * @param _radius The radius of the updraft
  96037. * @param _strength The strength of the updraft
  96038. * @param _height The height of the updraft
  96039. * @param _updraftMode The mode of the updraft
  96040. */
  96041. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  96042. this._scene = _scene;
  96043. this._origin = _origin;
  96044. this._radius = _radius;
  96045. this._strength = _strength;
  96046. this._height = _height;
  96047. this._updraftMode = _updraftMode;
  96048. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  96049. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  96050. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  96051. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  96052. this._physicsEngine = this._scene.getPhysicsEngine();
  96053. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  96054. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  96055. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  96056. this._originDirection = this._origin.subtract(this._originTop).normalize();
  96057. }
  96058. this._tickCallback = this._tick.bind(this);
  96059. }
  96060. /**
  96061. * Returns the data related to the updraft event (cylinder).
  96062. * @returns A physics updraft event
  96063. */
  96064. PhysicsUpdraftEvent.prototype.getData = function () {
  96065. this._dataFetched = true;
  96066. return {
  96067. cylinder: this._cylinder,
  96068. };
  96069. };
  96070. /**
  96071. * Enables the updraft.
  96072. */
  96073. PhysicsUpdraftEvent.prototype.enable = function () {
  96074. this._tickCallback.call(this);
  96075. this._scene.registerBeforeRender(this._tickCallback);
  96076. };
  96077. /**
  96078. * Disables the cortex.
  96079. */
  96080. PhysicsUpdraftEvent.prototype.disable = function () {
  96081. this._scene.unregisterBeforeRender(this._tickCallback);
  96082. };
  96083. /**
  96084. * Disposes the sphere.
  96085. * @param force Specifies if the updraft should be disposed by force
  96086. */
  96087. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  96088. var _this = this;
  96089. if (force === void 0) { force = true; }
  96090. if (force) {
  96091. this._cylinder.dispose();
  96092. }
  96093. else {
  96094. setTimeout(function () {
  96095. if (!_this._dataFetched) {
  96096. _this._cylinder.dispose();
  96097. }
  96098. }, 0);
  96099. }
  96100. };
  96101. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  96102. if (impostor.mass === 0) {
  96103. return null;
  96104. }
  96105. if (!this._intersectsWithCylinder(impostor)) {
  96106. return null;
  96107. }
  96108. var impostorObjectCenter = impostor.getObjectCenter();
  96109. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  96110. var direction = this._originDirection;
  96111. }
  96112. else {
  96113. var direction = impostorObjectCenter.subtract(this._originTop);
  96114. }
  96115. var multiplier = this._strength * -1;
  96116. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  96117. return { force: force, contactPoint: impostorObjectCenter };
  96118. };
  96119. PhysicsUpdraftEvent.prototype._tick = function () {
  96120. var _this = this;
  96121. this._physicsEngine.getImpostors().forEach(function (impostor) {
  96122. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  96123. if (!impostorForceAndContactPoint) {
  96124. return;
  96125. }
  96126. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96127. });
  96128. };
  96129. /*** Helpers ***/
  96130. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  96131. if (!this._cylinder) {
  96132. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  96133. height: this._height,
  96134. diameter: this._radius * 2,
  96135. }, this._scene);
  96136. this._cylinder.isVisible = false;
  96137. }
  96138. };
  96139. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  96140. var impostorObject = impostor.object;
  96141. this._prepareCylinder();
  96142. this._cylinder.position = this._cylinderPosition;
  96143. return this._cylinder.intersectsMesh(impostorObject, true);
  96144. };
  96145. return PhysicsUpdraftEvent;
  96146. }());
  96147. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  96148. /**
  96149. * Represents a physics vortex event
  96150. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96151. */
  96152. var PhysicsVortexEvent = /** @class */ (function () {
  96153. /**
  96154. * Initializes the physics vortex event
  96155. * @param _scene The BabylonJS scene
  96156. * @param _origin The origin position of the vortex
  96157. * @param _radius The radius of the vortex
  96158. * @param _strength The strength of the vortex
  96159. * @param _height The height of the vortex
  96160. */
  96161. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  96162. this._scene = _scene;
  96163. this._origin = _origin;
  96164. this._radius = _radius;
  96165. this._strength = _strength;
  96166. this._height = _height;
  96167. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  96168. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  96169. this._updraftMultiplier = 0.02;
  96170. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  96171. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  96172. this._physicsEngine = this._scene.getPhysicsEngine();
  96173. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  96174. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  96175. this._tickCallback = this._tick.bind(this);
  96176. }
  96177. /**
  96178. * Returns the data related to the vortex event (cylinder).
  96179. * @returns The physics vortex event data
  96180. */
  96181. PhysicsVortexEvent.prototype.getData = function () {
  96182. this._dataFetched = true;
  96183. return {
  96184. cylinder: this._cylinder,
  96185. };
  96186. };
  96187. /**
  96188. * Enables the vortex.
  96189. */
  96190. PhysicsVortexEvent.prototype.enable = function () {
  96191. this._tickCallback.call(this);
  96192. this._scene.registerBeforeRender(this._tickCallback);
  96193. };
  96194. /**
  96195. * Disables the cortex.
  96196. */
  96197. PhysicsVortexEvent.prototype.disable = function () {
  96198. this._scene.unregisterBeforeRender(this._tickCallback);
  96199. };
  96200. /**
  96201. * Disposes the sphere.
  96202. * @param force
  96203. */
  96204. PhysicsVortexEvent.prototype.dispose = function (force) {
  96205. var _this = this;
  96206. if (force === void 0) { force = true; }
  96207. if (force) {
  96208. this._cylinder.dispose();
  96209. }
  96210. else {
  96211. setTimeout(function () {
  96212. if (!_this._dataFetched) {
  96213. _this._cylinder.dispose();
  96214. }
  96215. }, 0);
  96216. }
  96217. };
  96218. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  96219. if (impostor.mass === 0) {
  96220. return null;
  96221. }
  96222. if (!this._intersectsWithCylinder(impostor)) {
  96223. return null;
  96224. }
  96225. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  96226. return null;
  96227. }
  96228. var impostorObjectCenter = impostor.getObjectCenter();
  96229. 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)
  96230. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  96231. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  96232. var hit = ray.intersectsMesh(impostor.object);
  96233. var contactPoint = hit.pickedPoint;
  96234. if (!contactPoint) {
  96235. return null;
  96236. }
  96237. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  96238. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  96239. var directionToOrigin = contactPoint.normalize();
  96240. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  96241. directionToOrigin = directionToOrigin.negate();
  96242. }
  96243. // TODO: find a more physically based solution
  96244. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  96245. var forceX = directionToOrigin.x * this._strength / 8;
  96246. var forceY = directionToOrigin.y * this._updraftMultiplier;
  96247. var forceZ = directionToOrigin.z * this._strength / 8;
  96248. }
  96249. else {
  96250. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  96251. var forceY = this._originTop.y * this._updraftMultiplier;
  96252. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  96253. }
  96254. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  96255. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  96256. return { force: force, contactPoint: impostorObjectCenter };
  96257. };
  96258. PhysicsVortexEvent.prototype._tick = function () {
  96259. var _this = this;
  96260. this._physicsEngine.getImpostors().forEach(function (impostor) {
  96261. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  96262. if (!impostorForceAndContactPoint) {
  96263. return;
  96264. }
  96265. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96266. });
  96267. };
  96268. /*** Helpers ***/
  96269. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  96270. if (!this._cylinder) {
  96271. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  96272. height: this._height,
  96273. diameter: this._radius * 2,
  96274. }, this._scene);
  96275. this._cylinder.isVisible = false;
  96276. }
  96277. };
  96278. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  96279. var impostorObject = impostor.object;
  96280. this._prepareCylinder();
  96281. this._cylinder.position = this._cylinderPosition;
  96282. return this._cylinder.intersectsMesh(impostorObject, true);
  96283. };
  96284. return PhysicsVortexEvent;
  96285. }());
  96286. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  96287. /**
  96288. * The strenght of the force in correspondence to the distance of the affected object
  96289. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96290. */
  96291. var PhysicsRadialImpulseFalloff;
  96292. (function (PhysicsRadialImpulseFalloff) {
  96293. /** Defines that impulse is constant in strength across it's whole radius */
  96294. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  96295. /** DEfines that impulse gets weaker if it's further from the origin */
  96296. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  96297. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  96298. /**
  96299. * The strength of the force in correspondence to the distance of the affected object
  96300. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96301. */
  96302. var PhysicsUpdraftMode;
  96303. (function (PhysicsUpdraftMode) {
  96304. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  96305. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  96306. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  96307. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  96308. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  96309. })(BABYLON || (BABYLON = {}));
  96310. //# sourceMappingURL=babylon.physicsHelper.js.map
  96311. var BABYLON;
  96312. (function (BABYLON) {
  96313. /** @hidden */
  96314. var CannonJSPlugin = /** @class */ (function () {
  96315. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  96316. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  96317. if (iterations === void 0) { iterations = 10; }
  96318. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  96319. this.name = "CannonJSPlugin";
  96320. this._physicsMaterials = new Array();
  96321. this._fixedTimeStep = 1 / 60;
  96322. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  96323. this.BJSCANNON = CANNON;
  96324. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  96325. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  96326. this._tmpPosition = BABYLON.Vector3.Zero();
  96327. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  96328. this._tmpUnityRotation = new BABYLON.Quaternion();
  96329. if (!this.isSupported()) {
  96330. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  96331. return;
  96332. }
  96333. this._extendNamespace();
  96334. this.world = new this.BJSCANNON.World();
  96335. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  96336. this.world.solver.iterations = iterations;
  96337. }
  96338. CannonJSPlugin.prototype.setGravity = function (gravity) {
  96339. this.world.gravity.copy(gravity);
  96340. };
  96341. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  96342. this._fixedTimeStep = timeStep;
  96343. };
  96344. CannonJSPlugin.prototype.getTimeStep = function () {
  96345. return this._fixedTimeStep;
  96346. };
  96347. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  96348. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  96349. };
  96350. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96351. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96352. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96353. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  96354. };
  96355. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96356. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96357. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96358. impostor.physicsBody.applyForce(impulse, worldPoint);
  96359. };
  96360. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96361. //parent-child relationship. Does this impostor has a parent impostor?
  96362. if (impostor.parent) {
  96363. if (impostor.physicsBody) {
  96364. this.removePhysicsBody(impostor);
  96365. //TODO is that needed?
  96366. impostor.forceUpdate();
  96367. }
  96368. return;
  96369. }
  96370. //should a new body be created for this impostor?
  96371. if (impostor.isBodyInitRequired()) {
  96372. var shape = this._createShape(impostor);
  96373. //unregister events, if body is being changed
  96374. var oldBody = impostor.physicsBody;
  96375. if (oldBody) {
  96376. this.removePhysicsBody(impostor);
  96377. }
  96378. //create the body and material
  96379. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  96380. var bodyCreationObject = {
  96381. mass: impostor.getParam("mass"),
  96382. material: material
  96383. };
  96384. // A simple extend, in case native options were used.
  96385. var nativeOptions = impostor.getParam("nativeOptions");
  96386. for (var key in nativeOptions) {
  96387. if (nativeOptions.hasOwnProperty(key)) {
  96388. bodyCreationObject[key] = nativeOptions[key];
  96389. }
  96390. }
  96391. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  96392. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  96393. this.world.addEventListener("preStep", impostor.beforeStep);
  96394. this.world.addEventListener("postStep", impostor.afterStep);
  96395. impostor.physicsBody.addShape(shape);
  96396. this.world.add(impostor.physicsBody);
  96397. //try to keep the body moving in the right direction by taking old properties.
  96398. //Should be tested!
  96399. if (oldBody) {
  96400. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  96401. impostor.physicsBody[param].copy(oldBody[param]);
  96402. });
  96403. }
  96404. this._processChildMeshes(impostor);
  96405. }
  96406. //now update the body's transformation
  96407. this._updatePhysicsBodyTransformation(impostor);
  96408. };
  96409. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  96410. var _this = this;
  96411. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  96412. var currentRotation = mainImpostor.object.rotationQuaternion;
  96413. if (meshChildren.length) {
  96414. var processMesh = function (localPosition, mesh) {
  96415. if (!currentRotation || !mesh.rotationQuaternion) {
  96416. return;
  96417. }
  96418. var childImpostor = mesh.getPhysicsImpostor();
  96419. if (childImpostor) {
  96420. var parent = childImpostor.parent;
  96421. if (parent !== mainImpostor) {
  96422. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  96423. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  96424. if (childImpostor.physicsBody) {
  96425. _this.removePhysicsBody(childImpostor);
  96426. childImpostor.physicsBody = null;
  96427. }
  96428. childImpostor.parent = mainImpostor;
  96429. childImpostor.resetUpdateFlags();
  96430. 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));
  96431. //Add the mass of the children.
  96432. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  96433. }
  96434. }
  96435. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  96436. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  96437. };
  96438. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  96439. }
  96440. };
  96441. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  96442. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  96443. this.world.removeEventListener("preStep", impostor.beforeStep);
  96444. this.world.removeEventListener("postStep", impostor.afterStep);
  96445. this.world.remove(impostor.physicsBody);
  96446. };
  96447. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  96448. var mainBody = impostorJoint.mainImpostor.physicsBody;
  96449. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  96450. if (!mainBody || !connectedBody) {
  96451. return;
  96452. }
  96453. var constraint;
  96454. var jointData = impostorJoint.joint.jointData;
  96455. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  96456. var constraintData = {
  96457. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  96458. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  96459. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  96460. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  96461. maxForce: jointData.nativeParams.maxForce,
  96462. collideConnected: !!jointData.collision
  96463. };
  96464. switch (impostorJoint.joint.type) {
  96465. case BABYLON.PhysicsJoint.HingeJoint:
  96466. case BABYLON.PhysicsJoint.Hinge2Joint:
  96467. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  96468. break;
  96469. case BABYLON.PhysicsJoint.DistanceJoint:
  96470. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  96471. break;
  96472. case BABYLON.PhysicsJoint.SpringJoint:
  96473. var springData = jointData;
  96474. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  96475. restLength: springData.length,
  96476. stiffness: springData.stiffness,
  96477. damping: springData.damping,
  96478. localAnchorA: constraintData.pivotA,
  96479. localAnchorB: constraintData.pivotB
  96480. });
  96481. break;
  96482. case BABYLON.PhysicsJoint.LockJoint:
  96483. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  96484. break;
  96485. case BABYLON.PhysicsJoint.PointToPointJoint:
  96486. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  96487. default:
  96488. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  96489. break;
  96490. }
  96491. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  96492. constraint.collideConnected = !!jointData.collision;
  96493. impostorJoint.joint.physicsJoint = constraint;
  96494. //don't add spring as constraint, as it is not one.
  96495. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96496. this.world.addConstraint(constraint);
  96497. }
  96498. else {
  96499. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  96500. constraint.applyForce();
  96501. };
  96502. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96503. }
  96504. };
  96505. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  96506. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96507. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  96508. }
  96509. else {
  96510. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96511. }
  96512. };
  96513. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  96514. var index;
  96515. var mat;
  96516. for (index = 0; index < this._physicsMaterials.length; index++) {
  96517. mat = this._physicsMaterials[index];
  96518. if (mat.friction === friction && mat.restitution === restitution) {
  96519. return mat;
  96520. }
  96521. }
  96522. var currentMat = new this.BJSCANNON.Material(name);
  96523. currentMat.friction = friction;
  96524. currentMat.restitution = restitution;
  96525. this._physicsMaterials.push(currentMat);
  96526. return currentMat;
  96527. };
  96528. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  96529. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  96530. };
  96531. CannonJSPlugin.prototype._createShape = function (impostor) {
  96532. var object = impostor.object;
  96533. var returnValue;
  96534. var extendSize = impostor.getObjectExtendSize();
  96535. switch (impostor.type) {
  96536. case BABYLON.PhysicsImpostor.SphereImpostor:
  96537. var radiusX = extendSize.x;
  96538. var radiusY = extendSize.y;
  96539. var radiusZ = extendSize.z;
  96540. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  96541. break;
  96542. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  96543. case BABYLON.PhysicsImpostor.CylinderImpostor:
  96544. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  96545. break;
  96546. case BABYLON.PhysicsImpostor.BoxImpostor:
  96547. var box = extendSize.scale(0.5);
  96548. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  96549. break;
  96550. case BABYLON.PhysicsImpostor.PlaneImpostor:
  96551. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  96552. returnValue = new this.BJSCANNON.Plane();
  96553. break;
  96554. case BABYLON.PhysicsImpostor.MeshImpostor:
  96555. // should transform the vertex data to world coordinates!!
  96556. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  96557. var rawFaces = object.getIndices ? object.getIndices() : [];
  96558. if (!rawVerts) {
  96559. return;
  96560. }
  96561. // get only scale! so the object could transform correctly.
  96562. var oldPosition = object.position.clone();
  96563. var oldRotation = object.rotation && object.rotation.clone();
  96564. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  96565. object.position.copyFromFloats(0, 0, 0);
  96566. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96567. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96568. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96569. var transform = object.computeWorldMatrix(true);
  96570. // convert rawVerts to object space
  96571. var temp = new Array();
  96572. var index;
  96573. for (index = 0; index < rawVerts.length; index += 3) {
  96574. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  96575. }
  96576. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  96577. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  96578. //now set back the transformation!
  96579. object.position.copyFrom(oldPosition);
  96580. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  96581. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  96582. break;
  96583. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  96584. var oldPosition2 = object.position.clone();
  96585. var oldRotation2 = object.rotation && object.rotation.clone();
  96586. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  96587. object.position.copyFromFloats(0, 0, 0);
  96588. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96589. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96590. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96591. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  96592. returnValue = this._createHeightmap(object);
  96593. object.position.copyFrom(oldPosition2);
  96594. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  96595. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  96596. object.computeWorldMatrix(true);
  96597. break;
  96598. case BABYLON.PhysicsImpostor.ParticleImpostor:
  96599. returnValue = new this.BJSCANNON.Particle();
  96600. break;
  96601. }
  96602. return returnValue;
  96603. };
  96604. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  96605. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  96606. var transform = object.computeWorldMatrix(true);
  96607. // convert rawVerts to object space
  96608. var temp = new Array();
  96609. var index;
  96610. for (index = 0; index < pos.length; index += 3) {
  96611. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  96612. }
  96613. pos = temp;
  96614. var matrix = new Array();
  96615. //For now pointDepth will not be used and will be automatically calculated.
  96616. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  96617. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  96618. var boundingInfo = object.getBoundingInfo();
  96619. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  96620. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  96621. var elementSize = dim * 2 / arraySize;
  96622. for (var i = 0; i < pos.length; i = i + 3) {
  96623. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  96624. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  96625. var y = -pos[i + 2] + minY;
  96626. if (!matrix[x]) {
  96627. matrix[x] = [];
  96628. }
  96629. if (!matrix[x][z]) {
  96630. matrix[x][z] = y;
  96631. }
  96632. matrix[x][z] = Math.max(y, matrix[x][z]);
  96633. }
  96634. for (var x = 0; x <= arraySize; ++x) {
  96635. if (!matrix[x]) {
  96636. var loc = 1;
  96637. while (!matrix[(x + loc) % arraySize]) {
  96638. loc++;
  96639. }
  96640. matrix[x] = matrix[(x + loc) % arraySize].slice();
  96641. //console.log("missing x", x);
  96642. }
  96643. for (var z = 0; z <= arraySize; ++z) {
  96644. if (!matrix[x][z]) {
  96645. var loc = 1;
  96646. var newValue;
  96647. while (newValue === undefined) {
  96648. newValue = matrix[x][(z + loc++) % arraySize];
  96649. }
  96650. matrix[x][z] = newValue;
  96651. }
  96652. }
  96653. }
  96654. var shape = new this.BJSCANNON.Heightfield(matrix, {
  96655. elementSize: elementSize
  96656. });
  96657. //For future reference, needed for body transformation
  96658. shape.minY = minY;
  96659. return shape;
  96660. };
  96661. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  96662. var object = impostor.object;
  96663. //make sure it is updated...
  96664. object.computeWorldMatrix && object.computeWorldMatrix(true);
  96665. // The delta between the mesh position and the mesh bounding box center
  96666. var bInfo = object.getBoundingInfo();
  96667. if (!bInfo) {
  96668. return;
  96669. }
  96670. var center = impostor.getObjectCenter();
  96671. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  96672. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  96673. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  96674. this._tmpPosition.copyFrom(center);
  96675. var quaternion = object.rotationQuaternion;
  96676. if (!quaternion) {
  96677. return;
  96678. }
  96679. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  96680. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  96681. //-90 DEG in X, precalculated
  96682. quaternion = quaternion.multiply(this._minus90X);
  96683. //Invert! (Precalculated, 90 deg in X)
  96684. //No need to clone. this will never change.
  96685. impostor.setDeltaRotation(this._plus90X);
  96686. }
  96687. //If it is a heightfield, if should be centered.
  96688. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  96689. var mesh = object;
  96690. var boundingInfo = mesh.getBoundingInfo();
  96691. //calculate the correct body position:
  96692. var rotationQuaternion = mesh.rotationQuaternion;
  96693. mesh.rotationQuaternion = this._tmpUnityRotation;
  96694. mesh.computeWorldMatrix(true);
  96695. //get original center with no rotation
  96696. var c = center.clone();
  96697. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  96698. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  96699. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  96700. mesh.setPreTransformMatrix(p);
  96701. mesh.computeWorldMatrix(true);
  96702. //calculate the translation
  96703. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  96704. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  96705. //add it inverted to the delta
  96706. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  96707. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  96708. //rotation is back
  96709. mesh.rotationQuaternion = rotationQuaternion;
  96710. mesh.setPreTransformMatrix(oldPivot);
  96711. mesh.computeWorldMatrix(true);
  96712. }
  96713. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  96714. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  96715. //this._tmpPosition.copyFrom(object.position);
  96716. }
  96717. impostor.setDeltaPosition(this._tmpDeltaPosition);
  96718. //Now update the impostor object
  96719. impostor.physicsBody.position.copy(this._tmpPosition);
  96720. impostor.physicsBody.quaternion.copy(quaternion);
  96721. };
  96722. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  96723. impostor.object.position.copyFrom(impostor.physicsBody.position);
  96724. if (impostor.object.rotationQuaternion) {
  96725. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  96726. }
  96727. };
  96728. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  96729. impostor.physicsBody.position.copy(newPosition);
  96730. impostor.physicsBody.quaternion.copy(newRotation);
  96731. };
  96732. CannonJSPlugin.prototype.isSupported = function () {
  96733. return this.BJSCANNON !== undefined;
  96734. };
  96735. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  96736. impostor.physicsBody.velocity.copy(velocity);
  96737. };
  96738. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  96739. impostor.physicsBody.angularVelocity.copy(velocity);
  96740. };
  96741. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  96742. var v = impostor.physicsBody.velocity;
  96743. if (!v) {
  96744. return null;
  96745. }
  96746. return new BABYLON.Vector3(v.x, v.y, v.z);
  96747. };
  96748. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  96749. var v = impostor.physicsBody.angularVelocity;
  96750. if (!v) {
  96751. return null;
  96752. }
  96753. return new BABYLON.Vector3(v.x, v.y, v.z);
  96754. };
  96755. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  96756. impostor.physicsBody.mass = mass;
  96757. impostor.physicsBody.updateMassProperties();
  96758. };
  96759. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  96760. return impostor.physicsBody.mass;
  96761. };
  96762. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  96763. return impostor.physicsBody.material.friction;
  96764. };
  96765. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  96766. impostor.physicsBody.material.friction = friction;
  96767. };
  96768. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  96769. return impostor.physicsBody.material.restitution;
  96770. };
  96771. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  96772. impostor.physicsBody.material.restitution = restitution;
  96773. };
  96774. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  96775. impostor.physicsBody.sleep();
  96776. };
  96777. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  96778. impostor.physicsBody.wakeUp();
  96779. };
  96780. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  96781. joint.physicsJoint.distance = maxDistance;
  96782. };
  96783. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96784. // if (!motorIndex) {
  96785. // joint.physicsJoint.enableMotor();
  96786. // }
  96787. // }
  96788. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96789. // if (!motorIndex) {
  96790. // joint.physicsJoint.disableMotor();
  96791. // }
  96792. // }
  96793. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  96794. if (!motorIndex) {
  96795. joint.physicsJoint.enableMotor();
  96796. joint.physicsJoint.setMotorSpeed(speed);
  96797. if (maxForce) {
  96798. this.setLimit(joint, maxForce);
  96799. }
  96800. }
  96801. };
  96802. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  96803. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  96804. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  96805. };
  96806. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  96807. var body = impostor.physicsBody;
  96808. mesh.position.x = body.position.x;
  96809. mesh.position.y = body.position.y;
  96810. mesh.position.z = body.position.z;
  96811. if (mesh.rotationQuaternion) {
  96812. mesh.rotationQuaternion.x = body.quaternion.x;
  96813. mesh.rotationQuaternion.y = body.quaternion.y;
  96814. mesh.rotationQuaternion.z = body.quaternion.z;
  96815. mesh.rotationQuaternion.w = body.quaternion.w;
  96816. }
  96817. };
  96818. CannonJSPlugin.prototype.getRadius = function (impostor) {
  96819. var shape = impostor.physicsBody.shapes[0];
  96820. return shape.boundingSphereRadius;
  96821. };
  96822. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  96823. var shape = impostor.physicsBody.shapes[0];
  96824. result.x = shape.halfExtents.x * 2;
  96825. result.y = shape.halfExtents.y * 2;
  96826. result.z = shape.halfExtents.z * 2;
  96827. };
  96828. CannonJSPlugin.prototype.dispose = function () {
  96829. };
  96830. CannonJSPlugin.prototype._extendNamespace = function () {
  96831. //this will force cannon to execute at least one step when using interpolation
  96832. var step_tmp1 = new this.BJSCANNON.Vec3();
  96833. var Engine = this.BJSCANNON;
  96834. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  96835. maxSubSteps = maxSubSteps || 10;
  96836. timeSinceLastCalled = timeSinceLastCalled || 0;
  96837. if (timeSinceLastCalled === 0) {
  96838. this.internalStep(dt);
  96839. this.time += dt;
  96840. }
  96841. else {
  96842. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  96843. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  96844. var t0 = performance.now();
  96845. for (var i = 0; i !== internalSteps; i++) {
  96846. this.internalStep(dt);
  96847. if (performance.now() - t0 > dt * 1000) {
  96848. break;
  96849. }
  96850. }
  96851. this.time += timeSinceLastCalled;
  96852. var h = this.time % dt;
  96853. var h_div_dt = h / dt;
  96854. var interpvelo = step_tmp1;
  96855. var bodies = this.bodies;
  96856. for (var j = 0; j !== bodies.length; j++) {
  96857. var b = bodies[j];
  96858. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  96859. b.position.vsub(b.previousPosition, interpvelo);
  96860. interpvelo.scale(h_div_dt, interpvelo);
  96861. b.position.vadd(interpvelo, b.interpolatedPosition);
  96862. }
  96863. else {
  96864. b.interpolatedPosition.copy(b.position);
  96865. b.interpolatedQuaternion.copy(b.quaternion);
  96866. }
  96867. }
  96868. }
  96869. };
  96870. };
  96871. return CannonJSPlugin;
  96872. }());
  96873. BABYLON.CannonJSPlugin = CannonJSPlugin;
  96874. })(BABYLON || (BABYLON = {}));
  96875. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  96876. var BABYLON;
  96877. (function (BABYLON) {
  96878. /** @hidden */
  96879. var OimoJSPlugin = /** @class */ (function () {
  96880. function OimoJSPlugin(iterations) {
  96881. this.name = "OimoJSPlugin";
  96882. this._tmpImpostorsArray = [];
  96883. this._tmpPositionVector = BABYLON.Vector3.Zero();
  96884. this.BJSOIMO = OIMO;
  96885. this.world = new this.BJSOIMO.World({
  96886. iterations: iterations
  96887. });
  96888. this.world.clear();
  96889. }
  96890. OimoJSPlugin.prototype.setGravity = function (gravity) {
  96891. this.world.gravity.copy(gravity);
  96892. };
  96893. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  96894. this.world.timeStep = timeStep;
  96895. };
  96896. OimoJSPlugin.prototype.getTimeStep = function () {
  96897. return this.world.timeStep;
  96898. };
  96899. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  96900. var _this = this;
  96901. impostors.forEach(function (impostor) {
  96902. impostor.beforeStep();
  96903. });
  96904. this.world.step();
  96905. impostors.forEach(function (impostor) {
  96906. impostor.afterStep();
  96907. //update the ordered impostors array
  96908. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  96909. });
  96910. //check for collisions
  96911. var contact = this.world.contacts;
  96912. while (contact !== null) {
  96913. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  96914. contact = contact.next;
  96915. continue;
  96916. }
  96917. //is this body colliding with any other? get the impostor
  96918. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  96919. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  96920. if (!mainImpostor || !collidingImpostor) {
  96921. contact = contact.next;
  96922. continue;
  96923. }
  96924. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  96925. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  96926. contact = contact.next;
  96927. }
  96928. };
  96929. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96930. var mass = impostor.physicsBody.mass;
  96931. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  96932. };
  96933. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96934. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  96935. this.applyImpulse(impostor, force, contactPoint);
  96936. };
  96937. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96938. var _this = this;
  96939. //parent-child relationship. Does this impostor has a parent impostor?
  96940. if (impostor.parent) {
  96941. if (impostor.physicsBody) {
  96942. this.removePhysicsBody(impostor);
  96943. //TODO is that needed?
  96944. impostor.forceUpdate();
  96945. }
  96946. return;
  96947. }
  96948. if (impostor.isBodyInitRequired()) {
  96949. var bodyConfig = {
  96950. name: impostor.uniqueId,
  96951. //Oimo must have mass, also for static objects.
  96952. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  96953. size: [],
  96954. type: [],
  96955. pos: [],
  96956. posShape: [],
  96957. rot: [],
  96958. rotShape: [],
  96959. move: impostor.getParam("mass") !== 0,
  96960. density: impostor.getParam("mass"),
  96961. friction: impostor.getParam("friction"),
  96962. restitution: impostor.getParam("restitution"),
  96963. //Supporting older versions of Oimo
  96964. world: this.world
  96965. };
  96966. var impostors = [impostor];
  96967. var addToArray = function (parent) {
  96968. if (!parent.getChildMeshes) {
  96969. return;
  96970. }
  96971. parent.getChildMeshes().forEach(function (m) {
  96972. if (m.physicsImpostor) {
  96973. impostors.push(m.physicsImpostor);
  96974. //m.physicsImpostor._init();
  96975. }
  96976. });
  96977. };
  96978. addToArray(impostor.object);
  96979. var checkWithEpsilon_1 = function (value) {
  96980. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  96981. };
  96982. var globalQuaternion_1 = new BABYLON.Quaternion();
  96983. impostors.forEach(function (i) {
  96984. if (!i.object.rotationQuaternion) {
  96985. return;
  96986. }
  96987. //get the correct bounding box
  96988. var oldQuaternion = i.object.rotationQuaternion;
  96989. globalQuaternion_1 = oldQuaternion.clone();
  96990. var rot = oldQuaternion.toEulerAngles();
  96991. var extendSize = i.getObjectExtendSize();
  96992. var radToDeg = 57.295779513082320876;
  96993. if (i === impostor) {
  96994. var center = impostor.getObjectCenter();
  96995. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  96996. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  96997. //Can also use Array.prototype.push.apply
  96998. bodyConfig.pos.push(center.x);
  96999. bodyConfig.pos.push(center.y);
  97000. bodyConfig.pos.push(center.z);
  97001. bodyConfig.posShape.push(0, 0, 0);
  97002. //tmp solution
  97003. bodyConfig.rot.push(0);
  97004. bodyConfig.rot.push(0);
  97005. bodyConfig.rot.push(0);
  97006. bodyConfig.rotShape.push(0, 0, 0);
  97007. }
  97008. else {
  97009. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  97010. bodyConfig.posShape.push(localPosition.x);
  97011. bodyConfig.posShape.push(localPosition.y);
  97012. bodyConfig.posShape.push(localPosition.z);
  97013. bodyConfig.pos.push(0, 0, 0);
  97014. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  97015. bodyConfig.rot.push(0);
  97016. bodyConfig.rot.push(0);
  97017. bodyConfig.rot.push(0);
  97018. bodyConfig.rotShape.push(rot.x * radToDeg);
  97019. bodyConfig.rotShape.push(rot.y * radToDeg);
  97020. bodyConfig.rotShape.push(rot.z * radToDeg);
  97021. }
  97022. // register mesh
  97023. switch (i.type) {
  97024. case BABYLON.PhysicsImpostor.ParticleImpostor:
  97025. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  97026. case BABYLON.PhysicsImpostor.SphereImpostor:
  97027. var radiusX = extendSize.x;
  97028. var radiusY = extendSize.y;
  97029. var radiusZ = extendSize.z;
  97030. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  97031. bodyConfig.type.push('sphere');
  97032. //due to the way oimo works with compounds, add 3 times
  97033. bodyConfig.size.push(size);
  97034. bodyConfig.size.push(size);
  97035. bodyConfig.size.push(size);
  97036. break;
  97037. case BABYLON.PhysicsImpostor.CylinderImpostor:
  97038. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  97039. var sizeY = checkWithEpsilon_1(extendSize.y);
  97040. bodyConfig.type.push('cylinder');
  97041. bodyConfig.size.push(sizeX);
  97042. bodyConfig.size.push(sizeY);
  97043. //due to the way oimo works with compounds, add one more value.
  97044. bodyConfig.size.push(sizeY);
  97045. break;
  97046. case BABYLON.PhysicsImpostor.PlaneImpostor:
  97047. case BABYLON.PhysicsImpostor.BoxImpostor:
  97048. default:
  97049. var sizeX = checkWithEpsilon_1(extendSize.x);
  97050. var sizeY = checkWithEpsilon_1(extendSize.y);
  97051. var sizeZ = checkWithEpsilon_1(extendSize.z);
  97052. bodyConfig.type.push('box');
  97053. //if (i === impostor) {
  97054. bodyConfig.size.push(sizeX);
  97055. bodyConfig.size.push(sizeY);
  97056. bodyConfig.size.push(sizeZ);
  97057. //} else {
  97058. // bodyConfig.size.push(0,0,0);
  97059. //}
  97060. break;
  97061. }
  97062. //actually not needed, but hey...
  97063. i.object.rotationQuaternion = oldQuaternion;
  97064. });
  97065. impostor.physicsBody = this.world.add(bodyConfig);
  97066. // set the quaternion, ignoring the previously defined (euler) rotation
  97067. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  97068. // update with delta 0, so the body will reveive the new rotation.
  97069. impostor.physicsBody.updatePosition(0);
  97070. }
  97071. else {
  97072. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  97073. }
  97074. impostor.setDeltaPosition(this._tmpPositionVector);
  97075. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  97076. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  97077. };
  97078. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  97079. //impostor.physicsBody.dispose();
  97080. //Same as : (older oimo versions)
  97081. this.world.removeRigidBody(impostor.physicsBody);
  97082. };
  97083. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  97084. var mainBody = impostorJoint.mainImpostor.physicsBody;
  97085. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  97086. if (!mainBody || !connectedBody) {
  97087. return;
  97088. }
  97089. var jointData = impostorJoint.joint.jointData;
  97090. var options = jointData.nativeParams || {};
  97091. var type;
  97092. var nativeJointData = {
  97093. body1: mainBody,
  97094. body2: connectedBody,
  97095. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  97096. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  97097. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  97098. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  97099. min: options.min,
  97100. max: options.max,
  97101. collision: options.collision || jointData.collision,
  97102. spring: options.spring,
  97103. //supporting older version of Oimo
  97104. world: this.world
  97105. };
  97106. switch (impostorJoint.joint.type) {
  97107. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  97108. type = "jointBall";
  97109. break;
  97110. case BABYLON.PhysicsJoint.SpringJoint:
  97111. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  97112. var springData = jointData;
  97113. nativeJointData.min = springData.length || nativeJointData.min;
  97114. //Max should also be set, just make sure it is at least min
  97115. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  97116. case BABYLON.PhysicsJoint.DistanceJoint:
  97117. type = "jointDistance";
  97118. nativeJointData.max = jointData.maxDistance;
  97119. break;
  97120. case BABYLON.PhysicsJoint.PrismaticJoint:
  97121. type = "jointPrisme";
  97122. break;
  97123. case BABYLON.PhysicsJoint.SliderJoint:
  97124. type = "jointSlide";
  97125. break;
  97126. case BABYLON.PhysicsJoint.WheelJoint:
  97127. type = "jointWheel";
  97128. break;
  97129. case BABYLON.PhysicsJoint.HingeJoint:
  97130. default:
  97131. type = "jointHinge";
  97132. break;
  97133. }
  97134. nativeJointData.type = type;
  97135. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  97136. };
  97137. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  97138. //Bug in Oimo prevents us from disposing a joint in the playground
  97139. //joint.joint.physicsJoint.dispose();
  97140. //So we will bruteforce it!
  97141. try {
  97142. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  97143. }
  97144. catch (e) {
  97145. BABYLON.Tools.Warn(e);
  97146. }
  97147. };
  97148. OimoJSPlugin.prototype.isSupported = function () {
  97149. return this.BJSOIMO !== undefined;
  97150. };
  97151. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  97152. if (!impostor.physicsBody.sleeping) {
  97153. //TODO check that
  97154. /*if (impostor.physicsBody.shapes.next) {
  97155. var parentShape = this._getLastShape(impostor.physicsBody);
  97156. impostor.object.position.copyFrom(parentShape.position);
  97157. console.log(parentShape.position);
  97158. } else {*/
  97159. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  97160. //}
  97161. if (impostor.object.rotationQuaternion) {
  97162. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  97163. }
  97164. }
  97165. };
  97166. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  97167. var body = impostor.physicsBody;
  97168. body.position.copy(newPosition);
  97169. body.orientation.copy(newRotation);
  97170. body.syncShapes();
  97171. body.awake();
  97172. };
  97173. /*private _getLastShape(body: any): any {
  97174. var lastShape = body.shapes;
  97175. while (lastShape.next) {
  97176. lastShape = lastShape.next;
  97177. }
  97178. return lastShape;
  97179. }*/
  97180. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  97181. impostor.physicsBody.linearVelocity.copy(velocity);
  97182. };
  97183. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  97184. impostor.physicsBody.angularVelocity.copy(velocity);
  97185. };
  97186. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  97187. var v = impostor.physicsBody.linearVelocity;
  97188. if (!v) {
  97189. return null;
  97190. }
  97191. return new BABYLON.Vector3(v.x, v.y, v.z);
  97192. };
  97193. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  97194. var v = impostor.physicsBody.angularVelocity;
  97195. if (!v) {
  97196. return null;
  97197. }
  97198. return new BABYLON.Vector3(v.x, v.y, v.z);
  97199. };
  97200. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  97201. var staticBody = mass === 0;
  97202. //this will actually set the body's density and not its mass.
  97203. //But this is how oimo treats the mass variable.
  97204. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  97205. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  97206. };
  97207. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  97208. return impostor.physicsBody.shapes.density;
  97209. };
  97210. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  97211. return impostor.physicsBody.shapes.friction;
  97212. };
  97213. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  97214. impostor.physicsBody.shapes.friction = friction;
  97215. };
  97216. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  97217. return impostor.physicsBody.shapes.restitution;
  97218. };
  97219. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  97220. impostor.physicsBody.shapes.restitution = restitution;
  97221. };
  97222. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  97223. impostor.physicsBody.sleep();
  97224. };
  97225. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  97226. impostor.physicsBody.awake();
  97227. };
  97228. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  97229. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  97230. if (minDistance !== void 0) {
  97231. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  97232. }
  97233. };
  97234. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  97235. //TODO separate rotational and transational motors.
  97236. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  97237. if (motor) {
  97238. motor.setMotor(speed, maxForce);
  97239. }
  97240. };
  97241. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  97242. //TODO separate rotational and transational motors.
  97243. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  97244. if (motor) {
  97245. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  97246. }
  97247. };
  97248. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  97249. var body = impostor.physicsBody;
  97250. mesh.position.x = body.position.x;
  97251. mesh.position.y = body.position.y;
  97252. mesh.position.z = body.position.z;
  97253. if (mesh.rotationQuaternion) {
  97254. mesh.rotationQuaternion.x = body.orientation.x;
  97255. mesh.rotationQuaternion.y = body.orientation.y;
  97256. mesh.rotationQuaternion.z = body.orientation.z;
  97257. mesh.rotationQuaternion.w = body.orientation.s;
  97258. }
  97259. };
  97260. OimoJSPlugin.prototype.getRadius = function (impostor) {
  97261. return impostor.physicsBody.shapes.radius;
  97262. };
  97263. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  97264. var shape = impostor.physicsBody.shapes;
  97265. result.x = shape.halfWidth * 2;
  97266. result.y = shape.halfHeight * 2;
  97267. result.z = shape.halfDepth * 2;
  97268. };
  97269. OimoJSPlugin.prototype.dispose = function () {
  97270. this.world.clear();
  97271. };
  97272. return OimoJSPlugin;
  97273. }());
  97274. BABYLON.OimoJSPlugin = OimoJSPlugin;
  97275. })(BABYLON || (BABYLON = {}));
  97276. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  97277. var BABYLON;
  97278. (function (BABYLON) {
  97279. /**
  97280. * Gets the current physics engine
  97281. * @returns a IPhysicsEngine or null if none attached
  97282. */
  97283. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  97284. return this._physicsEngine;
  97285. };
  97286. /**
  97287. * Enables physics to the current scene
  97288. * @param gravity defines the scene's gravity for the physics engine
  97289. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  97290. * @return a boolean indicating if the physics engine was initialized
  97291. */
  97292. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  97293. if (gravity === void 0) { gravity = null; }
  97294. if (this._physicsEngine) {
  97295. return true;
  97296. }
  97297. // Register the component to the scene
  97298. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  97299. if (!component) {
  97300. component = new PhysicsEngineSceneComponent(this);
  97301. this._addComponent(component);
  97302. }
  97303. try {
  97304. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  97305. return true;
  97306. }
  97307. catch (e) {
  97308. BABYLON.Tools.Error(e.message);
  97309. return false;
  97310. }
  97311. };
  97312. /**
  97313. * Disables and disposes the physics engine associated with the scene
  97314. */
  97315. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  97316. if (!this._physicsEngine) {
  97317. return;
  97318. }
  97319. this._physicsEngine.dispose();
  97320. this._physicsEngine = null;
  97321. };
  97322. /**
  97323. * Gets a boolean indicating if there is an active physics engine
  97324. * @returns a boolean indicating if there is an active physics engine
  97325. */
  97326. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  97327. return this._physicsEngine !== undefined;
  97328. };
  97329. /**
  97330. * Deletes a physics compound impostor
  97331. * @param compound defines the compound to delete
  97332. */
  97333. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  97334. var mesh = compound.parts[0].mesh;
  97335. if (mesh.physicsImpostor) {
  97336. mesh.physicsImpostor.dispose( /*true*/);
  97337. mesh.physicsImpostor = null;
  97338. }
  97339. };
  97340. /** @hidden */
  97341. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  97342. if (this._physicsEngine) {
  97343. this.onBeforePhysicsObservable.notifyObservers(this);
  97344. this._physicsEngine._step(step / 1000);
  97345. this.onAfterPhysicsObservable.notifyObservers(this);
  97346. }
  97347. };
  97348. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  97349. get: function () {
  97350. return this._physicsImpostor;
  97351. },
  97352. set: function (value) {
  97353. var _this = this;
  97354. if (this._physicsImpostor === value) {
  97355. return;
  97356. }
  97357. if (this._disposePhysicsObserver) {
  97358. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  97359. }
  97360. this._physicsImpostor = value;
  97361. if (value) {
  97362. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  97363. // Physics
  97364. if (_this.physicsImpostor) {
  97365. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  97366. _this.physicsImpostor = null;
  97367. }
  97368. });
  97369. }
  97370. },
  97371. enumerable: true,
  97372. configurable: true
  97373. });
  97374. /**
  97375. * Gets the current physics impostor
  97376. * @see http://doc.babylonjs.com/features/physics_engine
  97377. * @returns a physics impostor or null
  97378. */
  97379. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  97380. return this.physicsImpostor;
  97381. };
  97382. /**
  97383. * Apply a physic impulse to the mesh
  97384. * @param force defines the force to apply
  97385. * @param contactPoint defines where to apply the force
  97386. * @returns the current mesh
  97387. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  97388. */
  97389. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  97390. if (!this.physicsImpostor) {
  97391. return this;
  97392. }
  97393. this.physicsImpostor.applyImpulse(force, contactPoint);
  97394. return this;
  97395. };
  97396. /**
  97397. * Creates a physic joint between two meshes
  97398. * @param otherMesh defines the other mesh to use
  97399. * @param pivot1 defines the pivot to use on this mesh
  97400. * @param pivot2 defines the pivot to use on the other mesh
  97401. * @param options defines additional options (can be plugin dependent)
  97402. * @returns the current mesh
  97403. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  97404. */
  97405. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  97406. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  97407. return this;
  97408. }
  97409. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  97410. mainPivot: pivot1,
  97411. connectedPivot: pivot2,
  97412. nativeParams: options
  97413. });
  97414. return this;
  97415. };
  97416. /**
  97417. * Defines the physics engine scene component responsible to manage a physics engine
  97418. */
  97419. var PhysicsEngineSceneComponent = /** @class */ (function () {
  97420. /**
  97421. * Creates a new instance of the component for the given scene
  97422. * @param scene Defines the scene to register the component in
  97423. */
  97424. function PhysicsEngineSceneComponent(scene) {
  97425. var _this = this;
  97426. /**
  97427. * The component name helpful to identify the component in the list of scene components.
  97428. */
  97429. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  97430. this.scene = scene;
  97431. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  97432. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  97433. // Replace the function used to get the deterministic frame time
  97434. this.scene.getDeterministicFrameTime = function () {
  97435. if (_this.scene._physicsEngine) {
  97436. return _this.scene._physicsEngine.getTimeStep() * 1000;
  97437. }
  97438. return 1000.0 / 60.0;
  97439. };
  97440. }
  97441. /**
  97442. * Registers the component in a given scene
  97443. */
  97444. PhysicsEngineSceneComponent.prototype.register = function () {
  97445. };
  97446. /**
  97447. * Rebuilds the elements related to this component in case of
  97448. * context lost for instance.
  97449. */
  97450. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  97451. // Nothing to do for this component
  97452. };
  97453. /**
  97454. * Disposes the component and the associated ressources
  97455. */
  97456. PhysicsEngineSceneComponent.prototype.dispose = function () {
  97457. this.scene.onBeforePhysicsObservable.clear();
  97458. this.scene.onAfterPhysicsObservable.clear();
  97459. if (this.scene._physicsEngine) {
  97460. this.scene.disablePhysicsEngine();
  97461. }
  97462. };
  97463. return PhysicsEngineSceneComponent;
  97464. }());
  97465. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  97466. })(BABYLON || (BABYLON = {}));
  97467. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  97468. var BABYLON;
  97469. (function (BABYLON) {
  97470. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  97471. // All values and structures referenced from:
  97472. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  97473. var DDS_MAGIC = 0x20534444;
  97474. var
  97475. //DDSD_CAPS = 0x1,
  97476. //DDSD_HEIGHT = 0x2,
  97477. //DDSD_WIDTH = 0x4,
  97478. //DDSD_PITCH = 0x8,
  97479. //DDSD_PIXELFORMAT = 0x1000,
  97480. DDSD_MIPMAPCOUNT = 0x20000;
  97481. //DDSD_LINEARSIZE = 0x80000,
  97482. //DDSD_DEPTH = 0x800000;
  97483. // var DDSCAPS_COMPLEX = 0x8,
  97484. // DDSCAPS_MIPMAP = 0x400000,
  97485. // DDSCAPS_TEXTURE = 0x1000;
  97486. var DDSCAPS2_CUBEMAP = 0x200;
  97487. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  97488. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  97489. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  97490. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  97491. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  97492. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  97493. // DDSCAPS2_VOLUME = 0x200000;
  97494. var
  97495. //DDPF_ALPHAPIXELS = 0x1,
  97496. //DDPF_ALPHA = 0x2,
  97497. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  97498. //DDPF_YUV = 0x200,
  97499. DDPF_LUMINANCE = 0x20000;
  97500. function FourCCToInt32(value) {
  97501. return value.charCodeAt(0) +
  97502. (value.charCodeAt(1) << 8) +
  97503. (value.charCodeAt(2) << 16) +
  97504. (value.charCodeAt(3) << 24);
  97505. }
  97506. function Int32ToFourCC(value) {
  97507. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  97508. }
  97509. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  97510. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  97511. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  97512. var FOURCC_DX10 = FourCCToInt32("DX10");
  97513. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  97514. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  97515. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  97516. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  97517. var headerLengthInt = 31; // The header length in 32 bit ints
  97518. // Offsets into the header array
  97519. var off_magic = 0;
  97520. var off_size = 1;
  97521. var off_flags = 2;
  97522. var off_height = 3;
  97523. var off_width = 4;
  97524. var off_mipmapCount = 7;
  97525. var off_pfFlags = 20;
  97526. var off_pfFourCC = 21;
  97527. var off_RGBbpp = 22;
  97528. var off_RMask = 23;
  97529. var off_GMask = 24;
  97530. var off_BMask = 25;
  97531. var off_AMask = 26;
  97532. // var off_caps1 = 27;
  97533. var off_caps2 = 28;
  97534. // var off_caps3 = 29;
  97535. // var off_caps4 = 30;
  97536. var off_dxgiFormat = 32;
  97537. /**
  97538. * Class used to provide DDS decompression tools
  97539. */
  97540. var DDSTools = /** @class */ (function () {
  97541. function DDSTools() {
  97542. }
  97543. /**
  97544. * Gets DDS information from an array buffer
  97545. * @param arrayBuffer defines the array buffer to read data from
  97546. * @returns the DDS information
  97547. */
  97548. DDSTools.GetDDSInfo = function (arrayBuffer) {
  97549. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97550. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  97551. var mipmapCount = 1;
  97552. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  97553. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97554. }
  97555. var fourCC = header[off_pfFourCC];
  97556. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  97557. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97558. switch (fourCC) {
  97559. case FOURCC_D3DFMT_R16G16B16A16F:
  97560. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97561. break;
  97562. case FOURCC_D3DFMT_R32G32B32A32F:
  97563. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97564. break;
  97565. case FOURCC_DX10:
  97566. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  97567. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97568. break;
  97569. }
  97570. }
  97571. return {
  97572. width: header[off_width],
  97573. height: header[off_height],
  97574. mipmapCount: mipmapCount,
  97575. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  97576. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  97577. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  97578. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  97579. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  97580. dxgiFormat: dxgiFormat,
  97581. textureType: textureType
  97582. };
  97583. };
  97584. DDSTools._ToHalfFloat = function (value) {
  97585. if (!DDSTools._FloatView) {
  97586. DDSTools._FloatView = new Float32Array(1);
  97587. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  97588. }
  97589. DDSTools._FloatView[0] = value;
  97590. var x = DDSTools._Int32View[0];
  97591. var bits = (x >> 16) & 0x8000; /* Get the sign */
  97592. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  97593. var e = (x >> 23) & 0xff; /* Using int is faster here */
  97594. /* If zero, or denormal, or exponent underflows too much for a denormal
  97595. * half, return signed zero. */
  97596. if (e < 103) {
  97597. return bits;
  97598. }
  97599. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  97600. if (e > 142) {
  97601. bits |= 0x7c00;
  97602. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  97603. * not Inf, so make sure we set one mantissa bit too. */
  97604. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  97605. return bits;
  97606. }
  97607. /* If exponent underflows but not too much, return a denormal */
  97608. if (e < 113) {
  97609. m |= 0x0800;
  97610. /* Extra rounding may overflow and set mantissa to 0 and exponent
  97611. * to 1, which is OK. */
  97612. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  97613. return bits;
  97614. }
  97615. bits |= ((e - 112) << 10) | (m >> 1);
  97616. bits += m & 1;
  97617. return bits;
  97618. };
  97619. DDSTools._FromHalfFloat = function (value) {
  97620. var s = (value & 0x8000) >> 15;
  97621. var e = (value & 0x7C00) >> 10;
  97622. var f = value & 0x03FF;
  97623. if (e === 0) {
  97624. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  97625. }
  97626. else if (e == 0x1F) {
  97627. return f ? NaN : ((s ? -1 : 1) * Infinity);
  97628. }
  97629. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  97630. };
  97631. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97632. var destArray = new Float32Array(dataLength);
  97633. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97634. var index = 0;
  97635. for (var y = 0; y < height; y++) {
  97636. for (var x = 0; x < width; x++) {
  97637. var srcPos = (x + y * width) * 4;
  97638. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  97639. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  97640. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  97641. if (DDSTools.StoreLODInAlphaChannel) {
  97642. destArray[index + 3] = lod;
  97643. }
  97644. else {
  97645. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  97646. }
  97647. index += 4;
  97648. }
  97649. }
  97650. return destArray;
  97651. };
  97652. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97653. if (DDSTools.StoreLODInAlphaChannel) {
  97654. var destArray = new Uint16Array(dataLength);
  97655. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97656. var index = 0;
  97657. for (var y = 0; y < height; y++) {
  97658. for (var x = 0; x < width; x++) {
  97659. var srcPos = (x + y * width) * 4;
  97660. destArray[index] = srcData[srcPos];
  97661. destArray[index + 1] = srcData[srcPos + 1];
  97662. destArray[index + 2] = srcData[srcPos + 2];
  97663. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  97664. index += 4;
  97665. }
  97666. }
  97667. return destArray;
  97668. }
  97669. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  97670. };
  97671. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97672. if (DDSTools.StoreLODInAlphaChannel) {
  97673. var destArray = new Float32Array(dataLength);
  97674. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97675. var index = 0;
  97676. for (var y = 0; y < height; y++) {
  97677. for (var x = 0; x < width; x++) {
  97678. var srcPos = (x + y * width) * 4;
  97679. destArray[index] = srcData[srcPos];
  97680. destArray[index + 1] = srcData[srcPos + 1];
  97681. destArray[index + 2] = srcData[srcPos + 2];
  97682. destArray[index + 3] = lod;
  97683. index += 4;
  97684. }
  97685. }
  97686. return destArray;
  97687. }
  97688. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  97689. };
  97690. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97691. var destArray = new Uint8Array(dataLength);
  97692. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97693. var index = 0;
  97694. for (var y = 0; y < height; y++) {
  97695. for (var x = 0; x < width; x++) {
  97696. var srcPos = (x + y * width) * 4;
  97697. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  97698. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  97699. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  97700. if (DDSTools.StoreLODInAlphaChannel) {
  97701. destArray[index + 3] = lod;
  97702. }
  97703. else {
  97704. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  97705. }
  97706. index += 4;
  97707. }
  97708. }
  97709. return destArray;
  97710. };
  97711. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97712. var destArray = new Uint8Array(dataLength);
  97713. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97714. var index = 0;
  97715. for (var y = 0; y < height; y++) {
  97716. for (var x = 0; x < width; x++) {
  97717. var srcPos = (x + y * width) * 4;
  97718. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  97719. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  97720. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  97721. if (DDSTools.StoreLODInAlphaChannel) {
  97722. destArray[index + 3] = lod;
  97723. }
  97724. else {
  97725. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  97726. }
  97727. index += 4;
  97728. }
  97729. }
  97730. return destArray;
  97731. };
  97732. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  97733. var byteArray = new Uint8Array(dataLength);
  97734. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97735. var index = 0;
  97736. for (var y = 0; y < height; y++) {
  97737. for (var x = 0; x < width; x++) {
  97738. var srcPos = (x + y * width) * 4;
  97739. byteArray[index] = srcData[srcPos + rOffset];
  97740. byteArray[index + 1] = srcData[srcPos + gOffset];
  97741. byteArray[index + 2] = srcData[srcPos + bOffset];
  97742. byteArray[index + 3] = srcData[srcPos + aOffset];
  97743. index += 4;
  97744. }
  97745. }
  97746. return byteArray;
  97747. };
  97748. DDSTools._ExtractLongWordOrder = function (value) {
  97749. if (value === 0 || value === 255 || value === -16777216) {
  97750. return 0;
  97751. }
  97752. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  97753. };
  97754. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  97755. var byteArray = new Uint8Array(dataLength);
  97756. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97757. var index = 0;
  97758. for (var y = 0; y < height; y++) {
  97759. for (var x = 0; x < width; x++) {
  97760. var srcPos = (x + y * width) * 3;
  97761. byteArray[index] = srcData[srcPos + rOffset];
  97762. byteArray[index + 1] = srcData[srcPos + gOffset];
  97763. byteArray[index + 2] = srcData[srcPos + bOffset];
  97764. index += 3;
  97765. }
  97766. }
  97767. return byteArray;
  97768. };
  97769. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  97770. var byteArray = new Uint8Array(dataLength);
  97771. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97772. var index = 0;
  97773. for (var y = 0; y < height; y++) {
  97774. for (var x = 0; x < width; x++) {
  97775. var srcPos = (x + y * width);
  97776. byteArray[index] = srcData[srcPos];
  97777. index++;
  97778. }
  97779. }
  97780. return byteArray;
  97781. };
  97782. /**
  97783. * Uploads DDS Levels to a Babylon Texture
  97784. * @hidden
  97785. */
  97786. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  97787. if (lodIndex === void 0) { lodIndex = -1; }
  97788. var sphericalPolynomialFaces = null;
  97789. if (info.sphericalPolynomial) {
  97790. sphericalPolynomialFaces = new Array();
  97791. }
  97792. var ext = engine.getCaps().s3tc;
  97793. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97794. var fourCC, width, height, dataLength = 0, dataOffset;
  97795. var byteArray, mipmapCount, mip;
  97796. var internalCompressedFormat = 0;
  97797. var blockBytes = 1;
  97798. if (header[off_magic] !== DDS_MAGIC) {
  97799. BABYLON.Tools.Error("Invalid magic number in DDS header");
  97800. return;
  97801. }
  97802. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  97803. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  97804. return;
  97805. }
  97806. if (info.isCompressed && !ext) {
  97807. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  97808. return;
  97809. }
  97810. var bpp = header[off_RGBbpp];
  97811. dataOffset = header[off_size] + 4;
  97812. var computeFormats = false;
  97813. if (info.isFourCC) {
  97814. fourCC = header[off_pfFourCC];
  97815. switch (fourCC) {
  97816. case FOURCC_DXT1:
  97817. blockBytes = 8;
  97818. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  97819. break;
  97820. case FOURCC_DXT3:
  97821. blockBytes = 16;
  97822. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  97823. break;
  97824. case FOURCC_DXT5:
  97825. blockBytes = 16;
  97826. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  97827. break;
  97828. case FOURCC_D3DFMT_R16G16B16A16F:
  97829. computeFormats = true;
  97830. break;
  97831. case FOURCC_D3DFMT_R32G32B32A32F:
  97832. computeFormats = true;
  97833. break;
  97834. case FOURCC_DX10:
  97835. // There is an additionnal header so dataOffset need to be changed
  97836. dataOffset += 5 * 4; // 5 uints
  97837. var supported = false;
  97838. switch (info.dxgiFormat) {
  97839. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  97840. computeFormats = true;
  97841. supported = true;
  97842. break;
  97843. case DXGI_FORMAT_B8G8R8X8_UNORM:
  97844. info.isRGB = true;
  97845. info.isFourCC = false;
  97846. bpp = 32;
  97847. supported = true;
  97848. break;
  97849. }
  97850. if (supported) {
  97851. break;
  97852. }
  97853. default:
  97854. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  97855. return;
  97856. }
  97857. }
  97858. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  97859. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  97860. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  97861. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  97862. if (computeFormats) {
  97863. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  97864. }
  97865. mipmapCount = 1;
  97866. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  97867. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97868. }
  97869. for (var face = 0; face < faces; face++) {
  97870. width = header[off_width];
  97871. height = header[off_height];
  97872. for (mip = 0; mip < mipmapCount; ++mip) {
  97873. if (lodIndex === -1 || lodIndex === mip) {
  97874. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  97875. var i = (lodIndex === -1) ? mip : 0;
  97876. if (!info.isCompressed && info.isFourCC) {
  97877. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97878. dataLength = width * height * 4;
  97879. var floatArray = null;
  97880. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  97881. if (bpp === 128) {
  97882. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97883. if (sphericalPolynomialFaces && i == 0) {
  97884. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97885. }
  97886. }
  97887. else if (bpp === 64) {
  97888. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97889. if (sphericalPolynomialFaces && i == 0) {
  97890. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97891. }
  97892. }
  97893. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97894. }
  97895. else {
  97896. if (bpp === 128) {
  97897. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97898. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97899. if (sphericalPolynomialFaces && i == 0) {
  97900. sphericalPolynomialFaces.push(floatArray);
  97901. }
  97902. }
  97903. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  97904. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97905. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97906. if (sphericalPolynomialFaces && i == 0) {
  97907. sphericalPolynomialFaces.push(floatArray);
  97908. }
  97909. }
  97910. else { // 64
  97911. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97912. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97913. if (sphericalPolynomialFaces && i == 0) {
  97914. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97915. }
  97916. }
  97917. }
  97918. if (floatArray) {
  97919. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  97920. }
  97921. }
  97922. else if (info.isRGB) {
  97923. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97924. if (bpp === 24) {
  97925. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  97926. dataLength = width * height * 3;
  97927. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  97928. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97929. }
  97930. else { // 32
  97931. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97932. dataLength = width * height * 4;
  97933. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  97934. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97935. }
  97936. }
  97937. else if (info.isLuminance) {
  97938. var unpackAlignment = engine._getUnpackAlignement();
  97939. var unpaddedRowSize = width;
  97940. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  97941. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  97942. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  97943. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  97944. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97945. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97946. }
  97947. else {
  97948. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  97949. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  97950. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97951. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  97952. }
  97953. }
  97954. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  97955. width *= 0.5;
  97956. height *= 0.5;
  97957. width = Math.max(1.0, width);
  97958. height = Math.max(1.0, height);
  97959. }
  97960. if (currentFace !== undefined) {
  97961. // Loading a single face
  97962. break;
  97963. }
  97964. }
  97965. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  97966. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  97967. size: header[off_width],
  97968. right: sphericalPolynomialFaces[0],
  97969. left: sphericalPolynomialFaces[1],
  97970. up: sphericalPolynomialFaces[2],
  97971. down: sphericalPolynomialFaces[3],
  97972. front: sphericalPolynomialFaces[4],
  97973. back: sphericalPolynomialFaces[5],
  97974. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  97975. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  97976. gammaSpace: false,
  97977. });
  97978. }
  97979. else {
  97980. info.sphericalPolynomial = undefined;
  97981. }
  97982. };
  97983. /**
  97984. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  97985. */
  97986. DDSTools.StoreLODInAlphaChannel = false;
  97987. return DDSTools;
  97988. }());
  97989. BABYLON.DDSTools = DDSTools;
  97990. })(BABYLON || (BABYLON = {}));
  97991. //# sourceMappingURL=babylon.dds.js.map
  97992. var BABYLON;
  97993. (function (BABYLON) {
  97994. /**
  97995. * Implementation of the DDS Texture Loader.
  97996. */
  97997. var DDSTextureLoader = /** @class */ (function () {
  97998. function DDSTextureLoader() {
  97999. /**
  98000. * Defines wether the loader supports cascade loading the different faces.
  98001. */
  98002. this.supportCascades = true;
  98003. }
  98004. /**
  98005. * This returns if the loader support the current file information.
  98006. * @param extension defines the file extension of the file being loaded
  98007. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98008. * @param fallback defines the fallback internal texture if any
  98009. * @param isBase64 defines whether the texture is encoded as a base64
  98010. * @param isBuffer defines whether the texture data are stored as a buffer
  98011. * @returns true if the loader can load the specified file
  98012. */
  98013. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98014. return extension.indexOf(".dds") === 0;
  98015. };
  98016. /**
  98017. * Transform the url before loading if required.
  98018. * @param rootUrl the url of the texture
  98019. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98020. * @returns the transformed texture
  98021. */
  98022. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98023. return rootUrl;
  98024. };
  98025. /**
  98026. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98027. * @param rootUrl the url of the texture
  98028. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98029. * @returns the fallback texture
  98030. */
  98031. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98032. return null;
  98033. };
  98034. /**
  98035. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98036. * @param data contains the texture data
  98037. * @param texture defines the BabylonJS internal texture
  98038. * @param createPolynomials will be true if polynomials have been requested
  98039. * @param onLoad defines the callback to trigger once the texture is ready
  98040. * @param onError defines the callback to trigger in case of error
  98041. */
  98042. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  98043. var engine = texture.getEngine();
  98044. var info;
  98045. var loadMipmap = false;
  98046. if (Array.isArray(imgs)) {
  98047. for (var index = 0; index < imgs.length; index++) {
  98048. var data_1 = imgs[index];
  98049. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  98050. texture.width = info.width;
  98051. texture.height = info.height;
  98052. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  98053. engine._unpackFlipY(info.isCompressed);
  98054. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  98055. if (!info.isFourCC && info.mipmapCount === 1) {
  98056. engine.generateMipMapsForCubemap(texture);
  98057. }
  98058. }
  98059. }
  98060. else {
  98061. var data = imgs;
  98062. info = BABYLON.DDSTools.GetDDSInfo(data);
  98063. texture.width = info.width;
  98064. texture.height = info.height;
  98065. if (createPolynomials) {
  98066. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  98067. }
  98068. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  98069. engine._unpackFlipY(info.isCompressed);
  98070. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  98071. if (!info.isFourCC && info.mipmapCount === 1) {
  98072. engine.generateMipMapsForCubemap(texture);
  98073. }
  98074. }
  98075. engine._setCubeMapTextureParams(loadMipmap);
  98076. texture.isReady = true;
  98077. if (onLoad) {
  98078. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  98079. }
  98080. };
  98081. /**
  98082. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98083. * @param data contains the texture data
  98084. * @param texture defines the BabylonJS internal texture
  98085. * @param callback defines the method to call once ready to upload
  98086. */
  98087. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  98088. var info = BABYLON.DDSTools.GetDDSInfo(data);
  98089. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  98090. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  98091. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  98092. });
  98093. };
  98094. return DDSTextureLoader;
  98095. }());
  98096. // Register the loader.
  98097. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  98098. })(BABYLON || (BABYLON = {}));
  98099. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  98100. var BABYLON;
  98101. (function (BABYLON) {
  98102. /**
  98103. * Based on jsTGALoader - Javascript loader for TGA file
  98104. * By Vincent Thibault
  98105. * @see http://blog.robrowser.com/javascript-tga-loader.html
  98106. */
  98107. var TGATools = /** @class */ (function () {
  98108. function TGATools() {
  98109. }
  98110. /**
  98111. * Gets the header of a TGA file
  98112. * @param data defines the TGA data
  98113. * @returns the header
  98114. */
  98115. TGATools.GetTGAHeader = function (data) {
  98116. var offset = 0;
  98117. var header = {
  98118. id_length: data[offset++],
  98119. colormap_type: data[offset++],
  98120. image_type: data[offset++],
  98121. colormap_index: data[offset++] | data[offset++] << 8,
  98122. colormap_length: data[offset++] | data[offset++] << 8,
  98123. colormap_size: data[offset++],
  98124. origin: [
  98125. data[offset++] | data[offset++] << 8,
  98126. data[offset++] | data[offset++] << 8
  98127. ],
  98128. width: data[offset++] | data[offset++] << 8,
  98129. height: data[offset++] | data[offset++] << 8,
  98130. pixel_size: data[offset++],
  98131. flags: data[offset++]
  98132. };
  98133. return header;
  98134. };
  98135. /**
  98136. * Uploads TGA content to a Babylon Texture
  98137. * @hidden
  98138. */
  98139. TGATools.UploadContent = function (texture, data) {
  98140. // Not enough data to contain header ?
  98141. if (data.length < 19) {
  98142. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  98143. return;
  98144. }
  98145. // Read Header
  98146. var offset = 18;
  98147. var header = TGATools.GetTGAHeader(data);
  98148. // Assume it's a valid Targa file.
  98149. if (header.id_length + offset > data.length) {
  98150. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  98151. return;
  98152. }
  98153. // Skip not needed data
  98154. offset += header.id_length;
  98155. var use_rle = false;
  98156. var use_pal = false;
  98157. var use_grey = false;
  98158. // Get some informations.
  98159. switch (header.image_type) {
  98160. case TGATools._TYPE_RLE_INDEXED:
  98161. use_rle = true;
  98162. case TGATools._TYPE_INDEXED:
  98163. use_pal = true;
  98164. break;
  98165. case TGATools._TYPE_RLE_RGB:
  98166. use_rle = true;
  98167. case TGATools._TYPE_RGB:
  98168. // use_rgb = true;
  98169. break;
  98170. case TGATools._TYPE_RLE_GREY:
  98171. use_rle = true;
  98172. case TGATools._TYPE_GREY:
  98173. use_grey = true;
  98174. break;
  98175. }
  98176. var pixel_data;
  98177. // var numAlphaBits = header.flags & 0xf;
  98178. var pixel_size = header.pixel_size >> 3;
  98179. var pixel_total = header.width * header.height * pixel_size;
  98180. // Read palettes
  98181. var palettes;
  98182. if (use_pal) {
  98183. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  98184. }
  98185. // Read LRE
  98186. if (use_rle) {
  98187. pixel_data = new Uint8Array(pixel_total);
  98188. var c, count, i;
  98189. var localOffset = 0;
  98190. var pixels = new Uint8Array(pixel_size);
  98191. while (offset < pixel_total && localOffset < pixel_total) {
  98192. c = data[offset++];
  98193. count = (c & 0x7f) + 1;
  98194. // RLE pixels
  98195. if (c & 0x80) {
  98196. // Bind pixel tmp array
  98197. for (i = 0; i < pixel_size; ++i) {
  98198. pixels[i] = data[offset++];
  98199. }
  98200. // Copy pixel array
  98201. for (i = 0; i < count; ++i) {
  98202. pixel_data.set(pixels, localOffset + i * pixel_size);
  98203. }
  98204. localOffset += pixel_size * count;
  98205. }
  98206. // Raw pixels
  98207. else {
  98208. count *= pixel_size;
  98209. for (i = 0; i < count; ++i) {
  98210. pixel_data[localOffset + i] = data[offset++];
  98211. }
  98212. localOffset += count;
  98213. }
  98214. }
  98215. }
  98216. // RAW Pixels
  98217. else {
  98218. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  98219. }
  98220. // Load to texture
  98221. var x_start, y_start, x_step, y_step, y_end, x_end;
  98222. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  98223. default:
  98224. case TGATools._ORIGIN_UL:
  98225. x_start = 0;
  98226. x_step = 1;
  98227. x_end = header.width;
  98228. y_start = 0;
  98229. y_step = 1;
  98230. y_end = header.height;
  98231. break;
  98232. case TGATools._ORIGIN_BL:
  98233. x_start = 0;
  98234. x_step = 1;
  98235. x_end = header.width;
  98236. y_start = header.height - 1;
  98237. y_step = -1;
  98238. y_end = -1;
  98239. break;
  98240. case TGATools._ORIGIN_UR:
  98241. x_start = header.width - 1;
  98242. x_step = -1;
  98243. x_end = -1;
  98244. y_start = 0;
  98245. y_step = 1;
  98246. y_end = header.height;
  98247. break;
  98248. case TGATools._ORIGIN_BR:
  98249. x_start = header.width - 1;
  98250. x_step = -1;
  98251. x_end = -1;
  98252. y_start = header.height - 1;
  98253. y_step = -1;
  98254. y_end = -1;
  98255. break;
  98256. }
  98257. // Load the specify method
  98258. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  98259. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  98260. var engine = texture.getEngine();
  98261. engine._uploadDataToTextureDirectly(texture, imageData);
  98262. };
  98263. /** @hidden */
  98264. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98265. var image = pixel_data, colormap = palettes;
  98266. var width = header.width, height = header.height;
  98267. var color, i = 0, x, y;
  98268. var imageData = new Uint8Array(width * height * 4);
  98269. for (y = y_start; y !== y_end; y += y_step) {
  98270. for (x = x_start; x !== x_end; x += x_step, i++) {
  98271. color = image[i];
  98272. imageData[(x + width * y) * 4 + 3] = 255;
  98273. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  98274. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  98275. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  98276. }
  98277. }
  98278. return imageData;
  98279. };
  98280. /** @hidden */
  98281. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98282. var image = pixel_data;
  98283. var width = header.width, height = header.height;
  98284. var color, i = 0, x, y;
  98285. var imageData = new Uint8Array(width * height * 4);
  98286. for (y = y_start; y !== y_end; y += y_step) {
  98287. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98288. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  98289. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  98290. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  98291. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  98292. imageData[(x + width * y) * 4 + 0] = r;
  98293. imageData[(x + width * y) * 4 + 1] = g;
  98294. imageData[(x + width * y) * 4 + 2] = b;
  98295. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  98296. }
  98297. }
  98298. return imageData;
  98299. };
  98300. /** @hidden */
  98301. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98302. var image = pixel_data;
  98303. var width = header.width, height = header.height;
  98304. var i = 0, x, y;
  98305. var imageData = new Uint8Array(width * height * 4);
  98306. for (y = y_start; y !== y_end; y += y_step) {
  98307. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  98308. imageData[(x + width * y) * 4 + 3] = 255;
  98309. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98310. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98311. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98312. }
  98313. }
  98314. return imageData;
  98315. };
  98316. /** @hidden */
  98317. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98318. var image = pixel_data;
  98319. var width = header.width, height = header.height;
  98320. var i = 0, x, y;
  98321. var imageData = new Uint8Array(width * height * 4);
  98322. for (y = y_start; y !== y_end; y += y_step) {
  98323. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  98324. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98325. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98326. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98327. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  98328. }
  98329. }
  98330. return imageData;
  98331. };
  98332. /** @hidden */
  98333. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98334. var image = pixel_data;
  98335. var width = header.width, height = header.height;
  98336. var color, i = 0, x, y;
  98337. var imageData = new Uint8Array(width * height * 4);
  98338. for (y = y_start; y !== y_end; y += y_step) {
  98339. for (x = x_start; x !== x_end; x += x_step, i++) {
  98340. color = image[i];
  98341. imageData[(x + width * y) * 4 + 0] = color;
  98342. imageData[(x + width * y) * 4 + 1] = color;
  98343. imageData[(x + width * y) * 4 + 2] = color;
  98344. imageData[(x + width * y) * 4 + 3] = 255;
  98345. }
  98346. }
  98347. return imageData;
  98348. };
  98349. /** @hidden */
  98350. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98351. var image = pixel_data;
  98352. var width = header.width, height = header.height;
  98353. var i = 0, x, y;
  98354. var imageData = new Uint8Array(width * height * 4);
  98355. for (y = y_start; y !== y_end; y += y_step) {
  98356. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98357. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  98358. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  98359. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98360. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  98361. }
  98362. }
  98363. return imageData;
  98364. };
  98365. //private static _TYPE_NO_DATA = 0;
  98366. TGATools._TYPE_INDEXED = 1;
  98367. TGATools._TYPE_RGB = 2;
  98368. TGATools._TYPE_GREY = 3;
  98369. TGATools._TYPE_RLE_INDEXED = 9;
  98370. TGATools._TYPE_RLE_RGB = 10;
  98371. TGATools._TYPE_RLE_GREY = 11;
  98372. TGATools._ORIGIN_MASK = 0x30;
  98373. TGATools._ORIGIN_SHIFT = 0x04;
  98374. TGATools._ORIGIN_BL = 0x00;
  98375. TGATools._ORIGIN_BR = 0x01;
  98376. TGATools._ORIGIN_UL = 0x02;
  98377. TGATools._ORIGIN_UR = 0x03;
  98378. return TGATools;
  98379. }());
  98380. BABYLON.TGATools = TGATools;
  98381. })(BABYLON || (BABYLON = {}));
  98382. //# sourceMappingURL=babylon.tga.js.map
  98383. var BABYLON;
  98384. (function (BABYLON) {
  98385. /**
  98386. * Implementation of the TGA Texture Loader.
  98387. */
  98388. var TGATextureLoader = /** @class */ (function () {
  98389. function TGATextureLoader() {
  98390. /**
  98391. * Defines wether the loader supports cascade loading the different faces.
  98392. */
  98393. this.supportCascades = false;
  98394. }
  98395. /**
  98396. * This returns if the loader support the current file information.
  98397. * @param extension defines the file extension of the file being loaded
  98398. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98399. * @param fallback defines the fallback internal texture if any
  98400. * @param isBase64 defines whether the texture is encoded as a base64
  98401. * @param isBuffer defines whether the texture data are stored as a buffer
  98402. * @returns true if the loader can load the specified file
  98403. */
  98404. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98405. return extension.indexOf(".tga") === 0;
  98406. };
  98407. /**
  98408. * Transform the url before loading if required.
  98409. * @param rootUrl the url of the texture
  98410. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98411. * @returns the transformed texture
  98412. */
  98413. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98414. return rootUrl;
  98415. };
  98416. /**
  98417. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98418. * @param rootUrl the url of the texture
  98419. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98420. * @returns the fallback texture
  98421. */
  98422. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98423. return null;
  98424. };
  98425. /**
  98426. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98427. * @param data contains the texture data
  98428. * @param texture defines the BabylonJS internal texture
  98429. * @param createPolynomials will be true if polynomials have been requested
  98430. * @param onLoad defines the callback to trigger once the texture is ready
  98431. * @param onError defines the callback to trigger in case of error
  98432. */
  98433. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98434. throw ".env not supported in Cube.";
  98435. };
  98436. /**
  98437. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98438. * @param data contains the texture data
  98439. * @param texture defines the BabylonJS internal texture
  98440. * @param callback defines the method to call once ready to upload
  98441. */
  98442. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  98443. var uintData = new Uint8Array(data);
  98444. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  98445. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  98446. BABYLON.TGATools.UploadContent(texture, uintData);
  98447. });
  98448. };
  98449. return TGATextureLoader;
  98450. }());
  98451. // Register the loader.
  98452. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  98453. })(BABYLON || (BABYLON = {}));
  98454. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  98455. var BABYLON;
  98456. (function (BABYLON) {
  98457. /**
  98458. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  98459. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  98460. */
  98461. var KhronosTextureContainer = /** @class */ (function () {
  98462. /**
  98463. * Creates a new KhronosTextureContainer
  98464. * @param arrayBuffer contents of the KTX container file
  98465. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  98466. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  98467. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  98468. */
  98469. function KhronosTextureContainer(
  98470. /** contents of the KTX container file */
  98471. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  98472. this.arrayBuffer = arrayBuffer;
  98473. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  98474. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  98475. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  98476. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  98477. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  98478. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  98479. BABYLON.Tools.Error("texture missing KTX identifier");
  98480. return;
  98481. }
  98482. // load the reset of the header in native 32 bit int
  98483. var header = new Int32Array(this.arrayBuffer, 12, 13);
  98484. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  98485. var oppositeEndianess = header[0] === 0x01020304;
  98486. // read all the header elements in order they exist in the file, without modification (sans endainness)
  98487. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  98488. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  98489. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  98490. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  98491. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  98492. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  98493. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  98494. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  98495. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  98496. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  98497. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  98498. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  98499. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  98500. if (this.glType !== 0) {
  98501. BABYLON.Tools.Error("only compressed formats currently supported");
  98502. return;
  98503. }
  98504. else {
  98505. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  98506. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  98507. }
  98508. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  98509. BABYLON.Tools.Error("only 2D textures currently supported");
  98510. return;
  98511. }
  98512. if (this.numberOfArrayElements !== 0) {
  98513. BABYLON.Tools.Error("texture arrays not currently supported");
  98514. return;
  98515. }
  98516. if (this.numberOfFaces !== facesExpected) {
  98517. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  98518. return;
  98519. }
  98520. // we now have a completely validated file, so could use existence of loadType as success
  98521. // would need to make this more elaborate & adjust checks above to support more than one load type
  98522. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  98523. }
  98524. //
  98525. /**
  98526. * Revert the endianness of a value.
  98527. * Not as fast hardware based, but will probably never need to use
  98528. * @param val defines the value to convert
  98529. * @returns the new value
  98530. */
  98531. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  98532. return ((val & 0xFF) << 24)
  98533. | ((val & 0xFF00) << 8)
  98534. | ((val >> 8) & 0xFF00)
  98535. | ((val >> 24) & 0xFF);
  98536. };
  98537. /**
  98538. * Uploads KTX content to a Babylon Texture.
  98539. * It is assumed that the texture has already been created & is currently bound
  98540. * @hidden
  98541. */
  98542. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  98543. switch (this.loadType) {
  98544. case KhronosTextureContainer.COMPRESSED_2D:
  98545. this._upload2DCompressedLevels(texture, loadMipmaps);
  98546. break;
  98547. case KhronosTextureContainer.TEX_2D:
  98548. case KhronosTextureContainer.COMPRESSED_3D:
  98549. case KhronosTextureContainer.TEX_3D:
  98550. }
  98551. };
  98552. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  98553. // initialize width & height for level 1
  98554. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  98555. var width = this.pixelWidth;
  98556. var height = this.pixelHeight;
  98557. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  98558. for (var level = 0; level < mipmapCount; level++) {
  98559. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  98560. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  98561. for (var face = 0; face < this.numberOfFaces; face++) {
  98562. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  98563. var engine = texture.getEngine();
  98564. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  98565. dataOffset += imageSize; // add size of the image for the next face/mipmap
  98566. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  98567. }
  98568. width = Math.max(1.0, width * 0.5);
  98569. height = Math.max(1.0, height * 0.5);
  98570. }
  98571. };
  98572. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  98573. // load types
  98574. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  98575. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  98576. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  98577. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  98578. return KhronosTextureContainer;
  98579. }());
  98580. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  98581. })(BABYLON || (BABYLON = {}));
  98582. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  98583. var BABYLON;
  98584. (function (BABYLON) {
  98585. /**
  98586. * Implementation of the KTX Texture Loader.
  98587. */
  98588. var KTXTextureLoader = /** @class */ (function () {
  98589. function KTXTextureLoader() {
  98590. /**
  98591. * Defines wether the loader supports cascade loading the different faces.
  98592. */
  98593. this.supportCascades = false;
  98594. }
  98595. /**
  98596. * This returns if the loader support the current file information.
  98597. * @param extension defines the file extension of the file being loaded
  98598. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98599. * @param fallback defines the fallback internal texture if any
  98600. * @param isBase64 defines whether the texture is encoded as a base64
  98601. * @param isBuffer defines whether the texture data are stored as a buffer
  98602. * @returns true if the loader can load the specified file
  98603. */
  98604. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98605. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  98606. return true;
  98607. }
  98608. return false;
  98609. };
  98610. /**
  98611. * Transform the url before loading if required.
  98612. * @param rootUrl the url of the texture
  98613. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98614. * @returns the transformed texture
  98615. */
  98616. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98617. var lastDot = rootUrl.lastIndexOf('.');
  98618. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  98619. };
  98620. /**
  98621. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98622. * @param rootUrl the url of the texture
  98623. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98624. * @returns the fallback texture
  98625. */
  98626. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98627. // remove the format appended to the rootUrl in the original createCubeTexture call.
  98628. var exp = new RegExp("" + textureFormatInUse + "$");
  98629. return rootUrl.replace(exp, "");
  98630. };
  98631. /**
  98632. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98633. * @param data contains the texture data
  98634. * @param texture defines the BabylonJS internal texture
  98635. * @param createPolynomials will be true if polynomials have been requested
  98636. * @param onLoad defines the callback to trigger once the texture is ready
  98637. * @param onError defines the callback to trigger in case of error
  98638. */
  98639. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98640. if (Array.isArray(data)) {
  98641. return;
  98642. }
  98643. var engine = texture.getEngine();
  98644. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  98645. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  98646. engine._unpackFlipY(true);
  98647. ktx.uploadLevels(texture, texture.generateMipMaps);
  98648. texture.width = ktx.pixelWidth;
  98649. texture.height = ktx.pixelHeight;
  98650. engine._setCubeMapTextureParams(loadMipmap);
  98651. texture.isReady = true;
  98652. };
  98653. /**
  98654. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98655. * @param data contains the texture data
  98656. * @param texture defines the BabylonJS internal texture
  98657. * @param callback defines the method to call once ready to upload
  98658. */
  98659. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  98660. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  98661. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  98662. ktx.uploadLevels(texture, texture.generateMipMaps);
  98663. });
  98664. };
  98665. return KTXTextureLoader;
  98666. }());
  98667. // Register the loader.
  98668. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  98669. })(BABYLON || (BABYLON = {}));
  98670. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  98671. var BABYLON;
  98672. (function (BABYLON) {
  98673. /**
  98674. * Sets of helpers addressing the serialization and deserialization of environment texture
  98675. * stored in a BabylonJS env file.
  98676. * Those files are usually stored as .env files.
  98677. */
  98678. var EnvironmentTextureTools = /** @class */ (function () {
  98679. function EnvironmentTextureTools() {
  98680. }
  98681. /**
  98682. * Gets the environment info from an env file.
  98683. * @param data The array buffer containing the .env bytes.
  98684. * @returns the environment file info (the json header) if successfully parsed.
  98685. */
  98686. EnvironmentTextureTools.GetEnvInfo = function (data) {
  98687. var dataView = new DataView(data);
  98688. var pos = 0;
  98689. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98690. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  98691. BABYLON.Tools.Error('Not a babylon environment map');
  98692. return null;
  98693. }
  98694. }
  98695. // Read json manifest - collect characters up to null terminator
  98696. var manifestString = '';
  98697. var charCode = 0x00;
  98698. while ((charCode = dataView.getUint8(pos++))) {
  98699. manifestString += String.fromCharCode(charCode);
  98700. }
  98701. var manifest = JSON.parse(manifestString);
  98702. if (manifest.specular) {
  98703. // Extend the header with the position of the payload.
  98704. manifest.specular.specularDataPosition = pos;
  98705. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  98706. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  98707. }
  98708. return manifest;
  98709. };
  98710. /**
  98711. * Creates an environment texture from a loaded cube texture.
  98712. * @param texture defines the cube texture to convert in env file
  98713. * @return a promise containing the environment data if succesfull.
  98714. */
  98715. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  98716. var _this = this;
  98717. var internalTexture = texture.getInternalTexture();
  98718. if (!internalTexture) {
  98719. return Promise.reject("The cube texture is invalid.");
  98720. }
  98721. if (!texture._prefiltered) {
  98722. return Promise.reject("The cube texture is invalid (not prefiltered).");
  98723. }
  98724. var engine = internalTexture.getEngine();
  98725. if (engine && engine.premultipliedAlpha) {
  98726. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  98727. }
  98728. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  98729. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  98730. }
  98731. var canvas = engine.getRenderingCanvas();
  98732. if (!canvas) {
  98733. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  98734. }
  98735. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98736. if (!engine.getCaps().textureFloatRender) {
  98737. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98738. if (!engine.getCaps().textureHalfFloatRender) {
  98739. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  98740. }
  98741. }
  98742. var cubeWidth = internalTexture.width;
  98743. var hostingScene = new BABYLON.Scene(engine);
  98744. var specularTextures = {};
  98745. var promises = [];
  98746. // Read and collect all mipmaps data from the cube.
  98747. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  98748. mipmapsCount = Math.round(mipmapsCount);
  98749. var _loop_1 = function (i) {
  98750. var faceWidth = Math.pow(2, mipmapsCount - i);
  98751. var _loop_2 = function (face) {
  98752. var data = texture.readPixels(face, i);
  98753. // Creates a temp texture with the face data.
  98754. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  98755. // And rgbdEncode them.
  98756. var promise = new Promise(function (resolve, reject) {
  98757. 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);
  98758. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  98759. rgbdPostProcess.onApply = function (effect) {
  98760. effect._bindTexture("textureSampler", tempTexture);
  98761. };
  98762. // As the process needs to happen on the main canvas, keep track of the current size
  98763. var currentW = engine.getRenderWidth();
  98764. var currentH = engine.getRenderHeight();
  98765. // Set the desired size for the texture
  98766. engine.setSize(faceWidth, faceWidth);
  98767. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  98768. // Reading datas from WebGL
  98769. BABYLON.Tools.ToBlob(canvas, function (blob) {
  98770. var fileReader = new FileReader();
  98771. fileReader.onload = function (event) {
  98772. var arrayBuffer = event.target.result;
  98773. specularTextures[i * 6 + face] = arrayBuffer;
  98774. resolve();
  98775. };
  98776. fileReader.readAsArrayBuffer(blob);
  98777. });
  98778. // Reapply the previous canvas size
  98779. engine.setSize(currentW, currentH);
  98780. });
  98781. });
  98782. promises.push(promise);
  98783. };
  98784. // All faces of the cube.
  98785. for (var face = 0; face < 6; face++) {
  98786. _loop_2(face);
  98787. }
  98788. };
  98789. for (var i = 0; i <= mipmapsCount; i++) {
  98790. _loop_1(i);
  98791. }
  98792. // Once all the textures haves been collected as RGBD stored in PNGs
  98793. return Promise.all(promises).then(function () {
  98794. // We can delete the hosting scene keeping track of all the creation objects
  98795. hostingScene.dispose();
  98796. // Creates the json header for the env texture
  98797. var info = {
  98798. version: 1,
  98799. width: cubeWidth,
  98800. irradiance: _this._CreateEnvTextureIrradiance(texture),
  98801. specular: {
  98802. mipmaps: [],
  98803. lodGenerationScale: texture.lodGenerationScale
  98804. }
  98805. };
  98806. // Sets the specular image data information
  98807. var position = 0;
  98808. for (var i = 0; i <= mipmapsCount; i++) {
  98809. for (var face = 0; face < 6; face++) {
  98810. var byteLength = specularTextures[i * 6 + face].byteLength;
  98811. info.specular.mipmaps.push({
  98812. length: byteLength,
  98813. position: position
  98814. });
  98815. position += byteLength;
  98816. }
  98817. }
  98818. // Encode the JSON as an array buffer
  98819. var infoString = JSON.stringify(info);
  98820. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  98821. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  98822. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  98823. infoView[i] = infoString.charCodeAt(i);
  98824. }
  98825. // Ends up with a null terminator for easier parsing
  98826. infoView[infoString.length] = 0x00;
  98827. // Computes the final required size and creates the storage
  98828. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  98829. var finalBuffer = new ArrayBuffer(totalSize);
  98830. var finalBufferView = new Uint8Array(finalBuffer);
  98831. var dataView = new DataView(finalBuffer);
  98832. // Copy the magic bytes identifying the file in
  98833. var pos = 0;
  98834. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98835. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  98836. }
  98837. // Add the json info
  98838. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  98839. pos += infoBuffer.byteLength;
  98840. // Finally inserts the texture data
  98841. for (var i = 0; i <= mipmapsCount; i++) {
  98842. for (var face = 0; face < 6; face++) {
  98843. var dataBuffer = specularTextures[i * 6 + face];
  98844. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  98845. pos += dataBuffer.byteLength;
  98846. }
  98847. }
  98848. // Voila
  98849. return finalBuffer;
  98850. });
  98851. };
  98852. /**
  98853. * Creates a JSON representation of the spherical data.
  98854. * @param texture defines the texture containing the polynomials
  98855. * @return the JSON representation of the spherical info
  98856. */
  98857. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  98858. var polynmials = texture.sphericalPolynomial;
  98859. if (polynmials == null) {
  98860. return null;
  98861. }
  98862. return {
  98863. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  98864. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  98865. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  98866. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  98867. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  98868. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  98869. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  98870. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  98871. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  98872. };
  98873. };
  98874. /**
  98875. * Uploads the texture info contained in the env file to the GPU.
  98876. * @param texture defines the internal texture to upload to
  98877. * @param arrayBuffer defines the buffer cotaining the data to load
  98878. * @param info defines the texture info retrieved through the GetEnvInfo method
  98879. * @returns a promise
  98880. */
  98881. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  98882. if (info.version !== 1) {
  98883. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  98884. }
  98885. var specularInfo = info.specular;
  98886. if (!specularInfo) {
  98887. // Nothing else parsed so far
  98888. return Promise.resolve();
  98889. }
  98890. // Double checks the enclosed info
  98891. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  98892. mipmapsCount = Math.round(mipmapsCount) + 1;
  98893. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  98894. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  98895. }
  98896. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  98897. var imageData = new Array(mipmapsCount);
  98898. for (var i = 0; i < mipmapsCount; i++) {
  98899. imageData[i] = new Array(6);
  98900. for (var face = 0; face < 6; face++) {
  98901. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  98902. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  98903. }
  98904. }
  98905. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  98906. };
  98907. /**
  98908. * Uploads the levels of image data to the GPU.
  98909. * @param texture defines the internal texture to upload to
  98910. * @param imageData defines the array buffer views of image data [mipmap][face]
  98911. * @returns a promise
  98912. */
  98913. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  98914. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  98915. throw new Error("Texture size must be a power of two");
  98916. }
  98917. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  98918. // Gets everything ready.
  98919. var engine = texture.getEngine();
  98920. var expandTexture = false;
  98921. var generateNonLODTextures = false;
  98922. var rgbdPostProcess = null;
  98923. var cubeRtt = null;
  98924. var lodTextures = null;
  98925. var caps = engine.getCaps();
  98926. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  98927. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98928. texture.generateMipMaps = true;
  98929. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  98930. // Add extra process if texture lod is not supported
  98931. if (!caps.textureLOD) {
  98932. expandTexture = false;
  98933. generateNonLODTextures = true;
  98934. lodTextures = {};
  98935. }
  98936. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  98937. else if (engine.webGLVersion < 2) {
  98938. expandTexture = false;
  98939. }
  98940. // If half float available we can uncompress the texture
  98941. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  98942. expandTexture = true;
  98943. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98944. }
  98945. // If full float available we can uncompress the texture
  98946. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  98947. expandTexture = true;
  98948. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98949. }
  98950. // Expand the texture if possible
  98951. if (expandTexture) {
  98952. // Simply run through the decode PP
  98953. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  98954. texture._isRGBD = false;
  98955. texture.invertY = false;
  98956. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  98957. generateDepthBuffer: false,
  98958. generateMipMaps: true,
  98959. generateStencilBuffer: false,
  98960. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  98961. type: texture.type,
  98962. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  98963. });
  98964. }
  98965. else {
  98966. texture._isRGBD = true;
  98967. texture.invertY = true;
  98968. // In case of missing support, applies the same patch than DDS files.
  98969. if (generateNonLODTextures) {
  98970. var mipSlices = 3;
  98971. var scale = texture._lodGenerationScale;
  98972. var offset = texture._lodGenerationOffset;
  98973. for (var i = 0; i < mipSlices; i++) {
  98974. //compute LOD from even spacing in smoothness (matching shader calculation)
  98975. var smoothness = i / (mipSlices - 1);
  98976. var roughness = 1 - smoothness;
  98977. var minLODIndex = offset; // roughness = 0
  98978. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  98979. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  98980. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  98981. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  98982. glTextureFromLod.isCube = true;
  98983. glTextureFromLod.invertY = true;
  98984. glTextureFromLod.generateMipMaps = false;
  98985. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  98986. // Wrap in a base texture for easy binding.
  98987. var lodTexture = new BABYLON.BaseTexture(null);
  98988. lodTexture.isCube = true;
  98989. lodTexture._texture = glTextureFromLod;
  98990. lodTextures[mipmapIndex] = lodTexture;
  98991. switch (i) {
  98992. case 0:
  98993. texture._lodTextureLow = lodTexture;
  98994. break;
  98995. case 1:
  98996. texture._lodTextureMid = lodTexture;
  98997. break;
  98998. case 2:
  98999. texture._lodTextureHigh = lodTexture;
  99000. break;
  99001. }
  99002. }
  99003. }
  99004. }
  99005. var promises = [];
  99006. var _loop_3 = function (i) {
  99007. var _loop_4 = function (face) {
  99008. // Constructs an image element from image data
  99009. var bytes = imageData[i][face];
  99010. var blob = new Blob([bytes], { type: 'image/png' });
  99011. var url = URL.createObjectURL(blob);
  99012. var image = new Image();
  99013. image.src = url;
  99014. // Enqueue promise to upload to the texture.
  99015. var promise = new Promise(function (resolve, reject) {
  99016. image.onload = function () {
  99017. if (expandTexture) {
  99018. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  99019. reject(message);
  99020. }, image);
  99021. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  99022. // Uncompress the data to a RTT
  99023. rgbdPostProcess.onApply = function (effect) {
  99024. effect._bindTexture("textureSampler", tempTexture_1);
  99025. effect.setFloat2("scale", 1, 1);
  99026. };
  99027. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  99028. // Cleanup
  99029. engine.restoreDefaultFramebuffer();
  99030. tempTexture_1.dispose();
  99031. window.URL.revokeObjectURL(url);
  99032. resolve();
  99033. });
  99034. }
  99035. else {
  99036. engine._uploadImageToTexture(texture, image, face, i);
  99037. // Upload the face to the non lod texture support
  99038. if (generateNonLODTextures) {
  99039. var lodTexture = lodTextures[i];
  99040. if (lodTexture) {
  99041. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  99042. }
  99043. }
  99044. resolve();
  99045. }
  99046. };
  99047. image.onerror = function (error) {
  99048. reject(error);
  99049. };
  99050. });
  99051. promises.push(promise);
  99052. };
  99053. // All faces
  99054. for (var face = 0; face < 6; face++) {
  99055. _loop_4(face);
  99056. }
  99057. };
  99058. // All mipmaps up to provided number of images
  99059. for (var i = 0; i < imageData.length; i++) {
  99060. _loop_3(i);
  99061. }
  99062. // Fill remaining mipmaps with black textures.
  99063. if (imageData.length < mipmapsCount) {
  99064. var data = void 0;
  99065. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  99066. var dataLength = size * size * 4;
  99067. switch (texture.type) {
  99068. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  99069. data = new Uint8Array(dataLength);
  99070. break;
  99071. }
  99072. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  99073. data = new Uint16Array(dataLength);
  99074. break;
  99075. }
  99076. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  99077. data = new Float32Array(dataLength);
  99078. break;
  99079. }
  99080. }
  99081. for (var i = imageData.length; i < mipmapsCount; i++) {
  99082. for (var face = 0; face < 6; face++) {
  99083. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  99084. }
  99085. }
  99086. }
  99087. // Once all done, finishes the cleanup and return
  99088. return Promise.all(promises).then(function () {
  99089. // Release temp RTT.
  99090. if (cubeRtt) {
  99091. engine._releaseFramebufferObjects(cubeRtt);
  99092. cubeRtt._swapAndDie(texture);
  99093. }
  99094. // Release temp Post Process.
  99095. if (rgbdPostProcess) {
  99096. rgbdPostProcess.dispose();
  99097. }
  99098. // Flag internal texture as ready in case they are in use.
  99099. if (generateNonLODTextures) {
  99100. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  99101. texture._lodTextureHigh._texture.isReady = true;
  99102. }
  99103. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  99104. texture._lodTextureMid._texture.isReady = true;
  99105. }
  99106. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  99107. texture._lodTextureLow._texture.isReady = true;
  99108. }
  99109. }
  99110. });
  99111. };
  99112. /**
  99113. * Uploads spherical polynomials information to the texture.
  99114. * @param texture defines the texture we are trying to upload the information to
  99115. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  99116. */
  99117. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  99118. if (info.version !== 1) {
  99119. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  99120. }
  99121. var irradianceInfo = info.irradiance;
  99122. if (!irradianceInfo) {
  99123. return;
  99124. }
  99125. var sp = new BABYLON.SphericalPolynomial();
  99126. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  99127. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  99128. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  99129. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  99130. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  99131. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  99132. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  99133. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  99134. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  99135. texture._sphericalPolynomial = sp;
  99136. };
  99137. /**
  99138. * Magic number identifying the env file.
  99139. */
  99140. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  99141. return EnvironmentTextureTools;
  99142. }());
  99143. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  99144. })(BABYLON || (BABYLON = {}));
  99145. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  99146. var BABYLON;
  99147. (function (BABYLON) {
  99148. /**
  99149. * Implementation of the ENV Texture Loader.
  99150. */
  99151. var ENVTextureLoader = /** @class */ (function () {
  99152. function ENVTextureLoader() {
  99153. /**
  99154. * Defines wether the loader supports cascade loading the different faces.
  99155. */
  99156. this.supportCascades = false;
  99157. }
  99158. /**
  99159. * This returns if the loader support the current file information.
  99160. * @param extension defines the file extension of the file being loaded
  99161. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99162. * @param fallback defines the fallback internal texture if any
  99163. * @param isBase64 defines whether the texture is encoded as a base64
  99164. * @param isBuffer defines whether the texture data are stored as a buffer
  99165. * @returns true if the loader can load the specified file
  99166. */
  99167. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99168. return extension.indexOf(".env") === 0;
  99169. };
  99170. /**
  99171. * Transform the url before loading if required.
  99172. * @param rootUrl the url of the texture
  99173. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99174. * @returns the transformed texture
  99175. */
  99176. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99177. return rootUrl;
  99178. };
  99179. /**
  99180. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99181. * @param rootUrl the url of the texture
  99182. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99183. * @returns the fallback texture
  99184. */
  99185. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99186. return null;
  99187. };
  99188. /**
  99189. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99190. * @param data contains the texture data
  99191. * @param texture defines the BabylonJS internal texture
  99192. * @param createPolynomials will be true if polynomials have been requested
  99193. * @param onLoad defines the callback to trigger once the texture is ready
  99194. * @param onError defines the callback to trigger in case of error
  99195. */
  99196. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99197. if (Array.isArray(data)) {
  99198. return;
  99199. }
  99200. data = data;
  99201. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  99202. if (info) {
  99203. texture.width = info.width;
  99204. texture.height = info.width;
  99205. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  99206. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  99207. texture.isReady = true;
  99208. if (onLoad) {
  99209. onLoad();
  99210. }
  99211. });
  99212. }
  99213. else if (onError) {
  99214. onError("Can not parse the environment file", null);
  99215. }
  99216. };
  99217. /**
  99218. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99219. * @param data contains the texture data
  99220. * @param texture defines the BabylonJS internal texture
  99221. * @param callback defines the method to call once ready to upload
  99222. */
  99223. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  99224. throw ".env not supported in 2d.";
  99225. };
  99226. return ENVTextureLoader;
  99227. }());
  99228. // Register the loader.
  99229. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  99230. })(BABYLON || (BABYLON = {}));
  99231. //# sourceMappingURL=babylon.envTextureLoader.js.map
  99232. var BABYLON;
  99233. (function (BABYLON) {
  99234. /**
  99235. * Renders a layer on top of an existing scene
  99236. */
  99237. var UtilityLayerRenderer = /** @class */ (function () {
  99238. /**
  99239. * Instantiates a UtilityLayerRenderer
  99240. * @param originalScene the original scene that will be rendered on top of
  99241. */
  99242. function UtilityLayerRenderer(
  99243. /** the original scene that will be rendered on top of */
  99244. originalScene) {
  99245. var _this = this;
  99246. this.originalScene = originalScene;
  99247. this._pointerCaptures = {};
  99248. this._lastPointerEvents = {};
  99249. /**
  99250. * If the utility layer should automatically be rendered on top of existing scene
  99251. */
  99252. this.shouldRender = true;
  99253. /**
  99254. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  99255. */
  99256. this.onlyCheckPointerDownEvents = true;
  99257. /**
  99258. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  99259. */
  99260. this.processAllEvents = false;
  99261. /**
  99262. * Observable raised when the pointer move from the utility layer scene to the main scene
  99263. */
  99264. this.onPointerOutObservable = new BABYLON.Observable();
  99265. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  99266. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  99267. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  99268. this.utilityLayerScene._allowPostProcessClearColor = false;
  99269. originalScene.getEngine().scenes.pop();
  99270. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  99271. this.utilityLayerScene.detachControl();
  99272. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  99273. if (!_this.processAllEvents) {
  99274. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  99275. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  99276. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  99277. return;
  99278. }
  99279. }
  99280. var pointerEvent = (prePointerInfo.event);
  99281. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  99282. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99283. return;
  99284. }
  99285. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  99286. if (!prePointerInfo.ray && utilityScenePick) {
  99287. prePointerInfo.ray = utilityScenePick.ray;
  99288. }
  99289. // always fire the prepointer oversvable
  99290. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  99291. // allow every non pointer down event to flow to the utility layer
  99292. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  99293. if (!prePointerInfo.skipOnPointerObservable) {
  99294. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99295. }
  99296. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  99297. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99298. }
  99299. return;
  99300. }
  99301. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  99302. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  99303. if (utilityScenePick && utilityScenePick.hit) {
  99304. if (!prePointerInfo.skipOnPointerObservable) {
  99305. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99306. }
  99307. prePointerInfo.skipOnPointerObservable = true;
  99308. }
  99309. }
  99310. else {
  99311. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  99312. var pointerEvent_1 = (prePointerInfo.event);
  99313. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  99314. if (originalScenePick && utilityScenePick) {
  99315. // No pick in utility scene
  99316. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  99317. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99318. // We touched an utility mesh present in the main scene
  99319. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99320. prePointerInfo.skipOnPointerObservable = true;
  99321. }
  99322. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99323. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  99324. }
  99325. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99326. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99327. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99328. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99329. }
  99330. }
  99331. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  99332. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  99333. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  99334. // If a previous utility layer set this, do not unset this
  99335. if (!prePointerInfo.skipOnPointerObservable) {
  99336. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  99337. }
  99338. }
  99339. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  99340. // We have a pick in both scenes but main is closer than utility
  99341. // We touched an utility mesh present in the main scene
  99342. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99343. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99344. prePointerInfo.skipOnPointerObservable = true;
  99345. }
  99346. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99347. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99348. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99349. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99350. }
  99351. }
  99352. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  99353. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  99354. }
  99355. }
  99356. }
  99357. });
  99358. // Render directly on top of existing scene without clearing
  99359. this.utilityLayerScene.autoClear = false;
  99360. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  99361. if (_this.shouldRender) {
  99362. _this.render();
  99363. }
  99364. });
  99365. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  99366. _this.dispose();
  99367. });
  99368. this._updateCamera();
  99369. }
  99370. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  99371. /**
  99372. * 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)
  99373. */
  99374. get: function () {
  99375. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  99376. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99377. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99378. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99379. });
  99380. }
  99381. return UtilityLayerRenderer._DefaultUtilityLayer;
  99382. },
  99383. enumerable: true,
  99384. configurable: true
  99385. });
  99386. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  99387. /**
  99388. * 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)
  99389. */
  99390. get: function () {
  99391. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  99392. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99393. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  99394. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99395. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99396. });
  99397. }
  99398. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  99399. },
  99400. enumerable: true,
  99401. configurable: true
  99402. });
  99403. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  99404. if (!prePointerInfo.skipOnPointerObservable) {
  99405. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  99406. this._lastPointerEvents[pointerEvent.pointerId] = true;
  99407. }
  99408. };
  99409. /**
  99410. * Renders the utility layers scene on top of the original scene
  99411. */
  99412. UtilityLayerRenderer.prototype.render = function () {
  99413. this._updateCamera();
  99414. if (this.utilityLayerScene.activeCamera) {
  99415. // Set the camera's scene to utility layers scene
  99416. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  99417. var camera = this.utilityLayerScene.activeCamera;
  99418. camera._scene = this.utilityLayerScene;
  99419. if (camera.leftCamera) {
  99420. camera.leftCamera._scene = this.utilityLayerScene;
  99421. }
  99422. if (camera.rightCamera) {
  99423. camera.rightCamera._scene = this.utilityLayerScene;
  99424. }
  99425. this.utilityLayerScene.render(false);
  99426. // Reset camera's scene back to original
  99427. camera._scene = oldScene;
  99428. if (camera.leftCamera) {
  99429. camera.leftCamera._scene = oldScene;
  99430. }
  99431. if (camera.rightCamera) {
  99432. camera.rightCamera._scene = oldScene;
  99433. }
  99434. }
  99435. };
  99436. /**
  99437. * Disposes of the renderer
  99438. */
  99439. UtilityLayerRenderer.prototype.dispose = function () {
  99440. this.onPointerOutObservable.clear();
  99441. if (this._afterRenderObserver) {
  99442. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  99443. }
  99444. if (this._sceneDisposeObserver) {
  99445. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99446. }
  99447. if (this._originalPointerObserver) {
  99448. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  99449. }
  99450. this.utilityLayerScene.dispose();
  99451. };
  99452. UtilityLayerRenderer.prototype._updateCamera = function () {
  99453. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  99454. };
  99455. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99456. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99457. return UtilityLayerRenderer;
  99458. }());
  99459. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  99460. })(BABYLON || (BABYLON = {}));
  99461. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  99462. //# sourceMappingURL=babylon.behavior.js.map
  99463. var BABYLON;
  99464. (function (BABYLON) {
  99465. /**
  99466. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  99467. */
  99468. var PointerDragBehavior = /** @class */ (function () {
  99469. /**
  99470. * Creates a pointer drag behavior that can be attached to a mesh
  99471. * @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)
  99472. */
  99473. function PointerDragBehavior(options) {
  99474. /**
  99475. * 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)
  99476. */
  99477. this.maxDragAngle = 0;
  99478. /**
  99479. * @hidden
  99480. */
  99481. this._useAlternatePickedPointAboveMaxDragAngle = false;
  99482. /**
  99483. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99484. */
  99485. this.currentDraggingPointerID = -1;
  99486. /**
  99487. * If the behavior is currently in a dragging state
  99488. */
  99489. this.dragging = false;
  99490. /**
  99491. * 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)
  99492. */
  99493. this.dragDeltaRatio = 0.2;
  99494. /**
  99495. * If the drag plane orientation should be updated during the dragging (Default: true)
  99496. */
  99497. this.updateDragPlane = true;
  99498. // Debug mode will display drag planes to help visualize behavior
  99499. this._debugMode = false;
  99500. this._moving = false;
  99501. /**
  99502. * Fires each time the attached mesh is dragged with the pointer
  99503. * * delta between last drag position and current drag position in world space
  99504. * * dragDistance along the drag axis
  99505. * * dragPlaneNormal normal of the current drag plane used during the drag
  99506. * * dragPlanePoint in world space where the drag intersects the drag plane
  99507. */
  99508. this.onDragObservable = new BABYLON.Observable();
  99509. /**
  99510. * Fires each time a drag begins (eg. mouse down on mesh)
  99511. */
  99512. this.onDragStartObservable = new BABYLON.Observable();
  99513. /**
  99514. * Fires each time a drag ends (eg. mouse release after drag)
  99515. */
  99516. this.onDragEndObservable = new BABYLON.Observable();
  99517. /**
  99518. * If the attached mesh should be moved when dragged
  99519. */
  99520. this.moveAttached = true;
  99521. /**
  99522. * If the drag behavior will react to drag events (Default: true)
  99523. */
  99524. this.enabled = true;
  99525. /**
  99526. * If camera controls should be detached during the drag
  99527. */
  99528. this.detachCameraControls = true;
  99529. /**
  99530. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  99531. */
  99532. this.useObjectOrienationForDragging = true;
  99533. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99534. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  99535. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  99536. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99537. this._attachedElement = null;
  99538. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99539. this._lastPointerRay = {};
  99540. this._dragDelta = new BABYLON.Vector3();
  99541. // Variables to avoid instantiation in the below method
  99542. this._pointA = new BABYLON.Vector3(0, 0, 0);
  99543. this._pointB = new BABYLON.Vector3(0, 0, 0);
  99544. this._pointC = new BABYLON.Vector3(0, 0, 0);
  99545. this._lineA = new BABYLON.Vector3(0, 0, 0);
  99546. this._lineB = new BABYLON.Vector3(0, 0, 0);
  99547. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  99548. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  99549. this._options = options ? options : {};
  99550. var optionCount = 0;
  99551. if (this._options.dragAxis) {
  99552. optionCount++;
  99553. }
  99554. if (this._options.dragPlaneNormal) {
  99555. optionCount++;
  99556. }
  99557. if (optionCount > 1) {
  99558. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  99559. }
  99560. }
  99561. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  99562. /**
  99563. * The name of the behavior
  99564. */
  99565. get: function () {
  99566. return "PointerDrag";
  99567. },
  99568. enumerable: true,
  99569. configurable: true
  99570. });
  99571. /**
  99572. * Initializes the behavior
  99573. */
  99574. PointerDragBehavior.prototype.init = function () { };
  99575. /**
  99576. * Attaches the drag behavior the passed in mesh
  99577. * @param ownerNode The mesh that will be dragged around once attached
  99578. */
  99579. PointerDragBehavior.prototype.attach = function (ownerNode) {
  99580. var _this = this;
  99581. this._scene = ownerNode.getScene();
  99582. this._attachedNode = ownerNode;
  99583. // Initialize drag plane to not interfere with existing scene
  99584. if (!PointerDragBehavior._planeScene) {
  99585. if (this._debugMode) {
  99586. PointerDragBehavior._planeScene = this._scene;
  99587. }
  99588. else {
  99589. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  99590. PointerDragBehavior._planeScene.detachControl();
  99591. this._scene.getEngine().scenes.pop();
  99592. this._scene.onDisposeObservable.addOnce(function () {
  99593. PointerDragBehavior._planeScene.dispose();
  99594. PointerDragBehavior._planeScene = null;
  99595. });
  99596. }
  99597. }
  99598. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  99599. // State of the drag
  99600. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  99601. var pickPredicate = function (m) {
  99602. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  99603. };
  99604. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  99605. if (!_this.enabled) {
  99606. return;
  99607. }
  99608. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99609. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  99610. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  99611. }
  99612. }
  99613. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  99614. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  99615. _this.releaseDrag();
  99616. }
  99617. }
  99618. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  99619. var pointerId = pointerInfo.event.pointerId;
  99620. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  99621. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  99622. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  99623. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  99624. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  99625. }
  99626. _this.currentDraggingPointerID = pointerId;
  99627. }
  99628. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  99629. if (!_this._lastPointerRay[pointerId]) {
  99630. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99631. }
  99632. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  99633. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  99634. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  99635. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  99636. _this._moveDrag(pointerInfo.pickInfo.ray);
  99637. }
  99638. }
  99639. }
  99640. });
  99641. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  99642. if (_this._moving && _this.moveAttached) {
  99643. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  99644. // Slowly move mesh to avoid jitter
  99645. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  99646. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  99647. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  99648. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  99649. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  99650. }
  99651. });
  99652. };
  99653. /**
  99654. * Force relase the drag action by code.
  99655. */
  99656. PointerDragBehavior.prototype.releaseDrag = function () {
  99657. this.dragging = false;
  99658. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  99659. this.currentDraggingPointerID = -1;
  99660. this._moving = false;
  99661. // Reattach camera controls
  99662. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99663. this._scene.activeCamera.attachControl(this._attachedElement, true);
  99664. }
  99665. };
  99666. /**
  99667. * Simulates the start of a pointer drag event on the behavior
  99668. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  99669. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  99670. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  99671. */
  99672. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  99673. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  99674. this._startDrag(pointerId, fromRay, startPickedPoint);
  99675. var lastRay = this._lastPointerRay[pointerId];
  99676. if (pointerId === PointerDragBehavior._AnyMouseID) {
  99677. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  99678. }
  99679. if (lastRay) {
  99680. // if there was a last pointer ray drag the object there
  99681. this._moveDrag(lastRay);
  99682. }
  99683. };
  99684. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  99685. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  99686. return;
  99687. }
  99688. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  99689. // Create start ray from the camera to the object
  99690. if (fromRay) {
  99691. this._startDragRay.direction.copyFrom(fromRay.direction);
  99692. this._startDragRay.origin.copyFrom(fromRay.origin);
  99693. }
  99694. else {
  99695. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  99696. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  99697. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  99698. }
  99699. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  99700. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  99701. if (pickedPoint) {
  99702. this.dragging = true;
  99703. this.currentDraggingPointerID = pointerId;
  99704. this.lastDragPosition.copyFrom(pickedPoint);
  99705. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  99706. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  99707. // Detatch camera controls
  99708. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99709. if (this._scene.activeCamera.inputs.attachedElement) {
  99710. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  99711. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  99712. }
  99713. else {
  99714. this._attachedElement = null;
  99715. }
  99716. }
  99717. }
  99718. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  99719. };
  99720. PointerDragBehavior.prototype._moveDrag = function (ray) {
  99721. this._moving = true;
  99722. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  99723. if (pickedPoint) {
  99724. if (this.updateDragPlane) {
  99725. this._updateDragPlanePosition(ray, pickedPoint);
  99726. }
  99727. var dragLength = 0;
  99728. // depending on the drag mode option drag accordingly
  99729. if (this._options.dragAxis) {
  99730. // Convert local drag axis to world
  99731. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  99732. // Project delta drag from the drag plane onto the drag axis
  99733. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  99734. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  99735. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  99736. }
  99737. else {
  99738. dragLength = this._dragDelta.length();
  99739. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  99740. }
  99741. this._targetPosition.addInPlace(this._dragDelta);
  99742. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  99743. this.lastDragPosition.copyFrom(pickedPoint);
  99744. }
  99745. };
  99746. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  99747. var _this = this;
  99748. if (!ray) {
  99749. return null;
  99750. }
  99751. // Calculate angle between plane normal and ray
  99752. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  99753. // Correct if ray is casted from oposite side
  99754. if (angle > Math.PI / 2) {
  99755. angle = Math.PI - angle;
  99756. }
  99757. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  99758. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  99759. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  99760. // Invert ray direction along the towards object axis
  99761. this._tmpVector.copyFrom(ray.direction);
  99762. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  99763. this._alternatePickedPoint.normalize();
  99764. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  99765. this._tmpVector.addInPlace(this._alternatePickedPoint);
  99766. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  99767. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  99768. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  99769. this._alternatePickedPoint.addInPlace(this._tmpVector);
  99770. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  99771. return this._alternatePickedPoint;
  99772. }
  99773. else {
  99774. return null;
  99775. }
  99776. }
  99777. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  99778. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  99779. return pickResult.pickedPoint;
  99780. }
  99781. else {
  99782. return null;
  99783. }
  99784. };
  99785. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  99786. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  99787. this._pointA.copyFrom(dragPlanePosition);
  99788. if (this._options.dragAxis) {
  99789. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  99790. // Calculate plane normal in direction of camera but perpendicular to drag axis
  99791. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  99792. ray.origin.subtractToRef(this._pointA, this._pointC);
  99793. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  99794. // Get perpendicular line from direction to camera and drag axis
  99795. this._pointB.subtractToRef(this._pointA, this._lineA);
  99796. this._pointC.subtractToRef(this._pointA, this._lineB);
  99797. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  99798. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  99799. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  99800. this._lookAt.normalize();
  99801. this._dragPlane.position.copyFrom(this._pointA);
  99802. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  99803. this._dragPlane.lookAt(this._lookAt);
  99804. }
  99805. else if (this._options.dragPlaneNormal) {
  99806. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  99807. this._dragPlane.position.copyFrom(this._pointA);
  99808. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  99809. this._dragPlane.lookAt(this._lookAt);
  99810. }
  99811. else {
  99812. this._dragPlane.position.copyFrom(this._pointA);
  99813. this._dragPlane.lookAt(ray.origin);
  99814. }
  99815. this._dragPlane.computeWorldMatrix(true);
  99816. };
  99817. /**
  99818. * Detaches the behavior from the mesh
  99819. */
  99820. PointerDragBehavior.prototype.detach = function () {
  99821. if (this._pointerObserver) {
  99822. this._scene.onPointerObservable.remove(this._pointerObserver);
  99823. }
  99824. if (this._beforeRenderObserver) {
  99825. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  99826. }
  99827. };
  99828. PointerDragBehavior._AnyMouseID = -2;
  99829. return PointerDragBehavior;
  99830. }());
  99831. BABYLON.PointerDragBehavior = PointerDragBehavior;
  99832. })(BABYLON || (BABYLON = {}));
  99833. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  99834. var BABYLON;
  99835. (function (BABYLON) {
  99836. /**
  99837. * A behavior that when attached to a mesh will allow the mesh to be scaled
  99838. */
  99839. var MultiPointerScaleBehavior = /** @class */ (function () {
  99840. /**
  99841. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  99842. */
  99843. function MultiPointerScaleBehavior() {
  99844. this._startDistance = 0;
  99845. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  99846. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  99847. this._sceneRenderObserver = null;
  99848. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  99849. this._dragBehaviorA.moveAttached = false;
  99850. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  99851. this._dragBehaviorB.moveAttached = false;
  99852. }
  99853. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  99854. /**
  99855. * The name of the behavior
  99856. */
  99857. get: function () {
  99858. return "MultiPointerScale";
  99859. },
  99860. enumerable: true,
  99861. configurable: true
  99862. });
  99863. /**
  99864. * Initializes the behavior
  99865. */
  99866. MultiPointerScaleBehavior.prototype.init = function () { };
  99867. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  99868. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  99869. };
  99870. /**
  99871. * Attaches the scale behavior the passed in mesh
  99872. * @param ownerNode The mesh that will be scaled around once attached
  99873. */
  99874. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  99875. var _this = this;
  99876. this._ownerNode = ownerNode;
  99877. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  99878. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  99879. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99880. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99881. _this._dragBehaviorA.releaseDrag();
  99882. }
  99883. else {
  99884. _this._initialScale.copyFrom(ownerNode.scaling);
  99885. _this._startDistance = _this._getCurrentDistance();
  99886. }
  99887. }
  99888. });
  99889. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  99890. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99891. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99892. _this._dragBehaviorB.releaseDrag();
  99893. }
  99894. else {
  99895. _this._initialScale.copyFrom(ownerNode.scaling);
  99896. _this._startDistance = _this._getCurrentDistance();
  99897. }
  99898. }
  99899. });
  99900. // Once both drag behaviors are active scale based on the distance between the two pointers
  99901. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99902. behavior.onDragObservable.add(function () {
  99903. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99904. var ratio = _this._getCurrentDistance() / _this._startDistance;
  99905. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  99906. }
  99907. });
  99908. });
  99909. ownerNode.addBehavior(this._dragBehaviorA);
  99910. ownerNode.addBehavior(this._dragBehaviorB);
  99911. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  99912. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  99913. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99914. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  99915. if (change.length() > 0.01) {
  99916. ownerNode.scaling.addInPlace(change);
  99917. }
  99918. }
  99919. });
  99920. };
  99921. /**
  99922. * Detaches the behavior from the mesh
  99923. */
  99924. MultiPointerScaleBehavior.prototype.detach = function () {
  99925. var _this = this;
  99926. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  99927. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99928. behavior.onDragStartObservable.clear();
  99929. behavior.onDragObservable.clear();
  99930. _this._ownerNode.removeBehavior(behavior);
  99931. });
  99932. };
  99933. return MultiPointerScaleBehavior;
  99934. }());
  99935. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  99936. })(BABYLON || (BABYLON = {}));
  99937. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  99938. var BABYLON;
  99939. (function (BABYLON) {
  99940. /**
  99941. * 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
  99942. */
  99943. var SixDofDragBehavior = /** @class */ (function () {
  99944. /**
  99945. * 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
  99946. */
  99947. function SixDofDragBehavior() {
  99948. this._sceneRenderObserver = null;
  99949. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99950. this._moving = false;
  99951. this._startingOrientation = new BABYLON.Quaternion();
  99952. /**
  99953. * 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)
  99954. */
  99955. this.zDragFactor = 3;
  99956. /**
  99957. * If the behavior is currently in a dragging state
  99958. */
  99959. this.dragging = false;
  99960. /**
  99961. * 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)
  99962. */
  99963. this.dragDeltaRatio = 0.2;
  99964. /**
  99965. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99966. */
  99967. this.currentDraggingPointerID = -1;
  99968. /**
  99969. * If camera controls should be detached during the drag
  99970. */
  99971. this.detachCameraControls = true;
  99972. /**
  99973. * Fires each time a drag starts
  99974. */
  99975. this.onDragStartObservable = new BABYLON.Observable();
  99976. /**
  99977. * Fires each time a drag ends (eg. mouse release after drag)
  99978. */
  99979. this.onDragEndObservable = new BABYLON.Observable();
  99980. }
  99981. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  99982. /**
  99983. * The name of the behavior
  99984. */
  99985. get: function () {
  99986. return "SixDofDrag";
  99987. },
  99988. enumerable: true,
  99989. configurable: true
  99990. });
  99991. /**
  99992. * Initializes the behavior
  99993. */
  99994. SixDofDragBehavior.prototype.init = function () { };
  99995. /**
  99996. * Attaches the scale behavior the passed in mesh
  99997. * @param ownerNode The mesh that will be scaled around once attached
  99998. */
  99999. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  100000. var _this = this;
  100001. this._ownerNode = ownerNode;
  100002. this._scene = this._ownerNode.getScene();
  100003. if (!SixDofDragBehavior._virtualScene) {
  100004. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  100005. this._scene.getEngine().scenes.pop();
  100006. }
  100007. var pickedMesh = null;
  100008. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  100009. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  100010. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  100011. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  100012. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  100013. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  100014. var pickPredicate = function (m) {
  100015. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  100016. };
  100017. var attachedElement = null;
  100018. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  100019. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100020. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  100021. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  100022. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  100023. }
  100024. pickedMesh = _this._ownerNode;
  100025. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  100026. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  100027. // Set position and orientation of the controller
  100028. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  100029. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  100030. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  100031. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100032. pickedMesh.computeWorldMatrix();
  100033. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  100034. if (!pickedMesh.rotationQuaternion) {
  100035. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  100036. }
  100037. var oldParent = pickedMesh.parent;
  100038. pickedMesh.setParent(null);
  100039. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  100040. pickedMesh.setParent(oldParent);
  100041. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  100042. // Update state
  100043. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  100044. _this.dragging = true;
  100045. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  100046. // Detatch camera controls
  100047. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  100048. if (_this._scene.activeCamera.inputs.attachedElement) {
  100049. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  100050. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  100051. }
  100052. else {
  100053. attachedElement = null;
  100054. }
  100055. }
  100056. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  100057. _this.onDragStartObservable.notifyObservers({});
  100058. }
  100059. }
  100060. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  100061. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  100062. _this.dragging = false;
  100063. _this._moving = false;
  100064. _this.currentDraggingPointerID = -1;
  100065. pickedMesh = null;
  100066. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100067. // Reattach camera controls
  100068. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  100069. _this._scene.activeCamera.attachControl(attachedElement, true);
  100070. }
  100071. _this.onDragEndObservable.notifyObservers({});
  100072. }
  100073. }
  100074. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  100075. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  100076. var zDragFactor = _this.zDragFactor;
  100077. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  100078. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  100079. zDragFactor = 0;
  100080. }
  100081. // Calculate controller drag distance in controller space
  100082. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  100083. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  100084. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  100085. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  100086. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  100087. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  100088. if (_this._virtualDragMesh.position.z < 0) {
  100089. _this._virtualDragMesh.position.z = 0;
  100090. }
  100091. // Update the controller position
  100092. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  100093. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  100094. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100095. // Move the virtualObjectsPosition into the picked mesh's space if needed
  100096. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  100097. if (pickedMesh.parent) {
  100098. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  100099. }
  100100. if (!_this._moving) {
  100101. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  100102. }
  100103. _this._moving = true;
  100104. }
  100105. }
  100106. });
  100107. var tmpQuaternion = new BABYLON.Quaternion();
  100108. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  100109. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  100110. if (_this.dragging && _this._moving && pickedMesh) {
  100111. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  100112. // Slowly move mesh to avoid jitter
  100113. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  100114. // Get change in rotation
  100115. tmpQuaternion.copyFrom(_this._startingOrientation);
  100116. tmpQuaternion.x = -tmpQuaternion.x;
  100117. tmpQuaternion.y = -tmpQuaternion.y;
  100118. tmpQuaternion.z = -tmpQuaternion.z;
  100119. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  100120. // Convert change in rotation to only y axis rotation
  100121. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  100122. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  100123. // Slowly move mesh to avoid jitter
  100124. var oldParent = pickedMesh.parent;
  100125. pickedMesh.setParent(null);
  100126. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  100127. pickedMesh.setParent(oldParent);
  100128. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  100129. }
  100130. });
  100131. };
  100132. /**
  100133. * Detaches the behavior from the mesh
  100134. */
  100135. SixDofDragBehavior.prototype.detach = function () {
  100136. if (this._scene) {
  100137. this._scene.onPointerObservable.remove(this._pointerObserver);
  100138. }
  100139. if (this._ownerNode) {
  100140. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  100141. }
  100142. if (this._virtualOriginMesh) {
  100143. this._virtualOriginMesh.dispose();
  100144. }
  100145. if (this._virtualDragMesh) {
  100146. this._virtualDragMesh.dispose();
  100147. }
  100148. this.onDragEndObservable.clear();
  100149. this.onDragStartObservable.clear();
  100150. };
  100151. return SixDofDragBehavior;
  100152. }());
  100153. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  100154. })(BABYLON || (BABYLON = {}));
  100155. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  100156. var BABYLON;
  100157. (function (BABYLON) {
  100158. /**
  100159. * @hidden
  100160. */
  100161. var FaceDirectionInfo = /** @class */ (function () {
  100162. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  100163. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  100164. if (diff === void 0) { diff = 0; }
  100165. if (ignore === void 0) { ignore = false; }
  100166. this.direction = direction;
  100167. this.rotatedDirection = rotatedDirection;
  100168. this.diff = diff;
  100169. this.ignore = ignore;
  100170. }
  100171. return FaceDirectionInfo;
  100172. }());
  100173. /**
  100174. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  100175. */
  100176. var AttachToBoxBehavior = /** @class */ (function () {
  100177. /**
  100178. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  100179. * @param ui The transform node that should be attched to the mesh
  100180. */
  100181. function AttachToBoxBehavior(ui) {
  100182. this.ui = ui;
  100183. /**
  100184. * The name of the behavior
  100185. */
  100186. this.name = "AttachToBoxBehavior";
  100187. /**
  100188. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  100189. */
  100190. this.distanceAwayFromFace = 0.15;
  100191. /**
  100192. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  100193. */
  100194. this.distanceAwayFromBottomOfFace = 0.15;
  100195. 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))];
  100196. this._tmpMatrix = new BABYLON.Matrix();
  100197. this._tmpVector = new BABYLON.Vector3();
  100198. this._zeroVector = BABYLON.Vector3.Zero();
  100199. this._lookAtTmpMatrix = new BABYLON.Matrix();
  100200. /* Does nothing */
  100201. }
  100202. /**
  100203. * Initializes the behavior
  100204. */
  100205. AttachToBoxBehavior.prototype.init = function () {
  100206. /* Does nothing */
  100207. };
  100208. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  100209. var _this = this;
  100210. // Go over each face and calculate the angle between the face's normal and targetDirection
  100211. this._faceVectors.forEach(function (v) {
  100212. if (!_this._target.rotationQuaternion) {
  100213. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  100214. }
  100215. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  100216. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  100217. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  100218. });
  100219. // Return the face information of the one with the normal closeset to target direction
  100220. return this._faceVectors.reduce(function (min, p) {
  100221. if (min.ignore) {
  100222. return p;
  100223. }
  100224. else if (p.ignore) {
  100225. return min;
  100226. }
  100227. else {
  100228. return min.diff < p.diff ? min : p;
  100229. }
  100230. }, this._faceVectors[0]);
  100231. };
  100232. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  100233. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  100234. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  100235. this._lookAtTmpMatrix.invert();
  100236. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  100237. };
  100238. /**
  100239. * Attaches the AttachToBoxBehavior to the passed in mesh
  100240. * @param target The mesh that the specified node will be attached to
  100241. */
  100242. AttachToBoxBehavior.prototype.attach = function (target) {
  100243. var _this = this;
  100244. this._target = target;
  100245. this._scene = this._target.getScene();
  100246. // Every frame, update the app bars position
  100247. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  100248. if (!_this._scene.activeCamera) {
  100249. return;
  100250. }
  100251. // Find the face closest to the cameras position
  100252. var cameraPos = _this._scene.activeCamera.position;
  100253. if (_this._scene.activeCamera.devicePosition) {
  100254. cameraPos = _this._scene.activeCamera.devicePosition;
  100255. }
  100256. var facing = _this._closestFace(cameraPos.subtract(target.position));
  100257. if (_this._scene.activeCamera.leftCamera) {
  100258. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  100259. }
  100260. else {
  100261. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  100262. }
  100263. // Get camera up direction
  100264. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  100265. // Ignore faces to not select a parrelel face for the up vector of the UI
  100266. _this._faceVectors.forEach(function (v) {
  100267. if (facing.direction.x && v.direction.x) {
  100268. v.ignore = true;
  100269. }
  100270. if (facing.direction.y && v.direction.y) {
  100271. v.ignore = true;
  100272. }
  100273. if (facing.direction.z && v.direction.z) {
  100274. v.ignore = true;
  100275. }
  100276. });
  100277. var facingUp = _this._closestFace(_this._tmpVector);
  100278. // Unignore faces
  100279. _this._faceVectors.forEach(function (v) {
  100280. v.ignore = false;
  100281. });
  100282. // Position the app bar on that face
  100283. _this.ui.position.copyFrom(target.position);
  100284. if (facing.direction.x) {
  100285. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100286. _this.ui.position.addInPlace(_this._tmpVector);
  100287. }
  100288. if (facing.direction.y) {
  100289. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100290. _this.ui.position.addInPlace(_this._tmpVector);
  100291. }
  100292. if (facing.direction.z) {
  100293. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100294. _this.ui.position.addInPlace(_this._tmpVector);
  100295. }
  100296. // Rotate to be oriented properly to the camera
  100297. if (!_this.ui.rotationQuaternion) {
  100298. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  100299. }
  100300. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  100301. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  100302. // Place ui the correct distance from the bottom of the mesh
  100303. if (facingUp.direction.x) {
  100304. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  100305. }
  100306. if (facingUp.direction.y) {
  100307. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  100308. }
  100309. if (facingUp.direction.z) {
  100310. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  100311. }
  100312. _this.ui.position.addInPlace(_this._tmpVector);
  100313. });
  100314. };
  100315. /**
  100316. * Detaches the behavior from the mesh
  100317. */
  100318. AttachToBoxBehavior.prototype.detach = function () {
  100319. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  100320. };
  100321. return AttachToBoxBehavior;
  100322. }());
  100323. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  100324. })(BABYLON || (BABYLON = {}));
  100325. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  100326. var BABYLON;
  100327. (function (BABYLON) {
  100328. /**
  100329. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  100330. */
  100331. var FadeInOutBehavior = /** @class */ (function () {
  100332. /**
  100333. * Instatiates the FadeInOutBehavior
  100334. */
  100335. function FadeInOutBehavior() {
  100336. var _this = this;
  100337. /**
  100338. * Time in milliseconds to delay before fading in (Default: 0)
  100339. */
  100340. this.delay = 0;
  100341. /**
  100342. * Time in milliseconds for the mesh to fade in (Default: 300)
  100343. */
  100344. this.fadeInTime = 300;
  100345. this._millisecondsPerFrame = 1000 / 60;
  100346. this._hovered = false;
  100347. this._hoverValue = 0;
  100348. this._ownerNode = null;
  100349. this._update = function () {
  100350. if (_this._ownerNode) {
  100351. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  100352. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  100353. if (_this._ownerNode.visibility > 1) {
  100354. _this._setAllVisibility(_this._ownerNode, 1);
  100355. _this._hoverValue = _this.fadeInTime + _this.delay;
  100356. return;
  100357. }
  100358. else if (_this._ownerNode.visibility < 0) {
  100359. _this._setAllVisibility(_this._ownerNode, 0);
  100360. if (_this._hoverValue < 0) {
  100361. _this._hoverValue = 0;
  100362. return;
  100363. }
  100364. }
  100365. setTimeout(_this._update, _this._millisecondsPerFrame);
  100366. }
  100367. };
  100368. }
  100369. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  100370. /**
  100371. * The name of the behavior
  100372. */
  100373. get: function () {
  100374. return "FadeInOut";
  100375. },
  100376. enumerable: true,
  100377. configurable: true
  100378. });
  100379. /**
  100380. * Initializes the behavior
  100381. */
  100382. FadeInOutBehavior.prototype.init = function () {
  100383. };
  100384. /**
  100385. * Attaches the fade behavior on the passed in mesh
  100386. * @param ownerNode The mesh that will be faded in/out once attached
  100387. */
  100388. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  100389. this._ownerNode = ownerNode;
  100390. this._setAllVisibility(this._ownerNode, 0);
  100391. };
  100392. /**
  100393. * Detaches the behavior from the mesh
  100394. */
  100395. FadeInOutBehavior.prototype.detach = function () {
  100396. this._ownerNode = null;
  100397. };
  100398. /**
  100399. * Triggers the mesh to begin fading in or out
  100400. * @param value if the object should fade in or out (true to fade in)
  100401. */
  100402. FadeInOutBehavior.prototype.fadeIn = function (value) {
  100403. this._hovered = value;
  100404. this._update();
  100405. };
  100406. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  100407. var _this = this;
  100408. mesh.visibility = value;
  100409. mesh.getChildMeshes().forEach(function (c) {
  100410. _this._setAllVisibility(c, value);
  100411. });
  100412. };
  100413. return FadeInOutBehavior;
  100414. }());
  100415. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  100416. })(BABYLON || (BABYLON = {}));
  100417. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  100418. var BABYLON;
  100419. (function (BABYLON) {
  100420. /**
  100421. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  100422. */
  100423. var Gizmo = /** @class */ (function () {
  100424. /**
  100425. * Creates a gizmo
  100426. * @param gizmoLayer The utility layer the gizmo will be added to
  100427. */
  100428. function Gizmo(
  100429. /** The utility layer the gizmo will be added to */
  100430. gizmoLayer) {
  100431. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100432. var _this = this;
  100433. this.gizmoLayer = gizmoLayer;
  100434. /**
  100435. * Ratio for the scale of the gizmo (Default: 1)
  100436. */
  100437. this.scaleRatio = 1;
  100438. this._tmpMatrix = new BABYLON.Matrix();
  100439. /**
  100440. * If a custom mesh has been set (Default: false)
  100441. */
  100442. this._customMeshSet = false;
  100443. /**
  100444. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  100445. */
  100446. this.updateGizmoRotationToMatchAttachedMesh = true;
  100447. /**
  100448. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  100449. */
  100450. this.updateGizmoPositionToMatchAttachedMesh = true;
  100451. /**
  100452. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  100453. */
  100454. this._updateScale = true;
  100455. this._interactionsEnabled = true;
  100456. this._tempVector = new BABYLON.Vector3();
  100457. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  100458. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  100459. _this._update();
  100460. });
  100461. this.attachedMesh = null;
  100462. }
  100463. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  100464. /**
  100465. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  100466. * * When set, interactions will be enabled
  100467. */
  100468. get: function () {
  100469. return this._attachedMesh;
  100470. },
  100471. set: function (value) {
  100472. this._attachedMesh = value;
  100473. this._rootMesh.setEnabled(value ? true : false);
  100474. this._attachedMeshChanged(value);
  100475. },
  100476. enumerable: true,
  100477. configurable: true
  100478. });
  100479. /**
  100480. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100481. * @param mesh The mesh to replace the default mesh of the gizmo
  100482. */
  100483. Gizmo.prototype.setCustomMesh = function (mesh) {
  100484. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  100485. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  100486. }
  100487. this._rootMesh.getChildMeshes().forEach(function (c) {
  100488. c.dispose();
  100489. });
  100490. mesh.parent = this._rootMesh;
  100491. this._customMeshSet = true;
  100492. };
  100493. Gizmo.prototype._attachedMeshChanged = function (value) {
  100494. };
  100495. /**
  100496. * @hidden
  100497. * Updates the gizmo to match the attached mesh's position/rotation
  100498. */
  100499. Gizmo.prototype._update = function () {
  100500. if (this.attachedMesh) {
  100501. if (this.updateGizmoRotationToMatchAttachedMesh) {
  100502. if (!this._rootMesh.rotationQuaternion) {
  100503. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  100504. }
  100505. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  100506. this._tempVector.copyFrom(this.attachedMesh.scaling);
  100507. if (this.attachedMesh.scaling.x < 0) {
  100508. this.attachedMesh.scaling.x *= -1;
  100509. }
  100510. if (this.attachedMesh.scaling.y < 0) {
  100511. this.attachedMesh.scaling.y *= -1;
  100512. }
  100513. if (this.attachedMesh.scaling.z < 0) {
  100514. this.attachedMesh.scaling.z *= -1;
  100515. }
  100516. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  100517. this.attachedMesh.scaling.copyFrom(this._tempVector);
  100518. this.attachedMesh.computeWorldMatrix();
  100519. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  100520. }
  100521. else if (this._rootMesh.rotationQuaternion) {
  100522. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  100523. }
  100524. if (this.updateGizmoPositionToMatchAttachedMesh) {
  100525. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  100526. }
  100527. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  100528. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  100529. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  100530. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  100531. }
  100532. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  100533. var dist = this._tempVector.length() * this.scaleRatio;
  100534. this._rootMesh.scaling.set(dist, dist, dist);
  100535. }
  100536. }
  100537. };
  100538. /**
  100539. * Disposes of the gizmo
  100540. */
  100541. Gizmo.prototype.dispose = function () {
  100542. this._rootMesh.dispose();
  100543. if (this._beforeRenderObserver) {
  100544. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  100545. }
  100546. };
  100547. return Gizmo;
  100548. }());
  100549. BABYLON.Gizmo = Gizmo;
  100550. })(BABYLON || (BABYLON = {}));
  100551. //# sourceMappingURL=babylon.gizmo.js.map
  100552. var BABYLON;
  100553. (function (BABYLON) {
  100554. /**
  100555. * Single axis drag gizmo
  100556. */
  100557. var AxisDragGizmo = /** @class */ (function (_super) {
  100558. __extends(AxisDragGizmo, _super);
  100559. /**
  100560. * Creates an AxisDragGizmo
  100561. * @param gizmoLayer The utility layer the gizmo will be added to
  100562. * @param dragAxis The axis which the gizmo will be able to drag on
  100563. * @param color The color of the gizmo
  100564. */
  100565. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  100566. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100567. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100568. var _this = _super.call(this, gizmoLayer) || this;
  100569. _this._pointerObserver = null;
  100570. /**
  100571. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100572. */
  100573. _this.snapDistance = 0;
  100574. /**
  100575. * Event that fires each time the gizmo snaps to a new location.
  100576. * * snapDistance is the the change in distance
  100577. */
  100578. _this.onSnapObservable = new BABYLON.Observable();
  100579. // Create Material
  100580. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100581. coloredMaterial.disableLighting = true;
  100582. coloredMaterial.emissiveColor = color;
  100583. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100584. hoverMaterial.disableLighting = true;
  100585. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100586. // Build mesh on root node
  100587. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100588. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  100589. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100590. arrowTail.color = coloredMaterial.emissiveColor;
  100591. arrow.addChild(arrowMesh);
  100592. arrow.addChild(arrowTail);
  100593. // Position arrow pointing in its drag axis
  100594. arrowMesh.scaling.scaleInPlace(0.05);
  100595. arrowMesh.material = coloredMaterial;
  100596. arrowMesh.rotation.x = Math.PI / 2;
  100597. arrowMesh.position.z += 0.3;
  100598. arrowTail.scaling.scaleInPlace(0.26);
  100599. arrowTail.rotation.x = Math.PI / 2;
  100600. arrowTail.material = coloredMaterial;
  100601. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100602. arrow.scaling.scaleInPlace(1 / 3);
  100603. _this._rootMesh.addChild(arrow);
  100604. var currentSnapDragDistance = 0;
  100605. var tmpVector = new BABYLON.Vector3();
  100606. var tmpSnapEvent = { snapDistance: 0 };
  100607. // Add drag behavior to handle events when the gizmo is dragged
  100608. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100609. _this.dragBehavior.moveAttached = false;
  100610. _this._rootMesh.addBehavior(_this.dragBehavior);
  100611. var localDelta = new BABYLON.Vector3();
  100612. var tmpMatrix = new BABYLON.Matrix();
  100613. _this.dragBehavior.onDragObservable.add(function (event) {
  100614. if (_this.attachedMesh) {
  100615. // Convert delta to local translation if it has a parent
  100616. if (_this.attachedMesh.parent) {
  100617. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100618. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  100619. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  100620. }
  100621. else {
  100622. localDelta.copyFrom(event.delta);
  100623. }
  100624. // Snapping logic
  100625. if (_this.snapDistance == 0) {
  100626. _this.attachedMesh.position.addInPlace(localDelta);
  100627. }
  100628. else {
  100629. currentSnapDragDistance += event.dragDistance;
  100630. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100631. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  100632. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100633. localDelta.normalizeToRef(tmpVector);
  100634. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  100635. _this.attachedMesh.position.addInPlace(tmpVector);
  100636. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100637. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100638. }
  100639. }
  100640. }
  100641. });
  100642. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100643. if (_this._customMeshSet) {
  100644. return;
  100645. }
  100646. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100647. var material = isHovered ? hoverMaterial : coloredMaterial;
  100648. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100649. m.material = material;
  100650. if (m.color) {
  100651. m.color = material.emissiveColor;
  100652. }
  100653. });
  100654. });
  100655. return _this;
  100656. }
  100657. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  100658. if (this.dragBehavior) {
  100659. this.dragBehavior.enabled = value ? true : false;
  100660. }
  100661. };
  100662. /**
  100663. * Disposes of the gizmo
  100664. */
  100665. AxisDragGizmo.prototype.dispose = function () {
  100666. this.onSnapObservable.clear();
  100667. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100668. this.dragBehavior.detach();
  100669. _super.prototype.dispose.call(this);
  100670. };
  100671. return AxisDragGizmo;
  100672. }(BABYLON.Gizmo));
  100673. BABYLON.AxisDragGizmo = AxisDragGizmo;
  100674. })(BABYLON || (BABYLON = {}));
  100675. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  100676. var BABYLON;
  100677. (function (BABYLON) {
  100678. /**
  100679. * Single axis scale gizmo
  100680. */
  100681. var AxisScaleGizmo = /** @class */ (function (_super) {
  100682. __extends(AxisScaleGizmo, _super);
  100683. /**
  100684. * Creates an AxisScaleGizmo
  100685. * @param gizmoLayer The utility layer the gizmo will be added to
  100686. * @param dragAxis The axis which the gizmo will be able to scale on
  100687. * @param color The color of the gizmo
  100688. */
  100689. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  100690. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100691. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100692. var _this = _super.call(this, gizmoLayer) || this;
  100693. _this._pointerObserver = null;
  100694. /**
  100695. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100696. */
  100697. _this.snapDistance = 0;
  100698. /**
  100699. * Event that fires each time the gizmo snaps to a new location.
  100700. * * snapDistance is the the change in distance
  100701. */
  100702. _this.onSnapObservable = new BABYLON.Observable();
  100703. /**
  100704. * If the scaling operation should be done on all axis (default: false)
  100705. */
  100706. _this.uniformScaling = false;
  100707. // Create Material
  100708. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100709. _this._coloredMaterial.disableLighting = true;
  100710. _this._coloredMaterial.emissiveColor = color;
  100711. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100712. hoverMaterial.disableLighting = true;
  100713. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100714. // Build mesh on root node
  100715. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100716. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  100717. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100718. arrowTail.color = _this._coloredMaterial.emissiveColor;
  100719. arrow.addChild(arrowMesh);
  100720. arrow.addChild(arrowTail);
  100721. // Position arrow pointing in its drag axis
  100722. arrowMesh.scaling.scaleInPlace(0.1);
  100723. arrowMesh.material = _this._coloredMaterial;
  100724. arrowMesh.rotation.x = Math.PI / 2;
  100725. arrowMesh.position.z += 0.3;
  100726. arrowTail.scaling.scaleInPlace(0.26);
  100727. arrowTail.rotation.x = Math.PI / 2;
  100728. arrowTail.material = _this._coloredMaterial;
  100729. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100730. _this._rootMesh.addChild(arrow);
  100731. arrow.scaling.scaleInPlace(1 / 3);
  100732. // Add drag behavior to handle events when the gizmo is dragged
  100733. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100734. _this.dragBehavior.moveAttached = false;
  100735. _this._rootMesh.addBehavior(_this.dragBehavior);
  100736. var currentSnapDragDistance = 0;
  100737. var tmpVector = new BABYLON.Vector3();
  100738. var tmpSnapEvent = { snapDistance: 0 };
  100739. _this.dragBehavior.onDragObservable.add(function (event) {
  100740. if (_this.attachedMesh) {
  100741. // Snapping logic
  100742. var snapped = false;
  100743. var dragSteps = 0;
  100744. if (_this.uniformScaling) {
  100745. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  100746. if (tmpVector.y < 0) {
  100747. tmpVector.scaleInPlace(-1);
  100748. }
  100749. }
  100750. else {
  100751. tmpVector.copyFrom(dragAxis);
  100752. }
  100753. if (_this.snapDistance == 0) {
  100754. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  100755. }
  100756. else {
  100757. currentSnapDragDistance += event.dragDistance;
  100758. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100759. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100760. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100761. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  100762. snapped = true;
  100763. }
  100764. else {
  100765. tmpVector.scaleInPlace(0);
  100766. }
  100767. }
  100768. _this.attachedMesh.scaling.addInPlace(tmpVector);
  100769. if (snapped) {
  100770. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100771. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100772. }
  100773. }
  100774. });
  100775. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100776. if (_this._customMeshSet) {
  100777. return;
  100778. }
  100779. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100780. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  100781. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100782. m.material = material;
  100783. if (m.color) {
  100784. m.color = material.emissiveColor;
  100785. }
  100786. });
  100787. });
  100788. return _this;
  100789. }
  100790. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  100791. if (this.dragBehavior) {
  100792. this.dragBehavior.enabled = value ? true : false;
  100793. }
  100794. };
  100795. /**
  100796. * Disposes of the gizmo
  100797. */
  100798. AxisScaleGizmo.prototype.dispose = function () {
  100799. this.onSnapObservable.clear();
  100800. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100801. this.dragBehavior.detach();
  100802. _super.prototype.dispose.call(this);
  100803. };
  100804. /**
  100805. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100806. * @param mesh The mesh to replace the default mesh of the gizmo
  100807. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  100808. */
  100809. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  100810. var _this = this;
  100811. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  100812. _super.prototype.setCustomMesh.call(this, mesh);
  100813. if (useGizmoMaterial) {
  100814. this._rootMesh.getChildMeshes().forEach(function (m) {
  100815. m.material = _this._coloredMaterial;
  100816. if (m.color) {
  100817. m.color = _this._coloredMaterial.emissiveColor;
  100818. }
  100819. });
  100820. this._customMeshSet = false;
  100821. }
  100822. };
  100823. return AxisScaleGizmo;
  100824. }(BABYLON.Gizmo));
  100825. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  100826. })(BABYLON || (BABYLON = {}));
  100827. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  100828. var BABYLON;
  100829. (function (BABYLON) {
  100830. /**
  100831. * Single plane rotation gizmo
  100832. */
  100833. var PlaneRotationGizmo = /** @class */ (function (_super) {
  100834. __extends(PlaneRotationGizmo, _super);
  100835. /**
  100836. * Creates a PlaneRotationGizmo
  100837. * @param gizmoLayer The utility layer the gizmo will be added to
  100838. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  100839. * @param color The color of the gizmo
  100840. * @param tessellation Amount of tessellation to be used when creating rotation circles
  100841. */
  100842. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  100843. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100844. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100845. if (tessellation === void 0) { tessellation = 32; }
  100846. var _this = _super.call(this, gizmoLayer) || this;
  100847. _this._pointerObserver = null;
  100848. /**
  100849. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  100850. */
  100851. _this.snapDistance = 0;
  100852. /**
  100853. * Event that fires each time the gizmo snaps to a new location.
  100854. * * snapDistance is the the change in distance
  100855. */
  100856. _this.onSnapObservable = new BABYLON.Observable();
  100857. // Create Material
  100858. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100859. coloredMaterial.disableLighting = true;
  100860. coloredMaterial.emissiveColor = color;
  100861. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100862. hoverMaterial.disableLighting = true;
  100863. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100864. // Build mesh on root node
  100865. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100866. // Create circle out of lines
  100867. var radius = 0.8;
  100868. var points = new Array();
  100869. for (var i = 0; i < tessellation; i++) {
  100870. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  100871. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  100872. }
  100873. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  100874. rotationMesh.color = coloredMaterial.emissiveColor;
  100875. // Position arrow pointing in its drag axis
  100876. rotationMesh.scaling.scaleInPlace(0.26);
  100877. rotationMesh.material = coloredMaterial;
  100878. rotationMesh.rotation.x = Math.PI / 2;
  100879. parentMesh.addChild(rotationMesh);
  100880. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  100881. _this._rootMesh.addChild(parentMesh);
  100882. parentMesh.scaling.scaleInPlace(1 / 3);
  100883. // Add drag behavior to handle events when the gizmo is dragged
  100884. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  100885. _this.dragBehavior.moveAttached = false;
  100886. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  100887. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  100888. _this._rootMesh.addBehavior(_this.dragBehavior);
  100889. var lastDragPosition = new BABYLON.Vector3();
  100890. _this.dragBehavior.onDragStartObservable.add(function (e) {
  100891. if (_this.attachedMesh) {
  100892. lastDragPosition.copyFrom(e.dragPlanePoint);
  100893. }
  100894. });
  100895. var rotationMatrix = new BABYLON.Matrix();
  100896. var planeNormalTowardsCamera = new BABYLON.Vector3();
  100897. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  100898. var tmpSnapEvent = { snapDistance: 0 };
  100899. var currentSnapDragDistance = 0;
  100900. var tmpMatrix = new BABYLON.Matrix();
  100901. var tmpVector = new BABYLON.Vector3();
  100902. var amountToRotate = new BABYLON.Quaternion();
  100903. _this.dragBehavior.onDragObservable.add(function (event) {
  100904. if (_this.attachedMesh) {
  100905. if (!_this.attachedMesh.rotationQuaternion) {
  100906. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  100907. }
  100908. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  100909. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  100910. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  100911. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  100912. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  100913. var angle = Math.atan2(cross.length(), dot);
  100914. planeNormalTowardsCamera.copyFrom(planeNormal);
  100915. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  100916. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100917. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  100918. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  100919. }
  100920. // Flip up vector depending on which side the camera is on
  100921. if (gizmoLayer.utilityLayerScene.activeCamera) {
  100922. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  100923. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  100924. planeNormalTowardsCamera.scaleInPlace(-1);
  100925. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  100926. }
  100927. }
  100928. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  100929. if (halfCircleSide) {
  100930. angle = -angle;
  100931. }
  100932. // Snapping logic
  100933. var snapped = false;
  100934. if (_this.snapDistance != 0) {
  100935. currentSnapDragDistance += angle;
  100936. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100937. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100938. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100939. angle = _this.snapDistance * dragSteps;
  100940. snapped = true;
  100941. }
  100942. else {
  100943. angle = 0;
  100944. }
  100945. }
  100946. // If the mesh has a parent, convert needed world rotation to local rotation
  100947. tmpMatrix.reset();
  100948. if (_this.attachedMesh.parent) {
  100949. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100950. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  100951. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  100952. }
  100953. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  100954. var quaternionCoefficient = Math.sin(angle / 2);
  100955. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  100956. // 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
  100957. if (tmpMatrix.determinant() > 0) {
  100958. amountToRotate.toEulerAnglesToRef(tmpVector);
  100959. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  100960. }
  100961. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100962. // Rotate selected mesh quaternion over fixed axis
  100963. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  100964. }
  100965. else {
  100966. // Rotate selected mesh quaternion over rotated axis
  100967. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  100968. }
  100969. lastDragPosition.copyFrom(event.dragPlanePoint);
  100970. if (snapped) {
  100971. tmpSnapEvent.snapDistance = angle;
  100972. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100973. }
  100974. }
  100975. });
  100976. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100977. if (_this._customMeshSet) {
  100978. return;
  100979. }
  100980. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100981. var material = isHovered ? hoverMaterial : coloredMaterial;
  100982. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100983. m.material = material;
  100984. if (m.color) {
  100985. m.color = material.emissiveColor;
  100986. }
  100987. });
  100988. });
  100989. return _this;
  100990. }
  100991. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  100992. if (this.dragBehavior) {
  100993. this.dragBehavior.enabled = value ? true : false;
  100994. }
  100995. };
  100996. /**
  100997. * Disposes of the gizmo
  100998. */
  100999. PlaneRotationGizmo.prototype.dispose = function () {
  101000. this.onSnapObservable.clear();
  101001. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101002. this.dragBehavior.detach();
  101003. _super.prototype.dispose.call(this);
  101004. };
  101005. return PlaneRotationGizmo;
  101006. }(BABYLON.Gizmo));
  101007. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  101008. })(BABYLON || (BABYLON = {}));
  101009. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  101010. var BABYLON;
  101011. (function (BABYLON) {
  101012. /**
  101013. * Gizmo that enables dragging a mesh along 3 axis
  101014. */
  101015. var PositionGizmo = /** @class */ (function (_super) {
  101016. __extends(PositionGizmo, _super);
  101017. /**
  101018. * Creates a PositionGizmo
  101019. * @param gizmoLayer The utility layer the gizmo will be added to
  101020. */
  101021. function PositionGizmo(gizmoLayer) {
  101022. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101023. var _this = _super.call(this, gizmoLayer) || this;
  101024. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  101025. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  101026. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  101027. _this.attachedMesh = null;
  101028. return _this;
  101029. }
  101030. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  101031. set: function (mesh) {
  101032. if (this.xGizmo) {
  101033. this.xGizmo.attachedMesh = mesh;
  101034. this.yGizmo.attachedMesh = mesh;
  101035. this.zGizmo.attachedMesh = mesh;
  101036. }
  101037. },
  101038. enumerable: true,
  101039. configurable: true
  101040. });
  101041. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101042. get: function () {
  101043. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101044. },
  101045. set: function (value) {
  101046. if (this.xGizmo) {
  101047. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101048. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101049. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101050. }
  101051. },
  101052. enumerable: true,
  101053. configurable: true
  101054. });
  101055. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  101056. get: function () {
  101057. return this.xGizmo.snapDistance;
  101058. },
  101059. /**
  101060. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101061. */
  101062. set: function (value) {
  101063. if (this.xGizmo) {
  101064. this.xGizmo.snapDistance = value;
  101065. this.yGizmo.snapDistance = value;
  101066. this.zGizmo.snapDistance = value;
  101067. }
  101068. },
  101069. enumerable: true,
  101070. configurable: true
  101071. });
  101072. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  101073. get: function () {
  101074. return this.xGizmo.scaleRatio;
  101075. },
  101076. /**
  101077. * Ratio for the scale of the gizmo (Default: 1)
  101078. */
  101079. set: function (value) {
  101080. if (this.xGizmo) {
  101081. this.xGizmo.scaleRatio = value;
  101082. this.yGizmo.scaleRatio = value;
  101083. this.zGizmo.scaleRatio = value;
  101084. }
  101085. },
  101086. enumerable: true,
  101087. configurable: true
  101088. });
  101089. /**
  101090. * Disposes of the gizmo
  101091. */
  101092. PositionGizmo.prototype.dispose = function () {
  101093. this.xGizmo.dispose();
  101094. this.yGizmo.dispose();
  101095. this.zGizmo.dispose();
  101096. };
  101097. /**
  101098. * CustomMeshes are not supported by this gizmo
  101099. * @param mesh The mesh to replace the default mesh of the gizmo
  101100. */
  101101. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  101102. 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)");
  101103. };
  101104. return PositionGizmo;
  101105. }(BABYLON.Gizmo));
  101106. BABYLON.PositionGizmo = PositionGizmo;
  101107. })(BABYLON || (BABYLON = {}));
  101108. //# sourceMappingURL=babylon.positionGizmo.js.map
  101109. var BABYLON;
  101110. (function (BABYLON) {
  101111. /**
  101112. * Gizmo that enables rotating a mesh along 3 axis
  101113. */
  101114. var RotationGizmo = /** @class */ (function (_super) {
  101115. __extends(RotationGizmo, _super);
  101116. /**
  101117. * Creates a RotationGizmo
  101118. * @param gizmoLayer The utility layer the gizmo will be added to
  101119. * @param tessellation Amount of tessellation to be used when creating rotation circles
  101120. */
  101121. function RotationGizmo(gizmoLayer, tessellation) {
  101122. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101123. if (tessellation === void 0) { tessellation = 32; }
  101124. var _this = _super.call(this, gizmoLayer) || this;
  101125. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  101126. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  101127. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  101128. _this.attachedMesh = null;
  101129. return _this;
  101130. }
  101131. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  101132. set: function (mesh) {
  101133. if (this.xGizmo) {
  101134. this.xGizmo.attachedMesh = mesh;
  101135. this.yGizmo.attachedMesh = mesh;
  101136. this.zGizmo.attachedMesh = mesh;
  101137. }
  101138. },
  101139. enumerable: true,
  101140. configurable: true
  101141. });
  101142. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101143. get: function () {
  101144. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101145. },
  101146. set: function (value) {
  101147. if (this.xGizmo) {
  101148. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101149. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101150. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101151. }
  101152. },
  101153. enumerable: true,
  101154. configurable: true
  101155. });
  101156. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  101157. get: function () {
  101158. return this.xGizmo.snapDistance;
  101159. },
  101160. /**
  101161. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101162. */
  101163. set: function (value) {
  101164. if (this.xGizmo) {
  101165. this.xGizmo.snapDistance = value;
  101166. this.yGizmo.snapDistance = value;
  101167. this.zGizmo.snapDistance = value;
  101168. }
  101169. },
  101170. enumerable: true,
  101171. configurable: true
  101172. });
  101173. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  101174. get: function () {
  101175. return this.xGizmo.scaleRatio;
  101176. },
  101177. /**
  101178. * Ratio for the scale of the gizmo (Default: 1)
  101179. */
  101180. set: function (value) {
  101181. if (this.xGizmo) {
  101182. this.xGizmo.scaleRatio = value;
  101183. this.yGizmo.scaleRatio = value;
  101184. this.zGizmo.scaleRatio = value;
  101185. }
  101186. },
  101187. enumerable: true,
  101188. configurable: true
  101189. });
  101190. /**
  101191. * Disposes of the gizmo
  101192. */
  101193. RotationGizmo.prototype.dispose = function () {
  101194. this.xGizmo.dispose();
  101195. this.yGizmo.dispose();
  101196. this.zGizmo.dispose();
  101197. };
  101198. /**
  101199. * CustomMeshes are not supported by this gizmo
  101200. * @param mesh The mesh to replace the default mesh of the gizmo
  101201. */
  101202. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  101203. 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)");
  101204. };
  101205. return RotationGizmo;
  101206. }(BABYLON.Gizmo));
  101207. BABYLON.RotationGizmo = RotationGizmo;
  101208. })(BABYLON || (BABYLON = {}));
  101209. //# sourceMappingURL=babylon.rotationGizmo.js.map
  101210. var BABYLON;
  101211. (function (BABYLON) {
  101212. /**
  101213. * Gizmo that enables scaling a mesh along 3 axis
  101214. */
  101215. var ScaleGizmo = /** @class */ (function (_super) {
  101216. __extends(ScaleGizmo, _super);
  101217. /**
  101218. * Creates a ScaleGizmo
  101219. * @param gizmoLayer The utility layer the gizmo will be added to
  101220. */
  101221. function ScaleGizmo(gizmoLayer) {
  101222. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101223. var _this = _super.call(this, gizmoLayer) || this;
  101224. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  101225. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  101226. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  101227. // Create uniform scale gizmo
  101228. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  101229. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  101230. _this.uniformScaleGizmo.uniformScaling = true;
  101231. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  101232. uniformScalingMesh.scaling.scaleInPlace(0.02);
  101233. uniformScalingMesh.visibility = 0;
  101234. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  101235. octahedron.scaling.scaleInPlace(0.007);
  101236. uniformScalingMesh.addChild(octahedron);
  101237. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  101238. _this.attachedMesh = null;
  101239. return _this;
  101240. }
  101241. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  101242. set: function (mesh) {
  101243. if (this.xGizmo) {
  101244. this.xGizmo.attachedMesh = mesh;
  101245. this.yGizmo.attachedMesh = mesh;
  101246. this.zGizmo.attachedMesh = mesh;
  101247. this.uniformScaleGizmo.attachedMesh = mesh;
  101248. }
  101249. },
  101250. enumerable: true,
  101251. configurable: true
  101252. });
  101253. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101254. get: function () {
  101255. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101256. },
  101257. set: function (value) {
  101258. if (!value) {
  101259. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  101260. }
  101261. if (this.xGizmo) {
  101262. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101263. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101264. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101265. }
  101266. },
  101267. enumerable: true,
  101268. configurable: true
  101269. });
  101270. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  101271. get: function () {
  101272. return this.xGizmo.snapDistance;
  101273. },
  101274. /**
  101275. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101276. */
  101277. set: function (value) {
  101278. if (this.xGizmo) {
  101279. this.xGizmo.snapDistance = value;
  101280. this.yGizmo.snapDistance = value;
  101281. this.zGizmo.snapDistance = value;
  101282. this.uniformScaleGizmo.snapDistance = value;
  101283. }
  101284. },
  101285. enumerable: true,
  101286. configurable: true
  101287. });
  101288. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  101289. get: function () {
  101290. return this.xGizmo.scaleRatio;
  101291. },
  101292. /**
  101293. * Ratio for the scale of the gizmo (Default: 1)
  101294. */
  101295. set: function (value) {
  101296. if (this.xGizmo) {
  101297. this.xGizmo.scaleRatio = value;
  101298. this.yGizmo.scaleRatio = value;
  101299. this.zGizmo.scaleRatio = value;
  101300. this.uniformScaleGizmo.scaleRatio = value;
  101301. }
  101302. },
  101303. enumerable: true,
  101304. configurable: true
  101305. });
  101306. /**
  101307. * Disposes of the gizmo
  101308. */
  101309. ScaleGizmo.prototype.dispose = function () {
  101310. this.xGizmo.dispose();
  101311. this.yGizmo.dispose();
  101312. this.zGizmo.dispose();
  101313. this.uniformScaleGizmo.dispose();
  101314. };
  101315. return ScaleGizmo;
  101316. }(BABYLON.Gizmo));
  101317. BABYLON.ScaleGizmo = ScaleGizmo;
  101318. })(BABYLON || (BABYLON = {}));
  101319. //# sourceMappingURL=babylon.scaleGizmo.js.map
  101320. var BABYLON;
  101321. (function (BABYLON) {
  101322. /**
  101323. * Bounding box gizmo
  101324. */
  101325. var BoundingBoxGizmo = /** @class */ (function (_super) {
  101326. __extends(BoundingBoxGizmo, _super);
  101327. /**
  101328. * Creates an BoundingBoxGizmo
  101329. * @param gizmoLayer The utility layer the gizmo will be added to
  101330. * @param color The color of the gizmo
  101331. */
  101332. function BoundingBoxGizmo(color, gizmoLayer) {
  101333. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101334. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  101335. var _this = _super.call(this, gizmoLayer) || this;
  101336. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  101337. _this._renderObserver = null;
  101338. _this._pointerObserver = null;
  101339. _this._scaleDragSpeed = 0.2;
  101340. _this._tmpQuaternion = new BABYLON.Quaternion();
  101341. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  101342. _this._tmpRotationMatrix = new BABYLON.Matrix();
  101343. /**
  101344. * 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)
  101345. */
  101346. _this.ignoreChildren = false;
  101347. /**
  101348. * 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)
  101349. */
  101350. _this.includeChildPredicate = null;
  101351. /**
  101352. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  101353. */
  101354. _this.rotationSphereSize = 0.1;
  101355. /**
  101356. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  101357. */
  101358. _this.scaleBoxSize = 0.1;
  101359. /**
  101360. * 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)
  101361. */
  101362. _this.fixedDragMeshScreenSize = false;
  101363. /**
  101364. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  101365. */
  101366. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  101367. /**
  101368. * Fired when a rotation sphere or scale box is dragged
  101369. */
  101370. _this.onDragStartObservable = new BABYLON.Observable();
  101371. /**
  101372. * Fired when a scale box is dragged
  101373. */
  101374. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  101375. /**
  101376. * Fired when a scale box drag is ended
  101377. */
  101378. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  101379. /**
  101380. * Fired when a rotation sphere is dragged
  101381. */
  101382. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  101383. /**
  101384. * Fired when a rotation sphere drag is ended
  101385. */
  101386. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  101387. /**
  101388. * 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)
  101389. */
  101390. _this.scalePivot = null;
  101391. _this._existingMeshScale = new BABYLON.Vector3();
  101392. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  101393. _this._updateScale = false;
  101394. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  101395. // Create Materials
  101396. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101397. coloredMaterial.disableLighting = true;
  101398. coloredMaterial.emissiveColor = color;
  101399. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101400. hoverColoredMaterial.disableLighting = true;
  101401. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101402. // Build bounding box out of lines
  101403. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101404. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  101405. var lines = [];
  101406. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  101407. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  101408. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  101409. 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));
  101410. 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));
  101411. 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));
  101412. 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));
  101413. 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));
  101414. 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));
  101415. 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));
  101416. 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));
  101417. 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));
  101418. lines.forEach(function (l) {
  101419. l.color = color;
  101420. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  101421. l.isPickable = false;
  101422. _this._lineBoundingBox.addChild(l);
  101423. });
  101424. _this._rootMesh.addChild(_this._lineBoundingBox);
  101425. // Create rotation spheres
  101426. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101427. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  101428. var _loop_1 = function (i_1) {
  101429. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  101430. sphere.rotationQuaternion = new BABYLON.Quaternion();
  101431. sphere.material = coloredMaterial;
  101432. // Drag behavior
  101433. _dragBehavior = new BABYLON.PointerDragBehavior({});
  101434. _dragBehavior.moveAttached = false;
  101435. _dragBehavior.updateDragPlane = false;
  101436. sphere.addBehavior(_dragBehavior);
  101437. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  101438. var totalTurnAmountOfDrag = 0;
  101439. _dragBehavior.onDragStartObservable.add(function (event) {
  101440. startingTurnDirection.copyFrom(sphere.forward);
  101441. totalTurnAmountOfDrag = 0;
  101442. });
  101443. _dragBehavior.onDragObservable.add(function (event) {
  101444. _this.onRotationSphereDragObservable.notifyObservers({});
  101445. if (_this.attachedMesh) {
  101446. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101447. var worldDragDirection = startingTurnDirection;
  101448. // Project the world right on to the drag plane
  101449. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  101450. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  101451. // project drag delta on to the resulting drag axis and rotate based on that
  101452. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  101453. // Make rotation relative to size of mesh.
  101454. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101455. // Rotate based on axis
  101456. if (!_this.attachedMesh.rotationQuaternion) {
  101457. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  101458. }
  101459. if (!_this._anchorMesh.rotationQuaternion) {
  101460. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  101461. }
  101462. // Do not allow the object to turn more than a full circle
  101463. totalTurnAmountOfDrag += projectDist;
  101464. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  101465. if (i_1 >= 8) {
  101466. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  101467. }
  101468. else if (i_1 >= 4) {
  101469. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  101470. }
  101471. else {
  101472. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  101473. }
  101474. // Rotate around center of bounding box
  101475. _this._anchorMesh.addChild(_this.attachedMesh);
  101476. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  101477. _this._anchorMesh.removeChild(_this.attachedMesh);
  101478. }
  101479. _this.updateBoundingBox();
  101480. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101481. }
  101482. });
  101483. // Selection/deselection
  101484. _dragBehavior.onDragStartObservable.add(function () {
  101485. _this.onDragStartObservable.notifyObservers({});
  101486. _this._selectNode(sphere);
  101487. });
  101488. _dragBehavior.onDragEndObservable.add(function () {
  101489. _this.onRotationSphereDragEndObservable.notifyObservers({});
  101490. _this._selectNode(null);
  101491. });
  101492. this_1._rotateSpheresParent.addChild(sphere);
  101493. };
  101494. var this_1 = this, _dragBehavior;
  101495. for (var i_1 = 0; i_1 < 12; i_1++) {
  101496. _loop_1(i_1);
  101497. }
  101498. _this._rootMesh.addChild(_this._rotateSpheresParent);
  101499. // Create scale cubes
  101500. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101501. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  101502. for (var i = 0; i < 2; i++) {
  101503. for (var j = 0; j < 2; j++) {
  101504. var _loop_2 = function () {
  101505. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  101506. box.material = coloredMaterial;
  101507. // Dragging logic
  101508. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  101509. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101510. _dragBehavior.moveAttached = false;
  101511. box.addBehavior(_dragBehavior);
  101512. _dragBehavior.onDragObservable.add(function (event) {
  101513. _this.onScaleBoxDragObservable.notifyObservers({});
  101514. if (_this.attachedMesh) {
  101515. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101516. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101517. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  101518. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  101519. _this.updateBoundingBox();
  101520. if (_this.scalePivot) {
  101521. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  101522. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  101523. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  101524. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101525. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101526. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  101527. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101528. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  101529. }
  101530. else {
  101531. // Scale from the position of the opposite corner
  101532. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  101533. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101534. }
  101535. _this._anchorMesh.addChild(_this.attachedMesh);
  101536. _this._anchorMesh.scaling.addInPlace(deltaScale);
  101537. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  101538. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  101539. }
  101540. _this._anchorMesh.removeChild(_this.attachedMesh);
  101541. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101542. }
  101543. });
  101544. // Selection/deselection
  101545. _dragBehavior.onDragStartObservable.add(function () {
  101546. _this.onDragStartObservable.notifyObservers({});
  101547. _this._selectNode(box);
  101548. });
  101549. _dragBehavior.onDragEndObservable.add(function () {
  101550. _this.onScaleBoxDragEndObservable.notifyObservers({});
  101551. _this._selectNode(null);
  101552. });
  101553. this_2._scaleBoxesParent.addChild(box);
  101554. };
  101555. var this_2 = this, _dragBehavior;
  101556. for (var k = 0; k < 2; k++) {
  101557. _loop_2();
  101558. }
  101559. }
  101560. }
  101561. _this._rootMesh.addChild(_this._scaleBoxesParent);
  101562. // Hover color change
  101563. var pointerIds = new Array();
  101564. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101565. if (!pointerIds[pointerInfo.event.pointerId]) {
  101566. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  101567. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  101568. pointerIds[pointerInfo.event.pointerId] = mesh;
  101569. mesh.material = hoverColoredMaterial;
  101570. }
  101571. });
  101572. }
  101573. else {
  101574. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  101575. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  101576. delete pointerIds[pointerInfo.event.pointerId];
  101577. }
  101578. }
  101579. });
  101580. // Update bounding box positions
  101581. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  101582. // Only update the bouding box if scaling has changed
  101583. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  101584. _this.updateBoundingBox();
  101585. }
  101586. });
  101587. _this.updateBoundingBox();
  101588. return _this;
  101589. }
  101590. /** @hidden */
  101591. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  101592. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  101593. // Save old pivot and set pivot to 0,0,0
  101594. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  101595. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  101596. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  101597. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  101598. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101599. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101600. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101601. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  101602. }
  101603. }
  101604. BoundingBoxGizmo._PivotCached++;
  101605. };
  101606. /** @hidden */
  101607. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  101608. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  101609. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  101610. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101611. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101612. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101613. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  101614. }
  101615. this._PivotCached--;
  101616. };
  101617. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  101618. if (value) {
  101619. // Reset anchor mesh to match attached mesh's scale
  101620. // This is needed to avoid invalid box/sphere position on first drag
  101621. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  101622. this._anchorMesh.addChild(value);
  101623. this._anchorMesh.removeChild(value);
  101624. BoundingBoxGizmo._RestorePivotPoint(value);
  101625. this.updateBoundingBox();
  101626. }
  101627. };
  101628. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  101629. this._rotateSpheresParent.getChildMeshes()
  101630. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  101631. m.isVisible = (!selectedMesh || m == selectedMesh);
  101632. });
  101633. };
  101634. /**
  101635. * Updates the bounding box information for the Gizmo
  101636. */
  101637. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  101638. if (this.attachedMesh) {
  101639. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  101640. this._update();
  101641. // Rotate based on axis
  101642. if (!this.attachedMesh.rotationQuaternion) {
  101643. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  101644. }
  101645. if (!this._anchorMesh.rotationQuaternion) {
  101646. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  101647. }
  101648. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101649. // Store original position and reset mesh to origin before computing the bounding box
  101650. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101651. this._tmpVector.copyFrom(this.attachedMesh.position);
  101652. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  101653. this.attachedMesh.position.set(0, 0, 0);
  101654. // Update bounding dimensions/positions
  101655. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  101656. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  101657. // Update gizmo to match bounding box scaling and rotation
  101658. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  101659. 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);
  101660. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  101661. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  101662. this._lineBoundingBox.computeWorldMatrix();
  101663. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  101664. // restore position/rotation values
  101665. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  101666. this.attachedMesh.position.copyFrom(this._tmpVector);
  101667. }
  101668. // Update rotation sphere locations
  101669. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  101670. for (var i = 0; i < 3; i++) {
  101671. for (var j = 0; j < 2; j++) {
  101672. for (var k = 0; k < 2; k++) {
  101673. var index = ((i * 4) + (j * 2)) + k;
  101674. if (i == 0) {
  101675. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101676. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101677. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101678. }
  101679. if (i == 1) {
  101680. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  101681. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101682. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101683. }
  101684. if (i == 2) {
  101685. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  101686. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101687. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101688. }
  101689. if (this.fixedDragMeshScreenSize) {
  101690. this._rootMesh.computeWorldMatrix();
  101691. this._rotateSpheresParent.computeWorldMatrix();
  101692. rotateSpheres[index].computeWorldMatrix();
  101693. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101694. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101695. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101696. }
  101697. else {
  101698. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  101699. }
  101700. }
  101701. }
  101702. }
  101703. // Update scale box locations
  101704. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  101705. for (var i = 0; i < 2; i++) {
  101706. for (var j = 0; j < 2; j++) {
  101707. for (var k = 0; k < 2; k++) {
  101708. var index = ((i * 4) + (j * 2)) + k;
  101709. if (scaleBoxes[index]) {
  101710. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101711. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101712. if (this.fixedDragMeshScreenSize) {
  101713. this._rootMesh.computeWorldMatrix();
  101714. this._scaleBoxesParent.computeWorldMatrix();
  101715. scaleBoxes[index].computeWorldMatrix();
  101716. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101717. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101718. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101719. }
  101720. else {
  101721. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  101722. }
  101723. }
  101724. }
  101725. }
  101726. }
  101727. if (this.attachedMesh) {
  101728. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  101729. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  101730. }
  101731. };
  101732. /**
  101733. * Enables rotation on the specified axis and disables rotation on the others
  101734. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  101735. */
  101736. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  101737. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  101738. if (i < 4) {
  101739. m.setEnabled(axis.indexOf("x") != -1);
  101740. }
  101741. else if (i < 8) {
  101742. m.setEnabled(axis.indexOf("y") != -1);
  101743. }
  101744. else {
  101745. m.setEnabled(axis.indexOf("z") != -1);
  101746. }
  101747. });
  101748. };
  101749. /**
  101750. * Disposes of the gizmo
  101751. */
  101752. BoundingBoxGizmo.prototype.dispose = function () {
  101753. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101754. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  101755. this._lineBoundingBox.dispose();
  101756. this._rotateSpheresParent.dispose();
  101757. this._scaleBoxesParent.dispose();
  101758. _super.prototype.dispose.call(this);
  101759. };
  101760. /**
  101761. * 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)
  101762. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  101763. * @returns the bounding box mesh with the passed in mesh as a child
  101764. */
  101765. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  101766. var makeNotPickable = function (root) {
  101767. root.isPickable = false;
  101768. root.getChildMeshes().forEach(function (c) {
  101769. makeNotPickable(c);
  101770. });
  101771. };
  101772. makeNotPickable(mesh);
  101773. // Reset position to get boudning box from origin with no rotation
  101774. if (!mesh.rotationQuaternion) {
  101775. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  101776. }
  101777. var oldPos = mesh.position.clone();
  101778. var oldRot = mesh.rotationQuaternion.clone();
  101779. mesh.rotationQuaternion.set(0, 0, 0, 1);
  101780. mesh.position.set(0, 0, 0);
  101781. // Update bounding dimensions/positions
  101782. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  101783. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  101784. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  101785. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  101786. // Restore original positions
  101787. mesh.addChild(box);
  101788. mesh.rotationQuaternion.copyFrom(oldRot);
  101789. mesh.position.copyFrom(oldPos);
  101790. // Reverse parenting
  101791. mesh.removeChild(box);
  101792. box.addChild(mesh);
  101793. box.visibility = 0;
  101794. return box;
  101795. };
  101796. /**
  101797. * CustomMeshes are not supported by this gizmo
  101798. * @param mesh The mesh to replace the default mesh of the gizmo
  101799. */
  101800. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  101801. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  101802. };
  101803. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  101804. // store/remove pivot point should only be applied during their outermost calls
  101805. BoundingBoxGizmo._PivotCached = 0;
  101806. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  101807. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  101808. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  101809. return BoundingBoxGizmo;
  101810. }(BABYLON.Gizmo));
  101811. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  101812. })(BABYLON || (BABYLON = {}));
  101813. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  101814. var BABYLON;
  101815. (function (BABYLON) {
  101816. /**
  101817. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  101818. */
  101819. var GizmoManager = /** @class */ (function () {
  101820. /**
  101821. * Instatiates a gizmo manager
  101822. * @param scene the scene to overlay the gizmos on top of
  101823. */
  101824. function GizmoManager(scene) {
  101825. var _this = this;
  101826. this.scene = scene;
  101827. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  101828. this._pointerObserver = null;
  101829. this._attachedMesh = null;
  101830. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  101831. /**
  101832. * When bounding box gizmo is enabled, this can be used to track drag/end events
  101833. */
  101834. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  101835. /**
  101836. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  101837. */
  101838. this.attachableMeshes = null;
  101839. /**
  101840. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  101841. */
  101842. this.usePointerToAttachGizmos = true;
  101843. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101844. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  101845. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101846. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  101847. // Instatiate/dispose gizmos based on pointer actions
  101848. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  101849. if (!_this.usePointerToAttachGizmos) {
  101850. return;
  101851. }
  101852. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101853. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  101854. var node = pointerInfo.pickInfo.pickedMesh;
  101855. if (_this.attachableMeshes == null) {
  101856. // Attach to the most parent node
  101857. while (node && node.parent != null) {
  101858. node = node.parent;
  101859. }
  101860. }
  101861. else {
  101862. // Attach to the parent node that is an attachableMesh
  101863. var found = false;
  101864. _this.attachableMeshes.forEach(function (mesh) {
  101865. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  101866. node = mesh;
  101867. found = true;
  101868. }
  101869. });
  101870. if (!found) {
  101871. node = null;
  101872. }
  101873. }
  101874. if (node instanceof BABYLON.AbstractMesh) {
  101875. _this.attachToMesh(node);
  101876. }
  101877. else {
  101878. _this.attachToMesh(null);
  101879. }
  101880. }
  101881. else {
  101882. _this.attachToMesh(null);
  101883. }
  101884. }
  101885. });
  101886. }
  101887. /**
  101888. * Attaches a set of gizmos to the specified mesh
  101889. * @param mesh The mesh the gizmo's should be attached to
  101890. */
  101891. GizmoManager.prototype.attachToMesh = function (mesh) {
  101892. if (this._attachedMesh) {
  101893. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101894. }
  101895. this._attachedMesh = mesh;
  101896. for (var key in this.gizmos) {
  101897. var gizmo = (this.gizmos[key]);
  101898. if (gizmo && this._gizmosEnabled[key]) {
  101899. gizmo.attachedMesh = mesh;
  101900. }
  101901. }
  101902. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  101903. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  101904. }
  101905. };
  101906. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  101907. get: function () {
  101908. return this._gizmosEnabled.positionGizmo;
  101909. },
  101910. /**
  101911. * If the position gizmo is enabled
  101912. */
  101913. set: function (value) {
  101914. if (value) {
  101915. if (!this.gizmos.positionGizmo) {
  101916. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  101917. }
  101918. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  101919. }
  101920. else if (this.gizmos.positionGizmo) {
  101921. this.gizmos.positionGizmo.attachedMesh = null;
  101922. }
  101923. this._gizmosEnabled.positionGizmo = value;
  101924. },
  101925. enumerable: true,
  101926. configurable: true
  101927. });
  101928. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  101929. get: function () {
  101930. return this._gizmosEnabled.rotationGizmo;
  101931. },
  101932. /**
  101933. * If the rotation gizmo is enabled
  101934. */
  101935. set: function (value) {
  101936. if (value) {
  101937. if (!this.gizmos.rotationGizmo) {
  101938. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  101939. }
  101940. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  101941. }
  101942. else if (this.gizmos.rotationGizmo) {
  101943. this.gizmos.rotationGizmo.attachedMesh = null;
  101944. }
  101945. this._gizmosEnabled.rotationGizmo = value;
  101946. },
  101947. enumerable: true,
  101948. configurable: true
  101949. });
  101950. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  101951. get: function () {
  101952. return this._gizmosEnabled.scaleGizmo;
  101953. },
  101954. /**
  101955. * If the scale gizmo is enabled
  101956. */
  101957. set: function (value) {
  101958. if (value) {
  101959. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  101960. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  101961. }
  101962. else if (this.gizmos.scaleGizmo) {
  101963. this.gizmos.scaleGizmo.attachedMesh = null;
  101964. }
  101965. this._gizmosEnabled.scaleGizmo = value;
  101966. },
  101967. enumerable: true,
  101968. configurable: true
  101969. });
  101970. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  101971. get: function () {
  101972. return this._gizmosEnabled.boundingBoxGizmo;
  101973. },
  101974. /**
  101975. * If the boundingBox gizmo is enabled
  101976. */
  101977. set: function (value) {
  101978. if (value) {
  101979. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  101980. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  101981. if (this._attachedMesh) {
  101982. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101983. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  101984. }
  101985. }
  101986. else if (this.gizmos.boundingBoxGizmo) {
  101987. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  101988. }
  101989. this._gizmosEnabled.boundingBoxGizmo = value;
  101990. },
  101991. enumerable: true,
  101992. configurable: true
  101993. });
  101994. /**
  101995. * Disposes of the gizmo manager
  101996. */
  101997. GizmoManager.prototype.dispose = function () {
  101998. this.scene.onPointerObservable.remove(this._pointerObserver);
  101999. for (var key in this.gizmos) {
  102000. var gizmo = (this.gizmos[key]);
  102001. if (gizmo) {
  102002. gizmo.dispose();
  102003. }
  102004. }
  102005. this._defaultKeepDepthUtilityLayer.dispose();
  102006. this._defaultUtilityLayer.dispose();
  102007. this.boundingBoxDragBehavior.detach();
  102008. };
  102009. return GizmoManager;
  102010. }());
  102011. BABYLON.GizmoManager = GizmoManager;
  102012. })(BABYLON || (BABYLON = {}));
  102013. //# sourceMappingURL=babylon.gizmoManager.js.map
  102014. var BABYLON;
  102015. (function (BABYLON) {
  102016. /**
  102017. * Defines a target to use with MorphTargetManager
  102018. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  102019. */
  102020. var MorphTarget = /** @class */ (function () {
  102021. /**
  102022. * Creates a new MorphTarget
  102023. * @param name defines the name of the target
  102024. * @param influence defines the influence to use
  102025. */
  102026. function MorphTarget(
  102027. /** defines the name of the target */
  102028. name, influence, scene) {
  102029. if (influence === void 0) { influence = 0; }
  102030. if (scene === void 0) { scene = null; }
  102031. this.name = name;
  102032. /**
  102033. * Gets or sets the list of animations
  102034. */
  102035. this.animations = new Array();
  102036. this._positions = null;
  102037. this._normals = null;
  102038. this._tangents = null;
  102039. /**
  102040. * Observable raised when the influence changes
  102041. */
  102042. this.onInfluenceChanged = new BABYLON.Observable();
  102043. this._animationPropertiesOverride = null;
  102044. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102045. this.influence = influence;
  102046. }
  102047. Object.defineProperty(MorphTarget.prototype, "influence", {
  102048. /**
  102049. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  102050. */
  102051. get: function () {
  102052. return this._influence;
  102053. },
  102054. set: function (influence) {
  102055. if (this._influence === influence) {
  102056. return;
  102057. }
  102058. var previous = this._influence;
  102059. this._influence = influence;
  102060. if (this.onInfluenceChanged.hasObservers) {
  102061. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  102062. }
  102063. },
  102064. enumerable: true,
  102065. configurable: true
  102066. });
  102067. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  102068. /**
  102069. * Gets or sets the animation properties override
  102070. */
  102071. get: function () {
  102072. if (!this._animationPropertiesOverride && this._scene) {
  102073. return this._scene.animationPropertiesOverride;
  102074. }
  102075. return this._animationPropertiesOverride;
  102076. },
  102077. set: function (value) {
  102078. this._animationPropertiesOverride = value;
  102079. },
  102080. enumerable: true,
  102081. configurable: true
  102082. });
  102083. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  102084. /**
  102085. * Gets a boolean defining if the target contains position data
  102086. */
  102087. get: function () {
  102088. return !!this._positions;
  102089. },
  102090. enumerable: true,
  102091. configurable: true
  102092. });
  102093. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  102094. /**
  102095. * Gets a boolean defining if the target contains normal data
  102096. */
  102097. get: function () {
  102098. return !!this._normals;
  102099. },
  102100. enumerable: true,
  102101. configurable: true
  102102. });
  102103. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  102104. /**
  102105. * Gets a boolean defining if the target contains tangent data
  102106. */
  102107. get: function () {
  102108. return !!this._tangents;
  102109. },
  102110. enumerable: true,
  102111. configurable: true
  102112. });
  102113. /**
  102114. * Affects position data to this target
  102115. * @param data defines the position data to use
  102116. */
  102117. MorphTarget.prototype.setPositions = function (data) {
  102118. this._positions = data;
  102119. };
  102120. /**
  102121. * Gets the position data stored in this target
  102122. * @returns a FloatArray containing the position data (or null if not present)
  102123. */
  102124. MorphTarget.prototype.getPositions = function () {
  102125. return this._positions;
  102126. };
  102127. /**
  102128. * Affects normal data to this target
  102129. * @param data defines the normal data to use
  102130. */
  102131. MorphTarget.prototype.setNormals = function (data) {
  102132. this._normals = data;
  102133. };
  102134. /**
  102135. * Gets the normal data stored in this target
  102136. * @returns a FloatArray containing the normal data (or null if not present)
  102137. */
  102138. MorphTarget.prototype.getNormals = function () {
  102139. return this._normals;
  102140. };
  102141. /**
  102142. * Affects tangent data to this target
  102143. * @param data defines the tangent data to use
  102144. */
  102145. MorphTarget.prototype.setTangents = function (data) {
  102146. this._tangents = data;
  102147. };
  102148. /**
  102149. * Gets the tangent data stored in this target
  102150. * @returns a FloatArray containing the tangent data (or null if not present)
  102151. */
  102152. MorphTarget.prototype.getTangents = function () {
  102153. return this._tangents;
  102154. };
  102155. /**
  102156. * Serializes the current target into a Serialization object
  102157. * @returns the serialized object
  102158. */
  102159. MorphTarget.prototype.serialize = function () {
  102160. var serializationObject = {};
  102161. serializationObject.name = this.name;
  102162. serializationObject.influence = this.influence;
  102163. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  102164. if (this.hasNormals) {
  102165. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  102166. }
  102167. if (this.hasTangents) {
  102168. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  102169. }
  102170. // Animations
  102171. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  102172. return serializationObject;
  102173. };
  102174. // Statics
  102175. /**
  102176. * Creates a new target from serialized data
  102177. * @param serializationObject defines the serialized data to use
  102178. * @returns a new MorphTarget
  102179. */
  102180. MorphTarget.Parse = function (serializationObject) {
  102181. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  102182. result.setPositions(serializationObject.positions);
  102183. if (serializationObject.normals) {
  102184. result.setNormals(serializationObject.normals);
  102185. }
  102186. if (serializationObject.tangents) {
  102187. result.setTangents(serializationObject.tangents);
  102188. }
  102189. // Animations
  102190. if (serializationObject.animations) {
  102191. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  102192. var parsedAnimation = serializationObject.animations[animationIndex];
  102193. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  102194. }
  102195. }
  102196. return result;
  102197. };
  102198. /**
  102199. * Creates a MorphTarget from mesh data
  102200. * @param mesh defines the source mesh
  102201. * @param name defines the name to use for the new target
  102202. * @param influence defines the influence to attach to the target
  102203. * @returns a new MorphTarget
  102204. */
  102205. MorphTarget.FromMesh = function (mesh, name, influence) {
  102206. if (!name) {
  102207. name = mesh.name;
  102208. }
  102209. var result = new MorphTarget(name, influence, mesh.getScene());
  102210. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  102211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102212. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  102213. }
  102214. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  102215. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  102216. }
  102217. return result;
  102218. };
  102219. return MorphTarget;
  102220. }());
  102221. BABYLON.MorphTarget = MorphTarget;
  102222. })(BABYLON || (BABYLON = {}));
  102223. //# sourceMappingURL=babylon.morphTarget.js.map
  102224. var BABYLON;
  102225. (function (BABYLON) {
  102226. /**
  102227. * This class is used to deform meshes using morphing between different targets
  102228. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  102229. */
  102230. var MorphTargetManager = /** @class */ (function () {
  102231. /**
  102232. * Creates a new MorphTargetManager
  102233. * @param scene defines the current scene
  102234. */
  102235. function MorphTargetManager(scene) {
  102236. if (scene === void 0) { scene = null; }
  102237. this._targets = new Array();
  102238. this._targetObservable = new Array();
  102239. this._activeTargets = new BABYLON.SmartArray(16);
  102240. this._supportsNormals = false;
  102241. this._supportsTangents = false;
  102242. this._vertexCount = 0;
  102243. this._uniqueId = 0;
  102244. this._tempInfluences = new Array();
  102245. if (!scene) {
  102246. scene = BABYLON.Engine.LastCreatedScene;
  102247. }
  102248. this._scene = scene;
  102249. if (this._scene) {
  102250. this._scene.morphTargetManagers.push(this);
  102251. this._uniqueId = this._scene.getUniqueId();
  102252. }
  102253. }
  102254. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  102255. /**
  102256. * Gets the unique ID of this manager
  102257. */
  102258. get: function () {
  102259. return this._uniqueId;
  102260. },
  102261. enumerable: true,
  102262. configurable: true
  102263. });
  102264. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  102265. /**
  102266. * Gets the number of vertices handled by this manager
  102267. */
  102268. get: function () {
  102269. return this._vertexCount;
  102270. },
  102271. enumerable: true,
  102272. configurable: true
  102273. });
  102274. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  102275. /**
  102276. * Gets a boolean indicating if this manager supports morphing of normals
  102277. */
  102278. get: function () {
  102279. return this._supportsNormals;
  102280. },
  102281. enumerable: true,
  102282. configurable: true
  102283. });
  102284. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  102285. /**
  102286. * Gets a boolean indicating if this manager supports morphing of tangents
  102287. */
  102288. get: function () {
  102289. return this._supportsTangents;
  102290. },
  102291. enumerable: true,
  102292. configurable: true
  102293. });
  102294. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  102295. /**
  102296. * Gets the number of targets stored in this manager
  102297. */
  102298. get: function () {
  102299. return this._targets.length;
  102300. },
  102301. enumerable: true,
  102302. configurable: true
  102303. });
  102304. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  102305. /**
  102306. * Gets the number of influencers (ie. the number of targets with influences > 0)
  102307. */
  102308. get: function () {
  102309. return this._activeTargets.length;
  102310. },
  102311. enumerable: true,
  102312. configurable: true
  102313. });
  102314. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  102315. /**
  102316. * Gets the list of influences (one per target)
  102317. */
  102318. get: function () {
  102319. return this._influences;
  102320. },
  102321. enumerable: true,
  102322. configurable: true
  102323. });
  102324. /**
  102325. * Gets the active target at specified index. An active target is a target with an influence > 0
  102326. * @param index defines the index to check
  102327. * @returns the requested target
  102328. */
  102329. MorphTargetManager.prototype.getActiveTarget = function (index) {
  102330. return this._activeTargets.data[index];
  102331. };
  102332. /**
  102333. * Gets the target at specified index
  102334. * @param index defines the index to check
  102335. * @returns the requested target
  102336. */
  102337. MorphTargetManager.prototype.getTarget = function (index) {
  102338. return this._targets[index];
  102339. };
  102340. /**
  102341. * Add a new target to this manager
  102342. * @param target defines the target to add
  102343. */
  102344. MorphTargetManager.prototype.addTarget = function (target) {
  102345. var _this = this;
  102346. this._targets.push(target);
  102347. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  102348. _this._syncActiveTargets(needUpdate);
  102349. }));
  102350. this._syncActiveTargets(true);
  102351. };
  102352. /**
  102353. * Removes a target from the manager
  102354. * @param target defines the target to remove
  102355. */
  102356. MorphTargetManager.prototype.removeTarget = function (target) {
  102357. var index = this._targets.indexOf(target);
  102358. if (index >= 0) {
  102359. this._targets.splice(index, 1);
  102360. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  102361. this._syncActiveTargets(true);
  102362. }
  102363. };
  102364. /**
  102365. * Serializes the current manager into a Serialization object
  102366. * @returns the serialized object
  102367. */
  102368. MorphTargetManager.prototype.serialize = function () {
  102369. var serializationObject = {};
  102370. serializationObject.id = this.uniqueId;
  102371. serializationObject.targets = [];
  102372. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102373. var target = _a[_i];
  102374. serializationObject.targets.push(target.serialize());
  102375. }
  102376. return serializationObject;
  102377. };
  102378. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  102379. var influenceCount = 0;
  102380. this._activeTargets.reset();
  102381. this._supportsNormals = true;
  102382. this._supportsTangents = true;
  102383. this._vertexCount = 0;
  102384. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102385. var target = _a[_i];
  102386. this._activeTargets.push(target);
  102387. this._tempInfluences[influenceCount++] = target.influence;
  102388. var positions = target.getPositions();
  102389. if (positions) {
  102390. this._supportsNormals = this._supportsNormals && target.hasNormals;
  102391. this._supportsTangents = this._supportsTangents && target.hasTangents;
  102392. var vertexCount = positions.length / 3;
  102393. if (this._vertexCount === 0) {
  102394. this._vertexCount = vertexCount;
  102395. }
  102396. else if (this._vertexCount !== vertexCount) {
  102397. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  102398. return;
  102399. }
  102400. }
  102401. }
  102402. if (!this._influences || this._influences.length !== influenceCount) {
  102403. this._influences = new Float32Array(influenceCount);
  102404. }
  102405. for (var index = 0; index < influenceCount; index++) {
  102406. this._influences[index] = this._tempInfluences[index];
  102407. }
  102408. if (needUpdate) {
  102409. this.synchronize();
  102410. }
  102411. };
  102412. /**
  102413. * Syncrhonize the targets with all the meshes using this morph target manager
  102414. */
  102415. MorphTargetManager.prototype.synchronize = function () {
  102416. if (!this._scene) {
  102417. return;
  102418. }
  102419. // Flag meshes as dirty to resync with the active targets
  102420. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  102421. var mesh = _a[_i];
  102422. if (mesh.morphTargetManager === this) {
  102423. mesh._syncGeometryWithMorphTargetManager();
  102424. }
  102425. }
  102426. };
  102427. // Statics
  102428. /**
  102429. * Creates a new MorphTargetManager from serialized data
  102430. * @param serializationObject defines the serialized data
  102431. * @param scene defines the hosting scene
  102432. * @returns the new MorphTargetManager
  102433. */
  102434. MorphTargetManager.Parse = function (serializationObject, scene) {
  102435. var result = new MorphTargetManager(scene);
  102436. result._uniqueId = serializationObject.id;
  102437. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  102438. var targetData = _a[_i];
  102439. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  102440. }
  102441. return result;
  102442. };
  102443. return MorphTargetManager;
  102444. }());
  102445. BABYLON.MorphTargetManager = MorphTargetManager;
  102446. })(BABYLON || (BABYLON = {}));
  102447. //# sourceMappingURL=babylon.morphTargetManager.js.map
  102448. var BABYLON;
  102449. (function (BABYLON) {
  102450. /**
  102451. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  102452. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102453. */
  102454. var Octree = /** @class */ (function () {
  102455. /**
  102456. * Creates a octree
  102457. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102458. * @param creationFunc function to be used to instatiate the octree
  102459. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  102460. * @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.)
  102461. */
  102462. function Octree(creationFunc, maxBlockCapacity,
  102463. /** 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.) */
  102464. maxDepth) {
  102465. if (maxDepth === void 0) { maxDepth = 2; }
  102466. this.maxDepth = maxDepth;
  102467. /**
  102468. * Content stored in the octree
  102469. */
  102470. this.dynamicContent = new Array();
  102471. this._maxBlockCapacity = maxBlockCapacity || 64;
  102472. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  102473. this._creationFunc = creationFunc;
  102474. }
  102475. // Methods
  102476. /**
  102477. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  102478. * @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);
  102479. * @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);
  102480. * @param entries meshes to be added to the octree blocks
  102481. */
  102482. Octree.prototype.update = function (worldMin, worldMax, entries) {
  102483. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  102484. };
  102485. /**
  102486. * Adds a mesh to the octree
  102487. * @param entry Mesh to add to the octree
  102488. */
  102489. Octree.prototype.addMesh = function (entry) {
  102490. for (var index = 0; index < this.blocks.length; index++) {
  102491. var block = this.blocks[index];
  102492. block.addEntry(entry);
  102493. }
  102494. };
  102495. /**
  102496. * Selects an array of meshes within the frustum
  102497. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  102498. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  102499. * @returns array of meshes within the frustum
  102500. */
  102501. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  102502. this._selectionContent.reset();
  102503. for (var index = 0; index < this.blocks.length; index++) {
  102504. var block = this.blocks[index];
  102505. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  102506. }
  102507. if (allowDuplicate) {
  102508. this._selectionContent.concat(this.dynamicContent);
  102509. }
  102510. else {
  102511. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102512. }
  102513. return this._selectionContent;
  102514. };
  102515. /**
  102516. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  102517. * @param sphereCenter defines the bounding sphere center
  102518. * @param sphereRadius defines the bounding sphere radius
  102519. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102520. * @returns an array of objects that intersect the sphere
  102521. */
  102522. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  102523. this._selectionContent.reset();
  102524. for (var index = 0; index < this.blocks.length; index++) {
  102525. var block = this.blocks[index];
  102526. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  102527. }
  102528. if (allowDuplicate) {
  102529. this._selectionContent.concat(this.dynamicContent);
  102530. }
  102531. else {
  102532. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102533. }
  102534. return this._selectionContent;
  102535. };
  102536. /**
  102537. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  102538. * @param ray defines the ray to test with
  102539. * @returns array of intersected objects
  102540. */
  102541. Octree.prototype.intersectsRay = function (ray) {
  102542. this._selectionContent.reset();
  102543. for (var index = 0; index < this.blocks.length; index++) {
  102544. var block = this.blocks[index];
  102545. block.intersectsRay(ray, this._selectionContent);
  102546. }
  102547. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102548. return this._selectionContent;
  102549. };
  102550. /**
  102551. * @hidden
  102552. */
  102553. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  102554. target.blocks = new Array();
  102555. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102556. // Segmenting space
  102557. for (var x = 0; x < 2; x++) {
  102558. for (var y = 0; y < 2; y++) {
  102559. for (var z = 0; z < 2; z++) {
  102560. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  102561. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  102562. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  102563. block.addEntries(entries);
  102564. target.blocks.push(block);
  102565. }
  102566. }
  102567. }
  102568. };
  102569. /**
  102570. * Adds a mesh into the octree block if it intersects the block
  102571. */
  102572. Octree.CreationFuncForMeshes = function (entry, block) {
  102573. var boundingInfo = entry.getBoundingInfo();
  102574. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102575. block.entries.push(entry);
  102576. }
  102577. };
  102578. /**
  102579. * Adds a submesh into the octree block if it intersects the block
  102580. */
  102581. Octree.CreationFuncForSubMeshes = function (entry, block) {
  102582. var boundingInfo = entry.getBoundingInfo();
  102583. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102584. block.entries.push(entry);
  102585. }
  102586. };
  102587. return Octree;
  102588. }());
  102589. BABYLON.Octree = Octree;
  102590. })(BABYLON || (BABYLON = {}));
  102591. //# sourceMappingURL=babylon.octree.js.map
  102592. var BABYLON;
  102593. (function (BABYLON) {
  102594. /**
  102595. * Class used to store a cell in an octree
  102596. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102597. */
  102598. var OctreeBlock = /** @class */ (function () {
  102599. /**
  102600. * Creates a new block
  102601. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  102602. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  102603. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102604. * @param depth defines the current depth of this block in the octree
  102605. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  102606. * @param creationFunc defines a callback to call when an element is added to the block
  102607. */
  102608. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  102609. /**
  102610. * Gets the content of the current block
  102611. */
  102612. this.entries = new Array();
  102613. this._boundingVectors = new Array();
  102614. this._capacity = capacity;
  102615. this._depth = depth;
  102616. this._maxDepth = maxDepth;
  102617. this._creationFunc = creationFunc;
  102618. this._minPoint = minPoint;
  102619. this._maxPoint = maxPoint;
  102620. this._boundingVectors.push(minPoint.clone());
  102621. this._boundingVectors.push(maxPoint.clone());
  102622. this._boundingVectors.push(minPoint.clone());
  102623. this._boundingVectors[2].x = maxPoint.x;
  102624. this._boundingVectors.push(minPoint.clone());
  102625. this._boundingVectors[3].y = maxPoint.y;
  102626. this._boundingVectors.push(minPoint.clone());
  102627. this._boundingVectors[4].z = maxPoint.z;
  102628. this._boundingVectors.push(maxPoint.clone());
  102629. this._boundingVectors[5].z = minPoint.z;
  102630. this._boundingVectors.push(maxPoint.clone());
  102631. this._boundingVectors[6].x = minPoint.x;
  102632. this._boundingVectors.push(maxPoint.clone());
  102633. this._boundingVectors[7].y = minPoint.y;
  102634. }
  102635. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  102636. // Property
  102637. /**
  102638. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102639. */
  102640. get: function () {
  102641. return this._capacity;
  102642. },
  102643. enumerable: true,
  102644. configurable: true
  102645. });
  102646. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  102647. /**
  102648. * Gets the minimum vector (in world space) of the block's bounding box
  102649. */
  102650. get: function () {
  102651. return this._minPoint;
  102652. },
  102653. enumerable: true,
  102654. configurable: true
  102655. });
  102656. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  102657. /**
  102658. * Gets the maximum vector (in world space) of the block's bounding box
  102659. */
  102660. get: function () {
  102661. return this._maxPoint;
  102662. },
  102663. enumerable: true,
  102664. configurable: true
  102665. });
  102666. // Methods
  102667. /**
  102668. * Add a new element to this block
  102669. * @param entry defines the element to add
  102670. */
  102671. OctreeBlock.prototype.addEntry = function (entry) {
  102672. if (this.blocks) {
  102673. for (var index = 0; index < this.blocks.length; index++) {
  102674. var block = this.blocks[index];
  102675. block.addEntry(entry);
  102676. }
  102677. return;
  102678. }
  102679. this._creationFunc(entry, this);
  102680. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  102681. this.createInnerBlocks();
  102682. }
  102683. };
  102684. /**
  102685. * Add an array of elements to this block
  102686. * @param entries defines the array of elements to add
  102687. */
  102688. OctreeBlock.prototype.addEntries = function (entries) {
  102689. for (var index = 0; index < entries.length; index++) {
  102690. var mesh = entries[index];
  102691. this.addEntry(mesh);
  102692. }
  102693. };
  102694. /**
  102695. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  102696. * @param frustumPlanes defines the frustum planes to test
  102697. * @param selection defines the array to store current content if selection is positive
  102698. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102699. */
  102700. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  102701. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  102702. if (this.blocks) {
  102703. for (var index = 0; index < this.blocks.length; index++) {
  102704. var block = this.blocks[index];
  102705. block.select(frustumPlanes, selection, allowDuplicate);
  102706. }
  102707. return;
  102708. }
  102709. if (allowDuplicate) {
  102710. selection.concat(this.entries);
  102711. }
  102712. else {
  102713. selection.concatWithNoDuplicate(this.entries);
  102714. }
  102715. }
  102716. };
  102717. /**
  102718. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  102719. * @param sphereCenter defines the bounding sphere center
  102720. * @param sphereRadius defines the bounding sphere radius
  102721. * @param selection defines the array to store current content if selection is positive
  102722. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102723. */
  102724. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  102725. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  102726. if (this.blocks) {
  102727. for (var index = 0; index < this.blocks.length; index++) {
  102728. var block = this.blocks[index];
  102729. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  102730. }
  102731. return;
  102732. }
  102733. if (allowDuplicate) {
  102734. selection.concat(this.entries);
  102735. }
  102736. else {
  102737. selection.concatWithNoDuplicate(this.entries);
  102738. }
  102739. }
  102740. };
  102741. /**
  102742. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  102743. * @param ray defines the ray to test with
  102744. * @param selection defines the array to store current content if selection is positive
  102745. */
  102746. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  102747. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  102748. if (this.blocks) {
  102749. for (var index = 0; index < this.blocks.length; index++) {
  102750. var block = this.blocks[index];
  102751. block.intersectsRay(ray, selection);
  102752. }
  102753. return;
  102754. }
  102755. selection.concatWithNoDuplicate(this.entries);
  102756. }
  102757. };
  102758. /**
  102759. * Subdivide the content into child blocks (this block will then be empty)
  102760. */
  102761. OctreeBlock.prototype.createInnerBlocks = function () {
  102762. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  102763. };
  102764. return OctreeBlock;
  102765. }());
  102766. BABYLON.OctreeBlock = OctreeBlock;
  102767. })(BABYLON || (BABYLON = {}));
  102768. //# sourceMappingURL=babylon.octreeBlock.js.map
  102769. var BABYLON;
  102770. (function (BABYLON) {
  102771. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  102772. if (maxCapacity === void 0) { maxCapacity = 64; }
  102773. if (maxDepth === void 0) { maxDepth = 2; }
  102774. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102775. if (!component) {
  102776. component = new OctreeSceneComponent(this);
  102777. this._addComponent(component);
  102778. }
  102779. if (!this._selectionOctree) {
  102780. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  102781. }
  102782. var worldExtends = this.getWorldExtends();
  102783. // Update octree
  102784. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  102785. return this._selectionOctree;
  102786. };
  102787. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  102788. get: function () {
  102789. return this._selectionOctree;
  102790. },
  102791. enumerable: true,
  102792. configurable: true
  102793. });
  102794. /**
  102795. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  102796. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  102797. * @param maxCapacity defines the maximum size of each block (64 by default)
  102798. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  102799. * @returns the new octree
  102800. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  102801. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102802. */
  102803. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  102804. if (maxCapacity === void 0) { maxCapacity = 64; }
  102805. if (maxDepth === void 0) { maxDepth = 2; }
  102806. var scene = this.getScene();
  102807. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102808. if (!component) {
  102809. component = new OctreeSceneComponent(scene);
  102810. scene._addComponent(component);
  102811. }
  102812. if (!this._submeshesOctree) {
  102813. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  102814. }
  102815. this.computeWorldMatrix(true);
  102816. var boundingInfo = this.getBoundingInfo();
  102817. // Update octree
  102818. var bbox = boundingInfo.boundingBox;
  102819. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  102820. return this._submeshesOctree;
  102821. };
  102822. /**
  102823. * Defines the octree scene component responsible to manage any octrees
  102824. * in a given scene.
  102825. */
  102826. var OctreeSceneComponent = /** @class */ (function () {
  102827. /**
  102828. * Creates a new instance of the component for the given scene
  102829. * @param scene Defines the scene to register the component in
  102830. */
  102831. function OctreeSceneComponent(scene) {
  102832. /**
  102833. * The component name helpfull to identify the component in the list of scene components.
  102834. */
  102835. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  102836. /**
  102837. * Indicates if the meshes have been checked to make sure they are isEnabled()
  102838. */
  102839. this.checksIsEnabled = true;
  102840. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  102841. this.scene = scene;
  102842. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  102843. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  102844. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  102845. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  102846. }
  102847. /**
  102848. * Registers the component in a given scene
  102849. */
  102850. OctreeSceneComponent.prototype.register = function () {
  102851. var _this = this;
  102852. this.scene.onMeshRemovedObservable.add(function (mesh) {
  102853. var sceneOctree = _this.scene.selectionOctree;
  102854. if (sceneOctree !== undefined && sceneOctree !== null) {
  102855. var index = sceneOctree.dynamicContent.indexOf(mesh);
  102856. if (index !== -1) {
  102857. sceneOctree.dynamicContent.splice(index, 1);
  102858. }
  102859. }
  102860. });
  102861. this.scene.onMeshImportedObservable.add(function (mesh) {
  102862. var sceneOctree = _this.scene.selectionOctree;
  102863. if (sceneOctree !== undefined && sceneOctree !== null) {
  102864. sceneOctree.addMesh(mesh);
  102865. }
  102866. });
  102867. };
  102868. /**
  102869. * Return the list of active meshes
  102870. * @returns the list of active meshes
  102871. */
  102872. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  102873. if (this.scene._selectionOctree) {
  102874. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  102875. return selection;
  102876. }
  102877. return this.scene._getDefaultMeshCandidates();
  102878. };
  102879. /**
  102880. * Return the list of active sub meshes
  102881. * @param mesh The mesh to get the candidates sub meshes from
  102882. * @returns the list of active sub meshes
  102883. */
  102884. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  102885. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  102886. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  102887. return intersections;
  102888. }
  102889. return this.scene._getDefaultSubMeshCandidates(mesh);
  102890. };
  102891. /**
  102892. * Return the list of sub meshes intersecting with a given local ray
  102893. * @param mesh defines the mesh to find the submesh for
  102894. * @param localRay defines the ray in local space
  102895. * @returns the list of intersecting sub meshes
  102896. */
  102897. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  102898. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  102899. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  102900. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  102901. return intersections;
  102902. }
  102903. return this.scene._getDefaultSubMeshCandidates(mesh);
  102904. };
  102905. /**
  102906. * Return the list of sub meshes colliding with a collider
  102907. * @param mesh defines the mesh to find the submesh for
  102908. * @param collider defines the collider to evaluate the collision against
  102909. * @returns the list of colliding sub meshes
  102910. */
  102911. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  102912. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  102913. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  102914. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  102915. return intersections;
  102916. }
  102917. return this.scene._getDefaultSubMeshCandidates(mesh);
  102918. };
  102919. /**
  102920. * Rebuilds the elements related to this component in case of
  102921. * context lost for instance.
  102922. */
  102923. OctreeSceneComponent.prototype.rebuild = function () {
  102924. // Nothing to do here.
  102925. };
  102926. /**
  102927. * Disposes the component and the associated ressources.
  102928. */
  102929. OctreeSceneComponent.prototype.dispose = function () {
  102930. // Nothing to do here.
  102931. };
  102932. return OctreeSceneComponent;
  102933. }());
  102934. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  102935. })(BABYLON || (BABYLON = {}));
  102936. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  102937. var BABYLON;
  102938. (function (BABYLON) {
  102939. /**
  102940. * Postprocess used to generate anaglyphic rendering
  102941. */
  102942. var AnaglyphPostProcess = /** @class */ (function (_super) {
  102943. __extends(AnaglyphPostProcess, _super);
  102944. /**
  102945. * Creates a new AnaglyphPostProcess
  102946. * @param name defines postprocess name
  102947. * @param options defines creation options or target ratio scale
  102948. * @param rigCameras defines cameras using this postprocess
  102949. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  102950. * @param engine defines hosting engine
  102951. * @param reusable defines if the postprocess will be reused multiple times per frame
  102952. */
  102953. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  102954. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  102955. _this._passedProcess = rigCameras[0]._rigPostProcess;
  102956. _this.onApplyObservable.add(function (effect) {
  102957. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  102958. });
  102959. return _this;
  102960. }
  102961. return AnaglyphPostProcess;
  102962. }(BABYLON.PostProcess));
  102963. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  102964. })(BABYLON || (BABYLON = {}));
  102965. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  102966. var BABYLON;
  102967. (function (BABYLON) {
  102968. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  102969. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102970. });
  102971. /**
  102972. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  102973. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102974. */
  102975. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  102976. __extends(AnaglyphArcRotateCamera, _super);
  102977. /**
  102978. * Creates a new AnaglyphArcRotateCamera
  102979. * @param name defines camera name
  102980. * @param alpha defines alpha angle (in radians)
  102981. * @param beta defines beta angle (in radians)
  102982. * @param radius defines radius
  102983. * @param target defines camera target
  102984. * @param interaxialDistance defines distance between each color axis
  102985. * @param scene defines the hosting scene
  102986. */
  102987. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  102988. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102989. _this.interaxialDistance = interaxialDistance;
  102990. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102991. return _this;
  102992. }
  102993. /**
  102994. * Gets camera class name
  102995. * @returns AnaglyphArcRotateCamera
  102996. */
  102997. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  102998. return "AnaglyphArcRotateCamera";
  102999. };
  103000. return AnaglyphArcRotateCamera;
  103001. }(BABYLON.ArcRotateCamera));
  103002. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  103003. })(BABYLON || (BABYLON = {}));
  103004. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  103005. var BABYLON;
  103006. (function (BABYLON) {
  103007. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  103008. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103009. });
  103010. /**
  103011. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  103012. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103013. */
  103014. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  103015. __extends(AnaglyphFreeCamera, _super);
  103016. /**
  103017. * Creates a new AnaglyphFreeCamera
  103018. * @param name defines camera name
  103019. * @param position defines initial position
  103020. * @param interaxialDistance defines distance between each color axis
  103021. * @param scene defines the hosting scene
  103022. */
  103023. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  103024. var _this = _super.call(this, name, position, scene) || this;
  103025. _this.interaxialDistance = interaxialDistance;
  103026. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103027. return _this;
  103028. }
  103029. /**
  103030. * Gets camera class name
  103031. * @returns AnaglyphFreeCamera
  103032. */
  103033. AnaglyphFreeCamera.prototype.getClassName = function () {
  103034. return "AnaglyphFreeCamera";
  103035. };
  103036. return AnaglyphFreeCamera;
  103037. }(BABYLON.FreeCamera));
  103038. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  103039. })(BABYLON || (BABYLON = {}));
  103040. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  103041. var BABYLON;
  103042. (function (BABYLON) {
  103043. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  103044. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103045. });
  103046. /**
  103047. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  103048. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103049. */
  103050. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  103051. __extends(AnaglyphGamepadCamera, _super);
  103052. /**
  103053. * Creates a new AnaglyphGamepadCamera
  103054. * @param name defines camera name
  103055. * @param position defines initial position
  103056. * @param interaxialDistance defines distance between each color axis
  103057. * @param scene defines the hosting scene
  103058. */
  103059. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  103060. var _this = _super.call(this, name, position, scene) || this;
  103061. _this.interaxialDistance = interaxialDistance;
  103062. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103063. return _this;
  103064. }
  103065. /**
  103066. * Gets camera class name
  103067. * @returns AnaglyphGamepadCamera
  103068. */
  103069. AnaglyphGamepadCamera.prototype.getClassName = function () {
  103070. return "AnaglyphGamepadCamera";
  103071. };
  103072. return AnaglyphGamepadCamera;
  103073. }(BABYLON.GamepadCamera));
  103074. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  103075. })(BABYLON || (BABYLON = {}));
  103076. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  103077. var BABYLON;
  103078. (function (BABYLON) {
  103079. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  103080. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103081. });
  103082. /**
  103083. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  103084. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103085. */
  103086. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  103087. __extends(AnaglyphUniversalCamera, _super);
  103088. /**
  103089. * Creates a new AnaglyphUniversalCamera
  103090. * @param name defines camera name
  103091. * @param position defines initial position
  103092. * @param interaxialDistance defines distance between each color axis
  103093. * @param scene defines the hosting scene
  103094. */
  103095. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  103096. var _this = _super.call(this, name, position, scene) || this;
  103097. _this.interaxialDistance = interaxialDistance;
  103098. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103099. return _this;
  103100. }
  103101. /**
  103102. * Gets camera class name
  103103. * @returns AnaglyphUniversalCamera
  103104. */
  103105. AnaglyphUniversalCamera.prototype.getClassName = function () {
  103106. return "AnaglyphUniversalCamera";
  103107. };
  103108. return AnaglyphUniversalCamera;
  103109. }(BABYLON.UniversalCamera));
  103110. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  103111. })(BABYLON || (BABYLON = {}));
  103112. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  103113. var BABYLON;
  103114. (function (BABYLON) {
  103115. /**
  103116. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  103117. */
  103118. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  103119. __extends(StereoscopicInterlacePostProcess, _super);
  103120. /**
  103121. * Initializes a StereoscopicInterlacePostProcess
  103122. * @param name The name of the effect.
  103123. * @param rigCameras The rig cameras to be appled to the post process
  103124. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  103125. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  103126. * @param engine The engine which the post process will be applied. (default: current engine)
  103127. * @param reusable If the post process can be reused on the same frame. (default: false)
  103128. */
  103129. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  103130. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  103131. _this._passedProcess = rigCameras[0]._rigPostProcess;
  103132. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  103133. _this.onSizeChangedObservable.add(function () {
  103134. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  103135. });
  103136. _this.onApplyObservable.add(function (effect) {
  103137. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  103138. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  103139. });
  103140. return _this;
  103141. }
  103142. return StereoscopicInterlacePostProcess;
  103143. }(BABYLON.PostProcess));
  103144. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  103145. })(BABYLON || (BABYLON = {}));
  103146. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  103147. var BABYLON;
  103148. (function (BABYLON) {
  103149. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  103150. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103151. });
  103152. /**
  103153. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  103154. * @see http://doc.babylonjs.com/features/cameras
  103155. */
  103156. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  103157. __extends(StereoscopicArcRotateCamera, _super);
  103158. /**
  103159. * Creates a new StereoscopicArcRotateCamera
  103160. * @param name defines camera name
  103161. * @param alpha defines alpha angle (in radians)
  103162. * @param beta defines beta angle (in radians)
  103163. * @param radius defines radius
  103164. * @param target defines camera target
  103165. * @param interaxialDistance defines distance between each color axis
  103166. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103167. * @param scene defines the hosting scene
  103168. */
  103169. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  103170. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  103171. _this.interaxialDistance = interaxialDistance;
  103172. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103173. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103174. return _this;
  103175. }
  103176. /**
  103177. * Gets camera class name
  103178. * @returns StereoscopicArcRotateCamera
  103179. */
  103180. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  103181. return "StereoscopicArcRotateCamera";
  103182. };
  103183. return StereoscopicArcRotateCamera;
  103184. }(BABYLON.ArcRotateCamera));
  103185. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  103186. })(BABYLON || (BABYLON = {}));
  103187. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  103188. var BABYLON;
  103189. (function (BABYLON) {
  103190. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  103191. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103192. });
  103193. /**
  103194. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  103195. * @see http://doc.babylonjs.com/features/cameras
  103196. */
  103197. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  103198. __extends(StereoscopicFreeCamera, _super);
  103199. /**
  103200. * Creates a new StereoscopicFreeCamera
  103201. * @param name defines camera name
  103202. * @param position defines initial position
  103203. * @param interaxialDistance defines distance between each color axis
  103204. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103205. * @param scene defines the hosting scene
  103206. */
  103207. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103208. var _this = _super.call(this, name, position, scene) || this;
  103209. _this.interaxialDistance = interaxialDistance;
  103210. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103211. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103212. return _this;
  103213. }
  103214. /**
  103215. * Gets camera class name
  103216. * @returns StereoscopicFreeCamera
  103217. */
  103218. StereoscopicFreeCamera.prototype.getClassName = function () {
  103219. return "StereoscopicFreeCamera";
  103220. };
  103221. return StereoscopicFreeCamera;
  103222. }(BABYLON.FreeCamera));
  103223. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  103224. })(BABYLON || (BABYLON = {}));
  103225. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  103226. var BABYLON;
  103227. (function (BABYLON) {
  103228. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  103229. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103230. });
  103231. /**
  103232. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  103233. * @see http://doc.babylonjs.com/features/cameras
  103234. */
  103235. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  103236. __extends(StereoscopicGamepadCamera, _super);
  103237. /**
  103238. * Creates a new StereoscopicGamepadCamera
  103239. * @param name defines camera name
  103240. * @param position defines initial position
  103241. * @param interaxialDistance defines distance between each color axis
  103242. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103243. * @param scene defines the hosting scene
  103244. */
  103245. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103246. var _this = _super.call(this, name, position, scene) || this;
  103247. _this.interaxialDistance = interaxialDistance;
  103248. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103249. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103250. return _this;
  103251. }
  103252. /**
  103253. * Gets camera class name
  103254. * @returns StereoscopicGamepadCamera
  103255. */
  103256. StereoscopicGamepadCamera.prototype.getClassName = function () {
  103257. return "StereoscopicGamepadCamera";
  103258. };
  103259. return StereoscopicGamepadCamera;
  103260. }(BABYLON.GamepadCamera));
  103261. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  103262. })(BABYLON || (BABYLON = {}));
  103263. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  103264. var BABYLON;
  103265. (function (BABYLON) {
  103266. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  103267. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103268. });
  103269. /**
  103270. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  103271. * @see http://doc.babylonjs.com/features/cameras
  103272. */
  103273. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  103274. __extends(StereoscopicUniversalCamera, _super);
  103275. /**
  103276. * Creates a new StereoscopicUniversalCamera
  103277. * @param name defines camera name
  103278. * @param position defines initial position
  103279. * @param interaxialDistance defines distance between each color axis
  103280. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103281. * @param scene defines the hosting scene
  103282. */
  103283. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103284. var _this = _super.call(this, name, position, scene) || this;
  103285. _this.interaxialDistance = interaxialDistance;
  103286. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103287. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103288. return _this;
  103289. }
  103290. /**
  103291. * Gets camera class name
  103292. * @returns StereoscopicUniversalCamera
  103293. */
  103294. StereoscopicUniversalCamera.prototype.getClassName = function () {
  103295. return "StereoscopicUniversalCamera";
  103296. };
  103297. return StereoscopicUniversalCamera;
  103298. }(BABYLON.UniversalCamera));
  103299. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  103300. })(BABYLON || (BABYLON = {}));
  103301. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  103302. var BABYLON;
  103303. (function (BABYLON) {
  103304. /**
  103305. * VRDistortionCorrectionPostProcess used for mobile VR
  103306. */
  103307. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  103308. __extends(VRDistortionCorrectionPostProcess, _super);
  103309. /**
  103310. * Initializes the VRDistortionCorrectionPostProcess
  103311. * @param name The name of the effect.
  103312. * @param camera The camera to apply the render pass to.
  103313. * @param isRightEye If this is for the right eye distortion
  103314. * @param vrMetrics All the required metrics for the VR camera
  103315. */
  103316. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  103317. var _this = _super.call(this, name, "vrDistortionCorrection", [
  103318. 'LensCenter',
  103319. 'Scale',
  103320. 'ScaleIn',
  103321. 'HmdWarpParam'
  103322. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  103323. _this._isRightEye = isRightEye;
  103324. _this._distortionFactors = vrMetrics.distortionK;
  103325. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  103326. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  103327. _this.adaptScaleToCurrentViewport = true;
  103328. _this.onSizeChangedObservable.add(function () {
  103329. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  103330. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  103331. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  103332. });
  103333. _this.onApplyObservable.add(function (effect) {
  103334. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  103335. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  103336. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  103337. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  103338. });
  103339. return _this;
  103340. }
  103341. return VRDistortionCorrectionPostProcess;
  103342. }(BABYLON.PostProcess));
  103343. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  103344. })(BABYLON || (BABYLON = {}));
  103345. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  103346. var BABYLON;
  103347. (function (BABYLON) {
  103348. /**
  103349. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  103350. * Screen rotation is taken into account.
  103351. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103352. */
  103353. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  103354. /**
  103355. * Instantiates a new input
  103356. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103357. */
  103358. function FreeCameraDeviceOrientationInput() {
  103359. var _this = this;
  103360. this._screenOrientationAngle = 0;
  103361. this._screenQuaternion = new BABYLON.Quaternion();
  103362. this._alpha = 0;
  103363. this._beta = 0;
  103364. this._gamma = 0;
  103365. this._orientationChanged = function () {
  103366. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  103367. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  103368. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  103369. };
  103370. this._deviceOrientation = function (evt) {
  103371. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  103372. _this._beta = evt.beta !== null ? evt.beta : 0;
  103373. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  103374. };
  103375. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  103376. this._orientationChanged();
  103377. }
  103378. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  103379. /**
  103380. * Define the camera controlled by the input.
  103381. */
  103382. get: function () {
  103383. return this._camera;
  103384. },
  103385. set: function (camera) {
  103386. this._camera = camera;
  103387. if (this._camera != null && !this._camera.rotationQuaternion) {
  103388. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  103389. }
  103390. },
  103391. enumerable: true,
  103392. configurable: true
  103393. });
  103394. /**
  103395. * Attach the input controls to a specific dom element to get the input from.
  103396. * @param element Defines the element the controls should be listened from
  103397. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103398. */
  103399. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103400. window.addEventListener("orientationchange", this._orientationChanged);
  103401. window.addEventListener("deviceorientation", this._deviceOrientation);
  103402. //In certain cases, the attach control is called AFTER orientation was changed,
  103403. //So this is needed.
  103404. this._orientationChanged();
  103405. };
  103406. /**
  103407. * Detach the current controls from the specified dom element.
  103408. * @param element Defines the element to stop listening the inputs from
  103409. */
  103410. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  103411. window.removeEventListener("orientationchange", this._orientationChanged);
  103412. window.removeEventListener("deviceorientation", this._deviceOrientation);
  103413. };
  103414. /**
  103415. * Update the current camera state depending on the inputs that have been used this frame.
  103416. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103417. */
  103418. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  103419. //if no device orientation provided, don't update the rotation.
  103420. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  103421. if (!this._alpha) {
  103422. return;
  103423. }
  103424. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  103425. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  103426. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  103427. //Mirror on XY Plane
  103428. this._camera.rotationQuaternion.z *= -1;
  103429. this._camera.rotationQuaternion.w *= -1;
  103430. };
  103431. /**
  103432. * Gets the class name of the current intput.
  103433. * @returns the class name
  103434. */
  103435. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  103436. return "FreeCameraDeviceOrientationInput";
  103437. };
  103438. /**
  103439. * Get the friendly name associated with the input class.
  103440. * @returns the input friendly name
  103441. */
  103442. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  103443. return "deviceOrientation";
  103444. };
  103445. return FreeCameraDeviceOrientationInput;
  103446. }());
  103447. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  103448. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  103449. })(BABYLON || (BABYLON = {}));
  103450. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  103451. var BABYLON;
  103452. (function (BABYLON) {
  103453. /**
  103454. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  103455. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103456. */
  103457. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  103458. /**
  103459. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  103460. */
  103461. function ArcRotateCameraVRDeviceOrientationInput() {
  103462. /**
  103463. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  103464. */
  103465. this.alphaCorrection = 1;
  103466. /**
  103467. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  103468. */
  103469. this.betaCorrection = 1;
  103470. /**
  103471. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  103472. */
  103473. this.gammaCorrection = 1;
  103474. this._alpha = 0;
  103475. this._gamma = 0;
  103476. this._dirty = false;
  103477. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  103478. }
  103479. /**
  103480. * Attach the input controls to a specific dom element to get the input from.
  103481. * @param element Defines the element the controls should be listened from
  103482. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103483. */
  103484. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103485. this.camera.attachControl(element, noPreventDefault);
  103486. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  103487. };
  103488. /** @hidden */
  103489. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  103490. if (evt.alpha !== null) {
  103491. this._alpha = +evt.alpha | 0;
  103492. }
  103493. if (evt.gamma !== null) {
  103494. this._gamma = +evt.gamma | 0;
  103495. }
  103496. this._dirty = true;
  103497. };
  103498. /**
  103499. * Update the current camera state depending on the inputs that have been used this frame.
  103500. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103501. */
  103502. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  103503. if (this._dirty) {
  103504. this._dirty = false;
  103505. if (this._gamma < 0) {
  103506. this._gamma = 180 + this._gamma;
  103507. }
  103508. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  103509. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  103510. }
  103511. };
  103512. /**
  103513. * Detach the current controls from the specified dom element.
  103514. * @param element Defines the element to stop listening the inputs from
  103515. */
  103516. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  103517. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  103518. };
  103519. /**
  103520. * Gets the class name of the current intput.
  103521. * @returns the class name
  103522. */
  103523. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  103524. return "ArcRotateCameraVRDeviceOrientationInput";
  103525. };
  103526. /**
  103527. * Get the friendly name associated with the input class.
  103528. * @returns the input friendly name
  103529. */
  103530. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  103531. return "VRDeviceOrientation";
  103532. };
  103533. return ArcRotateCameraVRDeviceOrientationInput;
  103534. }());
  103535. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  103536. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  103537. })(BABYLON || (BABYLON = {}));
  103538. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  103539. var BABYLON;
  103540. (function (BABYLON) {
  103541. /**
  103542. * This represents all the required metrics to create a VR camera.
  103543. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  103544. */
  103545. var VRCameraMetrics = /** @class */ (function () {
  103546. function VRCameraMetrics() {
  103547. /**
  103548. * Define if the current vr camera should compensate the distortion of the lense or not.
  103549. */
  103550. this.compensateDistortion = true;
  103551. }
  103552. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  103553. /**
  103554. * Gets the rendering aspect ratio based on the provided resolutions.
  103555. */
  103556. get: function () {
  103557. return this.hResolution / (2 * this.vResolution);
  103558. },
  103559. enumerable: true,
  103560. configurable: true
  103561. });
  103562. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  103563. /**
  103564. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  103565. */
  103566. get: function () {
  103567. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  103568. },
  103569. enumerable: true,
  103570. configurable: true
  103571. });
  103572. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  103573. /**
  103574. * @hidden
  103575. */
  103576. get: function () {
  103577. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103578. var h = (4 * meters) / this.hScreenSize;
  103579. return BABYLON.Matrix.Translation(h, 0, 0);
  103580. },
  103581. enumerable: true,
  103582. configurable: true
  103583. });
  103584. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  103585. /**
  103586. * @hidden
  103587. */
  103588. get: function () {
  103589. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103590. var h = (4 * meters) / this.hScreenSize;
  103591. return BABYLON.Matrix.Translation(-h, 0, 0);
  103592. },
  103593. enumerable: true,
  103594. configurable: true
  103595. });
  103596. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  103597. /**
  103598. * @hidden
  103599. */
  103600. get: function () {
  103601. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  103602. },
  103603. enumerable: true,
  103604. configurable: true
  103605. });
  103606. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  103607. /**
  103608. * @hidden
  103609. */
  103610. get: function () {
  103611. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  103612. },
  103613. enumerable: true,
  103614. configurable: true
  103615. });
  103616. /**
  103617. * Get the default VRMetrics based on the most generic setup.
  103618. * @returns the default vr metrics
  103619. */
  103620. VRCameraMetrics.GetDefault = function () {
  103621. var result = new VRCameraMetrics();
  103622. result.hResolution = 1280;
  103623. result.vResolution = 800;
  103624. result.hScreenSize = 0.149759993;
  103625. result.vScreenSize = 0.0935999975;
  103626. result.vScreenCenter = 0.0467999987;
  103627. result.eyeToScreenDistance = 0.0410000011;
  103628. result.lensSeparationDistance = 0.0635000020;
  103629. result.interpupillaryDistance = 0.0640000030;
  103630. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  103631. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  103632. result.postProcessScaleFactor = 1.714605507808412;
  103633. result.lensCenterOffset = 0.151976421;
  103634. return result;
  103635. };
  103636. return VRCameraMetrics;
  103637. }());
  103638. BABYLON.VRCameraMetrics = VRCameraMetrics;
  103639. })(BABYLON || (BABYLON = {}));
  103640. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  103641. var BABYLON;
  103642. (function (BABYLON) {
  103643. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  103644. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103645. });
  103646. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  103647. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103648. });
  103649. /**
  103650. * This represents a WebVR camera.
  103651. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  103652. * @example http://doc.babylonjs.com/how_to/webvr_camera
  103653. */
  103654. var WebVRFreeCamera = /** @class */ (function (_super) {
  103655. __extends(WebVRFreeCamera, _super);
  103656. /**
  103657. * Instantiates a WebVRFreeCamera.
  103658. * @param name The name of the WebVRFreeCamera
  103659. * @param position The starting anchor position for the camera
  103660. * @param scene The scene the camera belongs to
  103661. * @param webVROptions a set of customizable options for the webVRCamera
  103662. */
  103663. function WebVRFreeCamera(name, position, scene, webVROptions) {
  103664. if (webVROptions === void 0) { webVROptions = {}; }
  103665. var _this = _super.call(this, name, position, scene) || this;
  103666. _this.webVROptions = webVROptions;
  103667. /**
  103668. * @hidden
  103669. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  103670. */
  103671. _this._vrDevice = null;
  103672. /**
  103673. * The rawPose of the vrDevice.
  103674. */
  103675. _this.rawPose = null;
  103676. _this._specsVersion = "1.1";
  103677. _this._attached = false;
  103678. _this._descendants = [];
  103679. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  103680. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  103681. /** @hidden */
  103682. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  103683. _this._standingMatrix = null;
  103684. /**
  103685. * Represents device position in babylon space.
  103686. */
  103687. _this.devicePosition = BABYLON.Vector3.Zero();
  103688. /**
  103689. * Represents device rotation in babylon space.
  103690. */
  103691. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  103692. /**
  103693. * The scale of the device to be used when translating from device space to babylon space.
  103694. */
  103695. _this.deviceScaleFactor = 1;
  103696. _this._deviceToWorld = BABYLON.Matrix.Identity();
  103697. _this._worldToDevice = BABYLON.Matrix.Identity();
  103698. /**
  103699. * References to the webVR controllers for the vrDevice.
  103700. */
  103701. _this.controllers = [];
  103702. /**
  103703. * Emits an event when a controller is attached.
  103704. */
  103705. _this.onControllersAttachedObservable = new BABYLON.Observable();
  103706. /**
  103707. * Emits an event when a controller's mesh has been loaded;
  103708. */
  103709. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  103710. /**
  103711. * Emits an event when the HMD's pose has been updated.
  103712. */
  103713. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  103714. _this._poseSet = false;
  103715. /**
  103716. * If the rig cameras be used as parent instead of this camera.
  103717. */
  103718. _this.rigParenting = true;
  103719. _this._defaultHeight = undefined;
  103720. _this._htmlElementAttached = null;
  103721. _this._detachIfAttached = function () {
  103722. var vrDisplay = _this.getEngine().getVRDevice();
  103723. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  103724. _this.detachControl(_this._htmlElementAttached);
  103725. }
  103726. };
  103727. _this._workingVector = BABYLON.Vector3.Zero();
  103728. _this._oneVector = BABYLON.Vector3.One();
  103729. _this._workingMatrix = BABYLON.Matrix.Identity();
  103730. _this._tmpMatrix = new BABYLON.Matrix();
  103731. _this._cache.position = BABYLON.Vector3.Zero();
  103732. if (webVROptions.defaultHeight) {
  103733. _this._defaultHeight = webVROptions.defaultHeight;
  103734. _this.position.y = _this._defaultHeight;
  103735. }
  103736. _this.minZ = 0.1;
  103737. //legacy support - the compensation boolean was removed.
  103738. if (arguments.length === 5) {
  103739. _this.webVROptions = arguments[4];
  103740. }
  103741. // default webVR options
  103742. if (_this.webVROptions.trackPosition == undefined) {
  103743. _this.webVROptions.trackPosition = true;
  103744. }
  103745. if (_this.webVROptions.controllerMeshes == undefined) {
  103746. _this.webVROptions.controllerMeshes = true;
  103747. }
  103748. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  103749. _this.webVROptions.defaultLightingOnControllers = true;
  103750. }
  103751. _this.rotationQuaternion = new BABYLON.Quaternion();
  103752. if (_this.webVROptions && _this.webVROptions.positionScale) {
  103753. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  103754. }
  103755. //enable VR
  103756. var engine = _this.getEngine();
  103757. _this._onVREnabled = function (success) { if (success) {
  103758. _this.initControllers();
  103759. } };
  103760. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  103761. engine.initWebVR().add(function (event) {
  103762. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  103763. return;
  103764. }
  103765. _this._vrDevice = event.vrDisplay;
  103766. //reset the rig parameters.
  103767. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  103768. if (_this._attached) {
  103769. _this.getEngine().enableVR();
  103770. }
  103771. });
  103772. if (typeof (VRFrameData) !== "undefined") {
  103773. _this._frameData = new VRFrameData();
  103774. }
  103775. /**
  103776. * The idea behind the following lines:
  103777. * objects that have the camera as parent should actually have the rig cameras as a parent.
  103778. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  103779. * the second will not show it correctly.
  103780. *
  103781. * To solve this - each object that has the camera as parent will be added to a protected array.
  103782. * When the rig camera renders, it will take this array and set all of those to be its children.
  103783. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  103784. * Amazing!
  103785. */
  103786. scene.onBeforeCameraRenderObservable.add(function (camera) {
  103787. if (camera.parent === _this && _this.rigParenting) {
  103788. _this._descendants = _this.getDescendants(true, function (n) {
  103789. // don't take the cameras or the controllers!
  103790. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  103791. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  103792. return !isController && !isRigCamera;
  103793. });
  103794. _this._descendants.forEach(function (node) {
  103795. node.parent = camera;
  103796. });
  103797. }
  103798. });
  103799. scene.onAfterCameraRenderObservable.add(function (camera) {
  103800. if (camera.parent === _this && _this.rigParenting) {
  103801. _this._descendants.forEach(function (node) {
  103802. node.parent = _this;
  103803. });
  103804. }
  103805. });
  103806. return _this;
  103807. }
  103808. /**
  103809. * Gets the device distance from the ground in meters.
  103810. * @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.
  103811. */
  103812. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  103813. if (this._standingMatrix) {
  103814. // Add standing matrix offset to get real offset from ground in room
  103815. this._standingMatrix.getTranslationToRef(this._workingVector);
  103816. return this._deviceRoomPosition.y + this._workingVector.y;
  103817. }
  103818. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  103819. return this._defaultHeight || 0;
  103820. };
  103821. /**
  103822. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103823. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  103824. */
  103825. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  103826. var _this = this;
  103827. if (callback === void 0) { callback = function (bool) { }; }
  103828. // Use standing matrix if available
  103829. this.getEngine().initWebVRAsync().then(function (result) {
  103830. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  103831. callback(false);
  103832. }
  103833. else {
  103834. _this._standingMatrix = new BABYLON.Matrix();
  103835. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  103836. if (!_this.getScene().useRightHandedSystem) {
  103837. [2, 6, 8, 9, 14].forEach(function (num) {
  103838. if (_this._standingMatrix) {
  103839. _this._standingMatrix.m[num] *= -1;
  103840. }
  103841. });
  103842. }
  103843. callback(true);
  103844. }
  103845. });
  103846. };
  103847. /**
  103848. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103849. * @returns A promise with a boolean set to if the standing matrix is supported.
  103850. */
  103851. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  103852. var _this = this;
  103853. return new Promise(function (res, rej) {
  103854. _this.useStandingMatrix(function (supported) {
  103855. res(supported);
  103856. });
  103857. });
  103858. };
  103859. /**
  103860. * Disposes the camera
  103861. */
  103862. WebVRFreeCamera.prototype.dispose = function () {
  103863. this._detachIfAttached();
  103864. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  103865. if (this._updateCacheWhenTrackingDisabledObserver) {
  103866. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  103867. }
  103868. _super.prototype.dispose.call(this);
  103869. };
  103870. /**
  103871. * Gets a vrController by name.
  103872. * @param name The name of the controller to retreive
  103873. * @returns the controller matching the name specified or null if not found
  103874. */
  103875. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  103876. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  103877. var gp = _a[_i];
  103878. if (gp.hand === name) {
  103879. return gp;
  103880. }
  103881. }
  103882. return null;
  103883. };
  103884. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  103885. /**
  103886. * The controller corrisponding to the users left hand.
  103887. */
  103888. get: function () {
  103889. if (!this._leftController) {
  103890. this._leftController = this.getControllerByName("left");
  103891. }
  103892. return this._leftController;
  103893. },
  103894. enumerable: true,
  103895. configurable: true
  103896. });
  103897. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  103898. /**
  103899. * The controller corrisponding to the users right hand.
  103900. */
  103901. get: function () {
  103902. if (!this._rightController) {
  103903. this._rightController = this.getControllerByName("right");
  103904. }
  103905. return this._rightController;
  103906. },
  103907. enumerable: true,
  103908. configurable: true
  103909. });
  103910. /**
  103911. * Casts a ray forward from the vrCamera's gaze.
  103912. * @param length Length of the ray (default: 100)
  103913. * @returns the ray corrisponding to the gaze
  103914. */
  103915. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  103916. if (length === void 0) { length = 100; }
  103917. if (this.leftCamera) {
  103918. // Use left eye to avoid computation to compute center on every call
  103919. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  103920. }
  103921. else {
  103922. return _super.prototype.getForwardRay.call(this, length);
  103923. }
  103924. };
  103925. /**
  103926. * @hidden
  103927. * Updates the camera based on device's frame data
  103928. */
  103929. WebVRFreeCamera.prototype._checkInputs = function () {
  103930. if (this._vrDevice && this._vrDevice.isPresenting) {
  103931. this._vrDevice.getFrameData(this._frameData);
  103932. this.updateFromDevice(this._frameData.pose);
  103933. }
  103934. _super.prototype._checkInputs.call(this);
  103935. };
  103936. /**
  103937. * Updates the poseControlled values based on the input device pose.
  103938. * @param poseData Pose coming from the device
  103939. */
  103940. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  103941. if (poseData && poseData.orientation) {
  103942. this.rawPose = poseData;
  103943. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  103944. if (this.getScene().useRightHandedSystem) {
  103945. this._deviceRoomRotationQuaternion.z *= -1;
  103946. this._deviceRoomRotationQuaternion.w *= -1;
  103947. }
  103948. if (this.webVROptions.trackPosition && this.rawPose.position) {
  103949. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  103950. if (this.getScene().useRightHandedSystem) {
  103951. this._deviceRoomPosition.z *= -1;
  103952. }
  103953. }
  103954. this._poseSet = true;
  103955. }
  103956. };
  103957. /**
  103958. * WebVR's attach control will start broadcasting frames to the device.
  103959. * Note that in certain browsers (chrome for example) this function must be called
  103960. * within a user-interaction callback. Example:
  103961. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  103962. *
  103963. * @param element html element to attach the vrDevice to
  103964. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  103965. */
  103966. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  103967. _super.prototype.attachControl.call(this, element, noPreventDefault);
  103968. this._attached = true;
  103969. this._htmlElementAttached = element;
  103970. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  103971. if (this._vrDevice) {
  103972. this.getEngine().enableVR();
  103973. }
  103974. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  103975. };
  103976. /**
  103977. * Detaches the camera from the html element and disables VR
  103978. *
  103979. * @param element html element to detach from
  103980. */
  103981. WebVRFreeCamera.prototype.detachControl = function (element) {
  103982. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  103983. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  103984. _super.prototype.detachControl.call(this, element);
  103985. this._attached = false;
  103986. this.getEngine().disableVR();
  103987. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  103988. };
  103989. /**
  103990. * @returns the name of this class
  103991. */
  103992. WebVRFreeCamera.prototype.getClassName = function () {
  103993. return "WebVRFreeCamera";
  103994. };
  103995. /**
  103996. * Calls resetPose on the vrDisplay
  103997. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  103998. */
  103999. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  104000. //uses the vrDisplay's "resetPose()".
  104001. //pitch and roll won't be affected.
  104002. this._vrDevice.resetPose();
  104003. };
  104004. /**
  104005. * @hidden
  104006. * Updates the rig cameras (left and right eye)
  104007. */
  104008. WebVRFreeCamera.prototype._updateRigCameras = function () {
  104009. var camLeft = this._rigCameras[0];
  104010. var camRight = this._rigCameras[1];
  104011. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  104012. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  104013. camLeft.position.copyFrom(this._deviceRoomPosition);
  104014. camRight.position.copyFrom(this._deviceRoomPosition);
  104015. };
  104016. // Remove translation from 6dof headset if trackposition is set to false
  104017. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  104018. if (isViewMatrix === void 0) { isViewMatrix = false; }
  104019. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  104020. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  104021. if (!isViewMatrix) {
  104022. this._tmpMatrix.invert();
  104023. }
  104024. this._tmpMatrix.multiplyToRef(matrix, matrix);
  104025. }
  104026. };
  104027. /**
  104028. * @hidden
  104029. * Updates the cached values of the camera
  104030. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  104031. */
  104032. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  104033. var _this = this;
  104034. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  104035. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  104036. if (!this.updateCacheCalled) {
  104037. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  104038. this.updateCacheCalled = true;
  104039. this.update();
  104040. }
  104041. // Set working vector to the device position in room space rotated by the new rotation
  104042. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  104043. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  104044. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  104045. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  104046. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  104047. // Add translation from anchor position
  104048. this._deviceToWorld.getTranslationToRef(this._workingVector);
  104049. this._workingVector.addInPlace(this.position);
  104050. this._workingVector.subtractInPlace(this._cache.position);
  104051. this._deviceToWorld.setTranslation(this._workingVector);
  104052. // Set an inverted matrix to be used when updating the camera
  104053. this._deviceToWorld.invertToRef(this._worldToDevice);
  104054. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  104055. this.controllers.forEach(function (controller) {
  104056. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  104057. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  104058. controller.update();
  104059. });
  104060. }
  104061. if (!ignoreParentClass) {
  104062. _super.prototype._updateCache.call(this);
  104063. }
  104064. this.updateCacheCalled = false;
  104065. };
  104066. /**
  104067. * @hidden
  104068. * Get current device position in babylon world
  104069. */
  104070. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  104071. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  104072. };
  104073. /**
  104074. * Updates the current device position and rotation in the babylon world
  104075. */
  104076. WebVRFreeCamera.prototype.update = function () {
  104077. this._computeDevicePosition();
  104078. // Get current device rotation in babylon world
  104079. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  104080. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  104081. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  104082. if (this._poseSet) {
  104083. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  104084. }
  104085. _super.prototype.update.call(this);
  104086. };
  104087. /**
  104088. * @hidden
  104089. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  104090. * @returns an identity matrix
  104091. */
  104092. WebVRFreeCamera.prototype._getViewMatrix = function () {
  104093. return BABYLON.Matrix.Identity();
  104094. };
  104095. /**
  104096. * This function is called by the two RIG cameras.
  104097. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  104098. */
  104099. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  104100. var _this = this;
  104101. // Update the parent camera prior to using a child camera to avoid desynchronization
  104102. var parentCamera = this._cameraRigParams["parentCamera"];
  104103. parentCamera._updateCache();
  104104. //WebVR 1.1
  104105. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  104106. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  104107. if (!this.getScene().useRightHandedSystem) {
  104108. [2, 6, 8, 9, 14].forEach(function (num) {
  104109. _this._webvrViewMatrix.m[num] *= -1;
  104110. });
  104111. }
  104112. // update the camera rotation matrix
  104113. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  104114. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  104115. // Computing target and final matrix
  104116. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  104117. // should the view matrix be updated with scale and position offset?
  104118. if (parentCamera.deviceScaleFactor !== 1) {
  104119. this._webvrViewMatrix.invert();
  104120. // scale the position, if set
  104121. if (parentCamera.deviceScaleFactor) {
  104122. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  104123. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  104124. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  104125. }
  104126. this._webvrViewMatrix.invert();
  104127. }
  104128. // Remove translation from 6dof headset if trackposition is set to false
  104129. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  104130. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  104131. // Compute global position
  104132. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  104133. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  104134. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  104135. this._workingMatrix.getTranslationToRef(this._globalPosition);
  104136. this._markSyncedWithParent();
  104137. return this._webvrViewMatrix;
  104138. };
  104139. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  104140. var _this = this;
  104141. var parentCamera = this.parent;
  104142. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  104143. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  104144. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  104145. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  104146. //babylon compatible matrix
  104147. if (!this.getScene().useRightHandedSystem) {
  104148. [8, 9, 10, 11].forEach(function (num) {
  104149. _this._projectionMatrix.m[num] *= -1;
  104150. });
  104151. }
  104152. return this._projectionMatrix;
  104153. };
  104154. /**
  104155. * Initializes the controllers and their meshes
  104156. */
  104157. WebVRFreeCamera.prototype.initControllers = function () {
  104158. var _this = this;
  104159. this.controllers = [];
  104160. var manager = this.getScene().gamepadManager;
  104161. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  104162. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  104163. var webVrController = gamepad;
  104164. if (webVrController.defaultModel) {
  104165. webVrController.defaultModel.setEnabled(false);
  104166. }
  104167. if (webVrController.hand === "right") {
  104168. _this._rightController = null;
  104169. }
  104170. if (webVrController.hand === "left") {
  104171. _this._leftController = null;
  104172. }
  104173. var controllerIndex = _this.controllers.indexOf(webVrController);
  104174. if (controllerIndex !== -1) {
  104175. _this.controllers.splice(controllerIndex, 1);
  104176. }
  104177. }
  104178. });
  104179. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  104180. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  104181. var webVrController_1 = gamepad;
  104182. if (!_this.webVROptions.trackPosition) {
  104183. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  104184. // Cache must be updated before rendering controllers to avoid them being one frame behind
  104185. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  104186. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  104187. _this._updateCache();
  104188. });
  104189. }
  104190. }
  104191. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  104192. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  104193. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  104194. if (_this.webVROptions.controllerMeshes) {
  104195. if (webVrController_1.defaultModel) {
  104196. webVrController_1.defaultModel.setEnabled(true);
  104197. }
  104198. else {
  104199. // Load the meshes
  104200. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  104201. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  104202. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  104203. if (_this.webVROptions.defaultLightingOnControllers) {
  104204. if (!_this._lightOnControllers) {
  104205. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  104206. }
  104207. var activateLightOnSubMeshes_1 = function (mesh, light) {
  104208. var children = mesh.getChildren();
  104209. if (children && children.length !== 0) {
  104210. children.forEach(function (mesh) {
  104211. light.includedOnlyMeshes.push(mesh);
  104212. activateLightOnSubMeshes_1(mesh, light);
  104213. });
  104214. }
  104215. };
  104216. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  104217. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  104218. }
  104219. });
  104220. }
  104221. }
  104222. webVrController_1.attachToPoseControlledCamera(_this);
  104223. // since this is async - sanity check. Is the controller already stored?
  104224. if (_this.controllers.indexOf(webVrController_1) === -1) {
  104225. //add to the controllers array
  104226. _this.controllers.push(webVrController_1);
  104227. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  104228. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  104229. // So we're overriding setting left & right manually to be sure
  104230. var firstViveWandDetected = false;
  104231. for (var i = 0; i < _this.controllers.length; i++) {
  104232. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  104233. if (!firstViveWandDetected) {
  104234. firstViveWandDetected = true;
  104235. _this.controllers[i].hand = "left";
  104236. }
  104237. else {
  104238. _this.controllers[i].hand = "right";
  104239. }
  104240. }
  104241. }
  104242. //did we find enough controllers? Great! let the developer know.
  104243. if (_this.controllers.length >= 2) {
  104244. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  104245. }
  104246. }
  104247. }
  104248. });
  104249. };
  104250. return WebVRFreeCamera;
  104251. }(BABYLON.FreeCamera));
  104252. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  104253. })(BABYLON || (BABYLON = {}));
  104254. //# sourceMappingURL=babylon.webVRCamera.js.map
  104255. var BABYLON;
  104256. (function (BABYLON) {
  104257. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  104258. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  104259. });
  104260. // We're mainly based on the logic defined into the FreeCamera code
  104261. /**
  104262. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  104263. * being tilted forward or back and left or right.
  104264. */
  104265. var DeviceOrientationCamera = /** @class */ (function (_super) {
  104266. __extends(DeviceOrientationCamera, _super);
  104267. /**
  104268. * Creates a new device orientation camera
  104269. * @param name The name of the camera
  104270. * @param position The start position camera
  104271. * @param scene The scene the camera belongs to
  104272. */
  104273. function DeviceOrientationCamera(name, position, scene) {
  104274. var _this = _super.call(this, name, position, scene) || this;
  104275. _this._quaternionCache = new BABYLON.Quaternion();
  104276. _this.inputs.addDeviceOrientation();
  104277. return _this;
  104278. }
  104279. /**
  104280. * Gets the current instance class name ("DeviceOrientationCamera").
  104281. * This helps avoiding instanceof at run time.
  104282. * @returns the class name
  104283. */
  104284. DeviceOrientationCamera.prototype.getClassName = function () {
  104285. return "DeviceOrientationCamera";
  104286. };
  104287. /**
  104288. * @hidden
  104289. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  104290. */
  104291. DeviceOrientationCamera.prototype._checkInputs = function () {
  104292. _super.prototype._checkInputs.call(this);
  104293. this._quaternionCache.copyFrom(this.rotationQuaternion);
  104294. if (this._initialQuaternion) {
  104295. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104296. }
  104297. };
  104298. /**
  104299. * Reset the camera to its default orientation on the specified axis only.
  104300. * @param axis The axis to reset
  104301. */
  104302. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  104303. var _this = this;
  104304. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  104305. //can only work if this camera has a rotation quaternion already.
  104306. if (!this.rotationQuaternion) {
  104307. return;
  104308. }
  104309. if (!this._initialQuaternion) {
  104310. this._initialQuaternion = new BABYLON.Quaternion();
  104311. }
  104312. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  104313. ['x', 'y', 'z'].forEach(function (axisName) {
  104314. if (!axis[axisName]) {
  104315. _this._initialQuaternion[axisName] = 0;
  104316. }
  104317. else {
  104318. _this._initialQuaternion[axisName] *= -1;
  104319. }
  104320. });
  104321. this._initialQuaternion.normalize();
  104322. //force rotation update
  104323. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104324. };
  104325. return DeviceOrientationCamera;
  104326. }(BABYLON.FreeCamera));
  104327. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  104328. })(BABYLON || (BABYLON = {}));
  104329. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  104330. var BABYLON;
  104331. (function (BABYLON) {
  104332. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104333. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104334. });
  104335. /**
  104336. * Camera used to simulate VR rendering (based on FreeCamera)
  104337. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104338. */
  104339. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  104340. __extends(VRDeviceOrientationFreeCamera, _super);
  104341. /**
  104342. * Creates a new VRDeviceOrientationFreeCamera
  104343. * @param name defines camera name
  104344. * @param position defines the start position of the camera
  104345. * @param scene defines the scene the camera belongs to
  104346. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104347. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104348. */
  104349. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104350. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104351. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104352. var _this = _super.call(this, name, position, scene) || this;
  104353. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104354. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104355. return _this;
  104356. }
  104357. /**
  104358. * Gets camera class name
  104359. * @returns VRDeviceOrientationFreeCamera
  104360. */
  104361. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  104362. return "VRDeviceOrientationFreeCamera";
  104363. };
  104364. return VRDeviceOrientationFreeCamera;
  104365. }(BABYLON.DeviceOrientationCamera));
  104366. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  104367. })(BABYLON || (BABYLON = {}));
  104368. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  104369. var BABYLON;
  104370. (function (BABYLON) {
  104371. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104372. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  104373. });
  104374. /**
  104375. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  104376. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104377. */
  104378. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  104379. __extends(VRDeviceOrientationArcRotateCamera, _super);
  104380. /**
  104381. * Creates a new VRDeviceOrientationArcRotateCamera
  104382. * @param name defines camera name
  104383. * @param alpha defines the camera rotation along the logitudinal axis
  104384. * @param beta defines the camera rotation along the latitudinal axis
  104385. * @param radius defines the camera distance from its target
  104386. * @param target defines the camera target
  104387. * @param scene defines the scene the camera belongs to
  104388. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104389. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104390. */
  104391. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  104392. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104393. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104394. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104395. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104396. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104397. _this.inputs.addVRDeviceOrientation();
  104398. return _this;
  104399. }
  104400. /**
  104401. * Gets camera class name
  104402. * @returns VRDeviceOrientationArcRotateCamera
  104403. */
  104404. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  104405. return "VRDeviceOrientationArcRotateCamera";
  104406. };
  104407. return VRDeviceOrientationArcRotateCamera;
  104408. }(BABYLON.ArcRotateCamera));
  104409. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  104410. })(BABYLON || (BABYLON = {}));
  104411. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  104412. var BABYLON;
  104413. (function (BABYLON) {
  104414. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  104415. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  104416. });
  104417. /**
  104418. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  104419. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104420. */
  104421. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  104422. __extends(VRDeviceOrientationGamepadCamera, _super);
  104423. /**
  104424. * Creates a new VRDeviceOrientationGamepadCamera
  104425. * @param name defines camera name
  104426. * @param position defines the start position of the camera
  104427. * @param scene defines the scene the camera belongs to
  104428. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104429. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104430. */
  104431. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104432. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104433. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104434. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  104435. _this.inputs.addGamepad();
  104436. return _this;
  104437. }
  104438. /**
  104439. * Gets camera class name
  104440. * @returns VRDeviceOrientationGamepadCamera
  104441. */
  104442. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  104443. return "VRDeviceOrientationGamepadCamera";
  104444. };
  104445. return VRDeviceOrientationGamepadCamera;
  104446. }(BABYLON.VRDeviceOrientationFreeCamera));
  104447. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  104448. })(BABYLON || (BABYLON = {}));
  104449. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  104450. var BABYLON;
  104451. (function (BABYLON) {
  104452. var VRExperienceHelperGazer = /** @class */ (function () {
  104453. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  104454. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  104455. this.scene = scene;
  104456. /** @hidden */
  104457. this._pointerDownOnMeshAsked = false;
  104458. /** @hidden */
  104459. this._isActionableMesh = false;
  104460. /** @hidden */
  104461. this._teleportationRequestInitiated = false;
  104462. /** @hidden */
  104463. this._teleportationBackRequestInitiated = false;
  104464. /** @hidden */
  104465. this._rotationRightAsked = false;
  104466. /** @hidden */
  104467. this._rotationLeftAsked = false;
  104468. /** @hidden */
  104469. this._dpadPressed = true;
  104470. /** @hidden */
  104471. this._activePointer = false;
  104472. this._id = VRExperienceHelperGazer._idCounter++;
  104473. // Gaze tracker
  104474. if (!gazeTrackerToClone) {
  104475. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  104476. this._gazeTracker.bakeCurrentTransformIntoVertices();
  104477. this._gazeTracker.isPickable = false;
  104478. this._gazeTracker.isVisible = false;
  104479. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  104480. targetMat.specularColor = BABYLON.Color3.Black();
  104481. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104482. targetMat.backFaceCulling = false;
  104483. this._gazeTracker.material = targetMat;
  104484. }
  104485. else {
  104486. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  104487. }
  104488. }
  104489. /** @hidden */
  104490. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  104491. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  104492. };
  104493. /** @hidden */
  104494. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  104495. this._pointerDownOnMeshAsked = true;
  104496. if (this._currentHit) {
  104497. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  104498. }
  104499. };
  104500. /** @hidden */
  104501. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  104502. if (this._currentHit) {
  104503. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  104504. }
  104505. this._pointerDownOnMeshAsked = false;
  104506. };
  104507. /** @hidden */
  104508. VRExperienceHelperGazer.prototype._activatePointer = function () {
  104509. this._activePointer = true;
  104510. };
  104511. /** @hidden */
  104512. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  104513. this._activePointer = false;
  104514. };
  104515. /** @hidden */
  104516. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  104517. if (distance === void 0) { distance = 100; }
  104518. };
  104519. VRExperienceHelperGazer.prototype.dispose = function () {
  104520. this._interactionsEnabled = false;
  104521. this._teleportationEnabled = false;
  104522. if (this._gazeTracker) {
  104523. this._gazeTracker.dispose();
  104524. }
  104525. };
  104526. VRExperienceHelperGazer._idCounter = 0;
  104527. return VRExperienceHelperGazer;
  104528. }());
  104529. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  104530. __extends(VRExperienceHelperControllerGazer, _super);
  104531. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  104532. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  104533. _this.webVRController = webVRController;
  104534. // Laser pointer
  104535. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  104536. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  104537. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104538. laserPointerMaterial.alpha = 0.6;
  104539. _this._laserPointer.material = laserPointerMaterial;
  104540. _this._laserPointer.rotation.x = Math.PI / 2;
  104541. _this._laserPointer.position.z = -0.5;
  104542. _this._laserPointer.isVisible = false;
  104543. _this._laserPointer.isPickable = false;
  104544. if (!webVRController.mesh) {
  104545. // Create an empty mesh that is used prior to loading the high quality model
  104546. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  104547. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  104548. preloadPointerPose.rotation.x = -0.7;
  104549. preloadMesh.addChild(preloadPointerPose);
  104550. webVRController.attachToMesh(preloadMesh);
  104551. }
  104552. _this._setLaserPointerParent(webVRController.mesh);
  104553. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  104554. _this._setLaserPointerParent(mesh);
  104555. });
  104556. return _this;
  104557. }
  104558. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  104559. return this.webVRController.getForwardRay(length);
  104560. };
  104561. /** @hidden */
  104562. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  104563. _super.prototype._activatePointer.call(this);
  104564. this._laserPointer.isVisible = true;
  104565. };
  104566. /** @hidden */
  104567. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  104568. _super.prototype._deactivatePointer.call(this);
  104569. this._laserPointer.isVisible = false;
  104570. };
  104571. /** @hidden */
  104572. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  104573. this._laserPointer.material.emissiveColor = color;
  104574. };
  104575. /** @hidden */
  104576. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  104577. var makeNotPick = function (root) {
  104578. root.isPickable = false;
  104579. root.getChildMeshes().forEach(function (c) {
  104580. makeNotPick(c);
  104581. });
  104582. };
  104583. makeNotPick(mesh);
  104584. var childMeshes = mesh.getChildMeshes();
  104585. this.webVRController._pointingPoseNode = null;
  104586. for (var i = 0; i < childMeshes.length; i++) {
  104587. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  104588. mesh = childMeshes[i];
  104589. this.webVRController._pointingPoseNode = mesh;
  104590. break;
  104591. }
  104592. }
  104593. this._laserPointer.parent = mesh;
  104594. };
  104595. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  104596. if (distance === void 0) { distance = 100; }
  104597. this._laserPointer.scaling.y = distance;
  104598. this._laserPointer.position.z = -distance / 2;
  104599. };
  104600. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  104601. _super.prototype.dispose.call(this);
  104602. this._laserPointer.dispose();
  104603. if (this._meshAttachedObserver) {
  104604. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  104605. }
  104606. };
  104607. return VRExperienceHelperControllerGazer;
  104608. }(VRExperienceHelperGazer));
  104609. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  104610. __extends(VRExperienceHelperCameraGazer, _super);
  104611. function VRExperienceHelperCameraGazer(getCamera, scene) {
  104612. var _this = _super.call(this, scene) || this;
  104613. _this.getCamera = getCamera;
  104614. return _this;
  104615. }
  104616. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  104617. var camera = this.getCamera();
  104618. if (camera) {
  104619. return camera.getForwardRay(length);
  104620. }
  104621. else {
  104622. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  104623. }
  104624. };
  104625. return VRExperienceHelperCameraGazer;
  104626. }(VRExperienceHelperGazer));
  104627. /**
  104628. * Helps to quickly add VR support to an existing scene.
  104629. * See http://doc.babylonjs.com/how_to/webvr_helper
  104630. */
  104631. var VRExperienceHelper = /** @class */ (function () {
  104632. /**
  104633. * Instantiates a VRExperienceHelper.
  104634. * Helps to quickly add VR support to an existing scene.
  104635. * @param scene The scene the VRExperienceHelper belongs to.
  104636. * @param webVROptions Options to modify the vr experience helper's behavior.
  104637. */
  104638. function VRExperienceHelper(scene,
  104639. /** Options to modify the vr experience helper's behavior. */
  104640. webVROptions) {
  104641. if (webVROptions === void 0) { webVROptions = {}; }
  104642. var _this = this;
  104643. this.webVROptions = webVROptions;
  104644. // Can the system support WebVR, even if a headset isn't plugged in?
  104645. this._webVRsupported = false;
  104646. // If WebVR is supported, is a headset plugged in and are we ready to present?
  104647. this._webVRready = false;
  104648. // Are we waiting for the requestPresent callback to complete?
  104649. this._webVRrequesting = false;
  104650. // Are we presenting to the headset right now? (this is the vrDevice state)
  104651. this._webVRpresenting = false;
  104652. // Are we presenting in the fullscreen fallback?
  104653. this._fullscreenVRpresenting = false;
  104654. /**
  104655. * Observable raised when entering VR.
  104656. */
  104657. this.onEnteringVRObservable = new BABYLON.Observable();
  104658. /**
  104659. * Observable raised when exiting VR.
  104660. */
  104661. this.onExitingVRObservable = new BABYLON.Observable();
  104662. /**
  104663. * Observable raised when controller mesh is loaded.
  104664. */
  104665. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  104666. this._useCustomVRButton = false;
  104667. this._teleportationRequested = false;
  104668. this._teleportActive = false;
  104669. this._floorMeshesCollection = [];
  104670. this._rotationAllowed = true;
  104671. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  104672. this._isDefaultTeleportationTarget = true;
  104673. this._teleportationFillColor = "#444444";
  104674. this._teleportationBorderColor = "#FFFFFF";
  104675. this._rotationAngle = 0;
  104676. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  104677. this._padSensibilityUp = 0.65;
  104678. this._padSensibilityDown = 0.35;
  104679. this._leftController = null;
  104680. this._rightController = null;
  104681. /**
  104682. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  104683. */
  104684. this.onNewMeshSelected = new BABYLON.Observable();
  104685. /**
  104686. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  104687. */
  104688. this.onNewMeshPicked = new BABYLON.Observable();
  104689. /**
  104690. * Observable raised before camera teleportation
  104691. */
  104692. this.onBeforeCameraTeleport = new BABYLON.Observable();
  104693. /**
  104694. * Observable raised after camera teleportation
  104695. */
  104696. this.onAfterCameraTeleport = new BABYLON.Observable();
  104697. /**
  104698. * Observable raised when current selected mesh gets unselected
  104699. */
  104700. this.onSelectedMeshUnselected = new BABYLON.Observable();
  104701. /**
  104702. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  104703. */
  104704. this.teleportationEnabled = true;
  104705. this._teleportationInitialized = false;
  104706. this._interactionsEnabled = false;
  104707. this._interactionsRequested = false;
  104708. this._displayGaze = true;
  104709. this._displayLaserPointer = true;
  104710. /**
  104711. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  104712. */
  104713. this.updateGazeTrackerScale = true;
  104714. this._onResize = function () {
  104715. _this.moveButtonToBottomRight();
  104716. if (_this._fullscreenVRpresenting && _this._webVRready) {
  104717. _this.exitVR();
  104718. }
  104719. };
  104720. this._onFullscreenChange = function () {
  104721. if (document.fullscreen !== undefined) {
  104722. _this._fullscreenVRpresenting = document.fullscreen;
  104723. }
  104724. else if (document.mozFullScreen !== undefined) {
  104725. _this._fullscreenVRpresenting = document.mozFullScreen;
  104726. }
  104727. else if (document.webkitIsFullScreen !== undefined) {
  104728. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  104729. }
  104730. else if (document.msIsFullScreen !== undefined) {
  104731. _this._fullscreenVRpresenting = document.msIsFullScreen;
  104732. }
  104733. else if (document.msFullscreenElement !== undefined) {
  104734. _this._fullscreenVRpresenting = document.msFullscreenElement;
  104735. }
  104736. if (!_this._fullscreenVRpresenting && _this._canvas) {
  104737. _this.exitVR();
  104738. if (!_this._useCustomVRButton) {
  104739. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  104740. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  104741. }
  104742. }
  104743. };
  104744. this.beforeRender = function () {
  104745. if (_this._leftController && _this._leftController._activePointer) {
  104746. _this._castRayAndSelectObject(_this._leftController);
  104747. }
  104748. if (_this._rightController && _this._rightController._activePointer) {
  104749. _this._castRayAndSelectObject(_this._rightController);
  104750. }
  104751. if (_this._noControllerIsActive) {
  104752. _this._castRayAndSelectObject(_this._cameraGazer);
  104753. }
  104754. else {
  104755. _this._cameraGazer._gazeTracker.isVisible = false;
  104756. }
  104757. };
  104758. this._onNewGamepadConnected = function (gamepad) {
  104759. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  104760. if (gamepad.leftStick) {
  104761. gamepad.onleftstickchanged(function (stickValues) {
  104762. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  104763. // Listening to classic/xbox gamepad only if no VR controller is active
  104764. if ((!_this._leftController && !_this._rightController) ||
  104765. ((_this._leftController && !_this._leftController._activePointer) &&
  104766. (_this._rightController && !_this._rightController._activePointer))) {
  104767. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  104768. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  104769. }
  104770. }
  104771. });
  104772. }
  104773. if (gamepad.rightStick) {
  104774. gamepad.onrightstickchanged(function (stickValues) {
  104775. if (_this._teleportationInitialized) {
  104776. _this._checkRotate(stickValues, _this._cameraGazer);
  104777. }
  104778. });
  104779. }
  104780. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  104781. gamepad.onbuttondown(function (buttonPressed) {
  104782. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104783. _this._cameraGazer._selectionPointerDown();
  104784. }
  104785. });
  104786. gamepad.onbuttonup(function (buttonPressed) {
  104787. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104788. _this._cameraGazer._selectionPointerUp();
  104789. }
  104790. });
  104791. }
  104792. }
  104793. else {
  104794. var webVRController = gamepad;
  104795. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  104796. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  104797. _this._rightController = controller;
  104798. }
  104799. else {
  104800. _this._leftController = controller;
  104801. }
  104802. _this._tryEnableInteractionOnController(controller);
  104803. }
  104804. };
  104805. // 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
  104806. this._tryEnableInteractionOnController = function (controller) {
  104807. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  104808. _this._enableInteractionOnController(controller);
  104809. }
  104810. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  104811. _this._enableTeleportationOnController(controller);
  104812. }
  104813. };
  104814. this._onNewGamepadDisconnected = function (gamepad) {
  104815. if (gamepad instanceof BABYLON.WebVRController) {
  104816. if (gamepad.hand === "left" && _this._leftController != null) {
  104817. _this._leftController.dispose();
  104818. _this._leftController = null;
  104819. }
  104820. if (gamepad.hand === "right" && _this._rightController != null) {
  104821. _this._rightController.dispose();
  104822. _this._rightController = null;
  104823. }
  104824. }
  104825. };
  104826. this._workingVector = BABYLON.Vector3.Zero();
  104827. this._workingQuaternion = BABYLON.Quaternion.Identity();
  104828. this._workingMatrix = BABYLON.Matrix.Identity();
  104829. this._scene = scene;
  104830. this._canvas = scene.getEngine().getRenderingCanvas();
  104831. // Parse options
  104832. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  104833. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  104834. }
  104835. if (webVROptions.createDeviceOrientationCamera === undefined) {
  104836. webVROptions.createDeviceOrientationCamera = true;
  104837. }
  104838. if (webVROptions.laserToggle === undefined) {
  104839. webVROptions.laserToggle = true;
  104840. }
  104841. if (webVROptions.defaultHeight === undefined) {
  104842. webVROptions.defaultHeight = 1.7;
  104843. }
  104844. if (webVROptions.useCustomVRButton) {
  104845. this._useCustomVRButton = true;
  104846. if (webVROptions.customVRButton) {
  104847. this._btnVR = webVROptions.customVRButton;
  104848. }
  104849. }
  104850. if (webVROptions.rayLength) {
  104851. this._rayLength = webVROptions.rayLength;
  104852. }
  104853. this._defaultHeight = webVROptions.defaultHeight;
  104854. if (webVROptions.positionScale) {
  104855. this._rayLength *= webVROptions.positionScale;
  104856. this._defaultHeight *= webVROptions.positionScale;
  104857. }
  104858. this._hasEnteredVR = false;
  104859. // Set position
  104860. if (this._scene.activeCamera) {
  104861. this._position = this._scene.activeCamera.position.clone();
  104862. }
  104863. else {
  104864. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  104865. }
  104866. // Set non-vr camera
  104867. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  104868. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  104869. // Copy data from existing camera
  104870. if (this._scene.activeCamera) {
  104871. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  104872. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  104873. // Set rotation from previous camera
  104874. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  104875. var targetCamera = this._scene.activeCamera;
  104876. if (targetCamera.rotationQuaternion) {
  104877. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  104878. }
  104879. else {
  104880. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  104881. }
  104882. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  104883. }
  104884. }
  104885. this._scene.activeCamera = this._deviceOrientationCamera;
  104886. if (this._canvas) {
  104887. this._scene.activeCamera.attachControl(this._canvas);
  104888. }
  104889. }
  104890. else {
  104891. this._existingCamera = this._scene.activeCamera;
  104892. }
  104893. // Create VR cameras
  104894. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104895. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  104896. }
  104897. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  104898. this._webVRCamera.useStandingMatrix();
  104899. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  104900. // Create default button
  104901. if (!this._useCustomVRButton) {
  104902. this._btnVR = document.createElement("BUTTON");
  104903. this._btnVR.className = "babylonVRicon";
  104904. this._btnVR.id = "babylonVRiconbtn";
  104905. this._btnVR.title = "Click to switch to VR";
  104906. 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) }";
  104907. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  104908. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  104909. // css += ".babylonVRicon.vrdisplaysupported { }";
  104910. // css += ".babylonVRicon.vrdisplayready { }";
  104911. // css += ".babylonVRicon.vrdisplayrequesting { }";
  104912. var style = document.createElement('style');
  104913. style.appendChild(document.createTextNode(css));
  104914. document.getElementsByTagName('head')[0].appendChild(style);
  104915. this.moveButtonToBottomRight();
  104916. }
  104917. // VR button click event
  104918. if (this._btnVR) {
  104919. this._btnVR.addEventListener("click", function () {
  104920. if (!_this.isInVRMode) {
  104921. _this.enterVR();
  104922. }
  104923. else {
  104924. _this.exitVR();
  104925. }
  104926. });
  104927. }
  104928. // Window events
  104929. window.addEventListener("resize", this._onResize);
  104930. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  104931. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  104932. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  104933. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  104934. document.onmsfullscreenchange = this._onFullscreenChange;
  104935. // Display vr button when headset is connected
  104936. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104937. this.displayVRButton();
  104938. }
  104939. else {
  104940. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  104941. if (e.vrDisplay) {
  104942. _this.displayVRButton();
  104943. }
  104944. });
  104945. }
  104946. // Exiting VR mode using 'ESC' key on desktop
  104947. this._onKeyDown = function (event) {
  104948. if (event.keyCode === 27 && _this.isInVRMode) {
  104949. _this.exitVR();
  104950. }
  104951. };
  104952. document.addEventListener("keydown", this._onKeyDown);
  104953. // Exiting VR mode double tapping the touch screen
  104954. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  104955. if (_this.isInVRMode) {
  104956. _this.exitVR();
  104957. if (_this._fullscreenVRpresenting) {
  104958. _this._scene.getEngine().switchFullscreen(true);
  104959. }
  104960. }
  104961. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  104962. // Listen for WebVR display changes
  104963. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  104964. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  104965. this._onVRRequestPresentStart = function () {
  104966. _this._webVRrequesting = true;
  104967. _this.updateButtonVisibility();
  104968. };
  104969. this._onVRRequestPresentComplete = function (success) {
  104970. _this._webVRrequesting = false;
  104971. _this.updateButtonVisibility();
  104972. };
  104973. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  104974. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  104975. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  104976. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104977. scene.onDisposeObservable.add(function () {
  104978. _this.dispose();
  104979. });
  104980. // Gamepad connection events
  104981. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  104982. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  104983. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  104984. this.updateButtonVisibility();
  104985. //create easing functions
  104986. this._circleEase = new BABYLON.CircleEase();
  104987. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  104988. if (this.webVROptions.floorMeshes) {
  104989. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  104990. }
  104991. }
  104992. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  104993. /** Return this.onEnteringVRObservable
  104994. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  104995. */
  104996. get: function () {
  104997. return this.onEnteringVRObservable;
  104998. },
  104999. enumerable: true,
  105000. configurable: true
  105001. });
  105002. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  105003. /** Return this.onExitingVRObservable
  105004. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  105005. */
  105006. get: function () {
  105007. return this.onExitingVRObservable;
  105008. },
  105009. enumerable: true,
  105010. configurable: true
  105011. });
  105012. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  105013. /** Return this.onControllerMeshLoadedObservable
  105014. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  105015. */
  105016. get: function () {
  105017. return this.onControllerMeshLoadedObservable;
  105018. },
  105019. enumerable: true,
  105020. configurable: true
  105021. });
  105022. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  105023. /**
  105024. * The mesh used to display where the user is going to teleport.
  105025. */
  105026. get: function () {
  105027. return this._teleportationTarget;
  105028. },
  105029. /**
  105030. * Sets the mesh to be used to display where the user is going to teleport.
  105031. */
  105032. set: function (value) {
  105033. if (value) {
  105034. value.name = "teleportationTarget";
  105035. this._isDefaultTeleportationTarget = false;
  105036. this._teleportationTarget = value;
  105037. }
  105038. },
  105039. enumerable: true,
  105040. configurable: true
  105041. });
  105042. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  105043. /**
  105044. * 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
  105045. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  105046. * See http://doc.babylonjs.com/resources/baking_transformations
  105047. */
  105048. get: function () {
  105049. return this._cameraGazer._gazeTracker;
  105050. },
  105051. set: function (value) {
  105052. if (value) {
  105053. // Dispose of existing meshes
  105054. if (this._cameraGazer._gazeTracker) {
  105055. this._cameraGazer._gazeTracker.dispose();
  105056. }
  105057. if (this._leftController && this._leftController._gazeTracker) {
  105058. this._leftController._gazeTracker.dispose();
  105059. }
  105060. if (this._rightController && this._rightController._gazeTracker) {
  105061. this._rightController._gazeTracker.dispose();
  105062. }
  105063. // Set and create gaze trackers on head and controllers
  105064. this._cameraGazer._gazeTracker = value;
  105065. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  105066. this._cameraGazer._gazeTracker.isPickable = false;
  105067. this._cameraGazer._gazeTracker.isVisible = false;
  105068. this._cameraGazer._gazeTracker.name = "gazeTracker";
  105069. if (this._leftController) {
  105070. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  105071. }
  105072. if (this._rightController) {
  105073. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  105074. }
  105075. }
  105076. },
  105077. enumerable: true,
  105078. configurable: true
  105079. });
  105080. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  105081. /**
  105082. * The gaze tracking mesh corresponding to the left controller
  105083. */
  105084. get: function () {
  105085. if (this._leftController) {
  105086. return this._leftController._gazeTracker;
  105087. }
  105088. return null;
  105089. },
  105090. enumerable: true,
  105091. configurable: true
  105092. });
  105093. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  105094. /**
  105095. * The gaze tracking mesh corresponding to the right controller
  105096. */
  105097. get: function () {
  105098. if (this._rightController) {
  105099. return this._rightController._gazeTracker;
  105100. }
  105101. return null;
  105102. },
  105103. enumerable: true,
  105104. configurable: true
  105105. });
  105106. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  105107. /**
  105108. * If the ray of the gaze should be displayed.
  105109. */
  105110. get: function () {
  105111. return this._displayGaze;
  105112. },
  105113. /**
  105114. * Sets if the ray of the gaze should be displayed.
  105115. */
  105116. set: function (value) {
  105117. this._displayGaze = value;
  105118. if (!value) {
  105119. this._cameraGazer._gazeTracker.isVisible = false;
  105120. if (this._leftController) {
  105121. this._leftController._gazeTracker.isVisible = false;
  105122. }
  105123. if (this._rightController) {
  105124. this._rightController._gazeTracker.isVisible = false;
  105125. }
  105126. }
  105127. },
  105128. enumerable: true,
  105129. configurable: true
  105130. });
  105131. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  105132. /**
  105133. * If the ray of the LaserPointer should be displayed.
  105134. */
  105135. get: function () {
  105136. return this._displayLaserPointer;
  105137. },
  105138. /**
  105139. * Sets if the ray of the LaserPointer should be displayed.
  105140. */
  105141. set: function (value) {
  105142. this._displayLaserPointer = value;
  105143. if (!value) {
  105144. if (this._rightController) {
  105145. this._rightController._deactivatePointer();
  105146. this._rightController._gazeTracker.isVisible = false;
  105147. }
  105148. if (this._leftController) {
  105149. this._leftController._deactivatePointer();
  105150. this._leftController._gazeTracker.isVisible = false;
  105151. }
  105152. }
  105153. else {
  105154. if (this._rightController) {
  105155. this._rightController._activatePointer();
  105156. }
  105157. if (this._leftController) {
  105158. this._leftController._activatePointer();
  105159. }
  105160. }
  105161. },
  105162. enumerable: true,
  105163. configurable: true
  105164. });
  105165. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  105166. /**
  105167. * The deviceOrientationCamera used as the camera when not in VR.
  105168. */
  105169. get: function () {
  105170. return this._deviceOrientationCamera;
  105171. },
  105172. enumerable: true,
  105173. configurable: true
  105174. });
  105175. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  105176. /**
  105177. * Based on the current WebVR support, returns the current VR camera used.
  105178. */
  105179. get: function () {
  105180. if (this._webVRready) {
  105181. return this._webVRCamera;
  105182. }
  105183. else {
  105184. return this._scene.activeCamera;
  105185. }
  105186. },
  105187. enumerable: true,
  105188. configurable: true
  105189. });
  105190. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  105191. /**
  105192. * The webVRCamera which is used when in VR.
  105193. */
  105194. get: function () {
  105195. return this._webVRCamera;
  105196. },
  105197. enumerable: true,
  105198. configurable: true
  105199. });
  105200. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  105201. /**
  105202. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  105203. */
  105204. get: function () {
  105205. return this._vrDeviceOrientationCamera;
  105206. },
  105207. enumerable: true,
  105208. configurable: true
  105209. });
  105210. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  105211. get: function () {
  105212. var result = this._cameraGazer._teleportationRequestInitiated
  105213. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  105214. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  105215. return result;
  105216. },
  105217. enumerable: true,
  105218. configurable: true
  105219. });
  105220. // Raised when one of the controller has loaded successfully its associated default mesh
  105221. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  105222. if (this._leftController && this._leftController.webVRController == webVRController) {
  105223. if (webVRController.mesh) {
  105224. this._leftController._setLaserPointerParent(webVRController.mesh);
  105225. }
  105226. }
  105227. if (this._rightController && this._rightController.webVRController == webVRController) {
  105228. if (webVRController.mesh) {
  105229. this._rightController._setLaserPointerParent(webVRController.mesh);
  105230. }
  105231. }
  105232. try {
  105233. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  105234. }
  105235. catch (err) {
  105236. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  105237. }
  105238. };
  105239. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  105240. /**
  105241. * Gets a value indicating if we are currently in VR mode.
  105242. */
  105243. get: function () {
  105244. return this._webVRpresenting || this._fullscreenVRpresenting;
  105245. },
  105246. enumerable: true,
  105247. configurable: true
  105248. });
  105249. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  105250. var vrDisplay = this._scene.getEngine().getVRDevice();
  105251. if (vrDisplay) {
  105252. var wasPresenting = this._webVRpresenting;
  105253. this._webVRpresenting = vrDisplay.isPresenting;
  105254. if (wasPresenting && !this._webVRpresenting) {
  105255. this.exitVR();
  105256. }
  105257. }
  105258. else {
  105259. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  105260. }
  105261. this.updateButtonVisibility();
  105262. };
  105263. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  105264. this._webVRsupported = eventArgs.vrSupported;
  105265. this._webVRready = !!eventArgs.vrDisplay;
  105266. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  105267. this.updateButtonVisibility();
  105268. };
  105269. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  105270. if (this._canvas && !this._useCustomVRButton) {
  105271. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  105272. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  105273. }
  105274. };
  105275. VRExperienceHelper.prototype.displayVRButton = function () {
  105276. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  105277. document.body.appendChild(this._btnVR);
  105278. this._btnVRDisplayed = true;
  105279. }
  105280. };
  105281. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  105282. if (!this._btnVR || this._useCustomVRButton) {
  105283. return;
  105284. }
  105285. this._btnVR.className = "babylonVRicon";
  105286. if (this.isInVRMode) {
  105287. this._btnVR.className += " vrdisplaypresenting";
  105288. }
  105289. else {
  105290. if (this._webVRready) {
  105291. this._btnVR.className += " vrdisplayready";
  105292. }
  105293. if (this._webVRsupported) {
  105294. this._btnVR.className += " vrdisplaysupported";
  105295. }
  105296. if (this._webVRrequesting) {
  105297. this._btnVR.className += " vrdisplayrequesting";
  105298. }
  105299. }
  105300. };
  105301. /**
  105302. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  105303. * Otherwise, will use the fullscreen API.
  105304. */
  105305. VRExperienceHelper.prototype.enterVR = function () {
  105306. if (this.onEnteringVRObservable) {
  105307. try {
  105308. this.onEnteringVRObservable.notifyObservers(this);
  105309. }
  105310. catch (err) {
  105311. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  105312. }
  105313. }
  105314. if (this._scene.activeCamera) {
  105315. this._position = this._scene.activeCamera.position.clone();
  105316. // make sure that we return to the last active camera
  105317. this._existingCamera = this._scene.activeCamera;
  105318. }
  105319. if (this._webVRrequesting) {
  105320. return;
  105321. }
  105322. // If WebVR is supported and a headset is connected
  105323. if (this._webVRready) {
  105324. if (!this._webVRpresenting) {
  105325. this._webVRCamera.position = this._position;
  105326. this._scene.activeCamera = this._webVRCamera;
  105327. }
  105328. }
  105329. else if (this._vrDeviceOrientationCamera) {
  105330. this._vrDeviceOrientationCamera.position = this._position;
  105331. if (this._scene.activeCamera) {
  105332. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  105333. }
  105334. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  105335. this._scene.getEngine().switchFullscreen(true);
  105336. this.updateButtonVisibility();
  105337. }
  105338. if (this._scene.activeCamera && this._canvas) {
  105339. this._scene.activeCamera.attachControl(this._canvas);
  105340. }
  105341. if (this._interactionsEnabled) {
  105342. this._scene.registerBeforeRender(this.beforeRender);
  105343. }
  105344. this._hasEnteredVR = true;
  105345. };
  105346. /**
  105347. * Attempt to exit VR, or fullscreen.
  105348. */
  105349. VRExperienceHelper.prototype.exitVR = function () {
  105350. if (this._hasEnteredVR) {
  105351. if (this.onExitingVRObservable) {
  105352. try {
  105353. this.onExitingVRObservable.notifyObservers(this);
  105354. }
  105355. catch (err) {
  105356. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  105357. }
  105358. }
  105359. if (this._webVRpresenting) {
  105360. this._scene.getEngine().disableVR();
  105361. }
  105362. if (this._scene.activeCamera) {
  105363. this._position = this._scene.activeCamera.position.clone();
  105364. }
  105365. if (this._deviceOrientationCamera) {
  105366. this._deviceOrientationCamera.position = this._position;
  105367. this._scene.activeCamera = this._deviceOrientationCamera;
  105368. if (this._canvas) {
  105369. this._scene.activeCamera.attachControl(this._canvas);
  105370. }
  105371. }
  105372. else if (this._existingCamera) {
  105373. this._existingCamera.position = this._position;
  105374. this._scene.activeCamera = this._existingCamera;
  105375. }
  105376. this.updateButtonVisibility();
  105377. if (this._interactionsEnabled) {
  105378. this._scene.unregisterBeforeRender(this.beforeRender);
  105379. this._cameraGazer._gazeTracker.isVisible = false;
  105380. if (this._leftController) {
  105381. this._leftController._gazeTracker.isVisible = false;
  105382. }
  105383. if (this._rightController) {
  105384. this._rightController._gazeTracker.isVisible = false;
  105385. }
  105386. }
  105387. // resize to update width and height when exiting vr exits fullscreen
  105388. this._scene.getEngine().resize();
  105389. this._hasEnteredVR = false;
  105390. }
  105391. };
  105392. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  105393. /**
  105394. * The position of the vr experience helper.
  105395. */
  105396. get: function () {
  105397. return this._position;
  105398. },
  105399. /**
  105400. * Sets the position of the vr experience helper.
  105401. */
  105402. set: function (value) {
  105403. this._position = value;
  105404. if (this._scene.activeCamera) {
  105405. this._scene.activeCamera.position = value;
  105406. }
  105407. },
  105408. enumerable: true,
  105409. configurable: true
  105410. });
  105411. /**
  105412. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  105413. */
  105414. VRExperienceHelper.prototype.enableInteractions = function () {
  105415. var _this = this;
  105416. if (!this._interactionsEnabled) {
  105417. this._interactionsRequested = true;
  105418. if (this._leftController) {
  105419. this._enableInteractionOnController(this._leftController);
  105420. }
  105421. if (this._rightController) {
  105422. this._enableInteractionOnController(this._rightController);
  105423. }
  105424. this.raySelectionPredicate = function (mesh) {
  105425. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  105426. };
  105427. this.meshSelectionPredicate = function (mesh) {
  105428. return true;
  105429. };
  105430. this._raySelectionPredicate = function (mesh) {
  105431. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  105432. && mesh.name.indexOf("teleportationTarget") === -1
  105433. && mesh.name.indexOf("torusTeleportation") === -1)) {
  105434. return _this.raySelectionPredicate(mesh);
  105435. }
  105436. return false;
  105437. };
  105438. this._interactionsEnabled = true;
  105439. }
  105440. };
  105441. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  105442. get: function () {
  105443. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  105444. },
  105445. enumerable: true,
  105446. configurable: true
  105447. });
  105448. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  105449. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  105450. if (this._floorMeshesCollection[i].id === mesh.id) {
  105451. return true;
  105452. }
  105453. }
  105454. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  105455. return true;
  105456. }
  105457. return false;
  105458. };
  105459. /**
  105460. * Adds a floor mesh to be used for teleportation.
  105461. * @param floorMesh the mesh to be used for teleportation.
  105462. */
  105463. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  105464. if (!this._floorMeshesCollection) {
  105465. return;
  105466. }
  105467. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  105468. return;
  105469. }
  105470. this._floorMeshesCollection.push(floorMesh);
  105471. };
  105472. /**
  105473. * Removes a floor mesh from being used for teleportation.
  105474. * @param floorMesh the mesh to be removed.
  105475. */
  105476. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  105477. if (!this._floorMeshesCollection) {
  105478. return;
  105479. }
  105480. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  105481. if (meshIndex !== -1) {
  105482. this._floorMeshesCollection.splice(meshIndex, 1);
  105483. }
  105484. };
  105485. /**
  105486. * Enables interactions and teleportation using the VR controllers and gaze.
  105487. * @param vrTeleportationOptions options to modify teleportation behavior.
  105488. */
  105489. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  105490. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  105491. if (!this._teleportationInitialized) {
  105492. this._teleportationRequested = true;
  105493. this.enableInteractions();
  105494. if (vrTeleportationOptions.floorMeshName) {
  105495. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  105496. }
  105497. if (vrTeleportationOptions.floorMeshes) {
  105498. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  105499. }
  105500. if (this._leftController != null) {
  105501. this._enableTeleportationOnController(this._leftController);
  105502. }
  105503. if (this._rightController != null) {
  105504. this._enableTeleportationOnController(this._rightController);
  105505. }
  105506. // Creates an image processing post process for the vignette not relying
  105507. // on the main scene configuration for image processing to reduce setup and spaces
  105508. // (gamma/linear) conflicts.
  105509. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  105510. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  105511. imageProcessingConfiguration.vignetteEnabled = true;
  105512. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  105513. this._webVRCamera.detachPostProcess(this._postProcessMove);
  105514. this._teleportationInitialized = true;
  105515. if (this._isDefaultTeleportationTarget) {
  105516. this._createTeleportationCircles();
  105517. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  105518. }
  105519. }
  105520. };
  105521. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  105522. var _this = this;
  105523. var controllerMesh = controller.webVRController.mesh;
  105524. if (controllerMesh) {
  105525. controller._interactionsEnabled = true;
  105526. controller._activatePointer();
  105527. if (this.webVROptions.laserToggle) {
  105528. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  105529. // Enabling / disabling laserPointer
  105530. if (_this._displayLaserPointer && stateObject.value === 1) {
  105531. if (controller._activePointer) {
  105532. controller._deactivatePointer();
  105533. }
  105534. else {
  105535. controller._activatePointer();
  105536. }
  105537. if (_this.displayGaze) {
  105538. controller._gazeTracker.isVisible = controller._activePointer;
  105539. }
  105540. }
  105541. });
  105542. }
  105543. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  105544. var gazer = controller;
  105545. if (_this._noControllerIsActive) {
  105546. gazer = _this._cameraGazer;
  105547. }
  105548. if (!gazer._pointerDownOnMeshAsked) {
  105549. if (stateObject.value > _this._padSensibilityUp) {
  105550. gazer._selectionPointerDown();
  105551. }
  105552. }
  105553. else if (stateObject.value < _this._padSensibilityDown) {
  105554. gazer._selectionPointerUp();
  105555. }
  105556. });
  105557. }
  105558. };
  105559. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  105560. // Dont teleport if another gaze already requested teleportation
  105561. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  105562. return;
  105563. }
  105564. if (!gazer._teleportationRequestInitiated) {
  105565. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  105566. gazer._activatePointer();
  105567. gazer._teleportationRequestInitiated = true;
  105568. }
  105569. }
  105570. else {
  105571. // Listening to the proper controller values changes to confirm teleportation
  105572. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  105573. if (this._teleportActive) {
  105574. this.teleportCamera(this._haloCenter);
  105575. }
  105576. gazer._teleportationRequestInitiated = false;
  105577. }
  105578. }
  105579. };
  105580. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  105581. // Only rotate when user is not currently selecting a teleportation location
  105582. if (gazer._teleportationRequestInitiated) {
  105583. return;
  105584. }
  105585. if (!gazer._rotationLeftAsked) {
  105586. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  105587. gazer._rotationLeftAsked = true;
  105588. if (this._rotationAllowed) {
  105589. this._rotateCamera(false);
  105590. }
  105591. }
  105592. }
  105593. else {
  105594. if (stateObject.x > -this._padSensibilityDown) {
  105595. gazer._rotationLeftAsked = false;
  105596. }
  105597. }
  105598. if (!gazer._rotationRightAsked) {
  105599. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  105600. gazer._rotationRightAsked = true;
  105601. if (this._rotationAllowed) {
  105602. this._rotateCamera(true);
  105603. }
  105604. }
  105605. }
  105606. else {
  105607. if (stateObject.x < this._padSensibilityDown) {
  105608. gazer._rotationRightAsked = false;
  105609. }
  105610. }
  105611. };
  105612. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  105613. // Only teleport backwards when user is not currently selecting a teleportation location
  105614. if (gazer._teleportationRequestInitiated) {
  105615. return;
  105616. }
  105617. // Teleport backwards
  105618. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  105619. if (!gazer._teleportationBackRequestInitiated) {
  105620. if (!this.currentVRCamera) {
  105621. return;
  105622. }
  105623. // Get rotation and position of the current camera
  105624. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  105625. var position = this.currentVRCamera.position;
  105626. // If the camera has device position, use that instead
  105627. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  105628. rotation = this.currentVRCamera.deviceRotationQuaternion;
  105629. position = this.currentVRCamera.devicePosition;
  105630. }
  105631. // Get matrix with only the y rotation of the device rotation
  105632. rotation.toEulerAnglesToRef(this._workingVector);
  105633. this._workingVector.z = 0;
  105634. this._workingVector.x = 0;
  105635. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  105636. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  105637. // Rotate backwards ray by device rotation to cast at the ground behind the user
  105638. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  105639. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  105640. var ray = new BABYLON.Ray(position, this._workingVector);
  105641. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105642. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  105643. this.teleportCamera(hit.pickedPoint);
  105644. }
  105645. gazer._teleportationBackRequestInitiated = true;
  105646. }
  105647. }
  105648. else {
  105649. gazer._teleportationBackRequestInitiated = false;
  105650. }
  105651. };
  105652. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  105653. var _this = this;
  105654. var controllerMesh = controller.webVRController.mesh;
  105655. if (controllerMesh) {
  105656. if (!controller._interactionsEnabled) {
  105657. this._enableInteractionOnController(controller);
  105658. }
  105659. controller._interactionsEnabled = true;
  105660. controller._teleportationEnabled = true;
  105661. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105662. controller._dpadPressed = false;
  105663. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  105664. controller._dpadPressed = stateObject.pressed;
  105665. if (!controller._dpadPressed) {
  105666. controller._rotationLeftAsked = false;
  105667. controller._rotationRightAsked = false;
  105668. controller._teleportationBackRequestInitiated = false;
  105669. }
  105670. });
  105671. }
  105672. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  105673. if (_this.teleportationEnabled) {
  105674. _this._checkTeleportBackwards(stateObject, controller);
  105675. _this._checkTeleportWithRay(stateObject, controller);
  105676. }
  105677. _this._checkRotate(stateObject, controller);
  105678. });
  105679. }
  105680. };
  105681. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  105682. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  105683. this._teleportationTarget.isPickable = false;
  105684. var length = 512;
  105685. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  105686. dynamicTexture.hasAlpha = true;
  105687. var context = dynamicTexture.getContext();
  105688. var centerX = length / 2;
  105689. var centerY = length / 2;
  105690. var radius = 200;
  105691. context.beginPath();
  105692. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  105693. context.fillStyle = this._teleportationFillColor;
  105694. context.fill();
  105695. context.lineWidth = 10;
  105696. context.strokeStyle = this._teleportationBorderColor;
  105697. context.stroke();
  105698. context.closePath();
  105699. dynamicTexture.update();
  105700. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  105701. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  105702. this._teleportationTarget.material = teleportationCircleMaterial;
  105703. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  105704. torus.isPickable = false;
  105705. torus.parent = this._teleportationTarget;
  105706. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105707. var keys = [];
  105708. keys.push({
  105709. frame: 0,
  105710. value: 0
  105711. });
  105712. keys.push({
  105713. frame: 30,
  105714. value: 0.4
  105715. });
  105716. keys.push({
  105717. frame: 60,
  105718. value: 0
  105719. });
  105720. animationInnerCircle.setKeys(keys);
  105721. var easingFunction = new BABYLON.SineEase();
  105722. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  105723. animationInnerCircle.setEasingFunction(easingFunction);
  105724. torus.animations = [];
  105725. torus.animations.push(animationInnerCircle);
  105726. this._scene.beginAnimation(torus, 0, 60, true);
  105727. this._hideTeleportationTarget();
  105728. };
  105729. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  105730. this._teleportActive = true;
  105731. if (this._teleportationInitialized) {
  105732. this._teleportationTarget.isVisible = true;
  105733. if (this._isDefaultTeleportationTarget) {
  105734. this._teleportationTarget.getChildren()[0].isVisible = true;
  105735. }
  105736. }
  105737. };
  105738. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  105739. this._teleportActive = false;
  105740. if (this._teleportationInitialized) {
  105741. this._teleportationTarget.isVisible = false;
  105742. if (this._isDefaultTeleportationTarget) {
  105743. this._teleportationTarget.getChildren()[0].isVisible = false;
  105744. }
  105745. }
  105746. };
  105747. VRExperienceHelper.prototype._rotateCamera = function (right) {
  105748. var _this = this;
  105749. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105750. return;
  105751. }
  105752. if (right) {
  105753. this._rotationAngle++;
  105754. }
  105755. else {
  105756. this._rotationAngle--;
  105757. }
  105758. this.currentVRCamera.animations = [];
  105759. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  105760. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105761. var animationRotationKeys = [];
  105762. animationRotationKeys.push({
  105763. frame: 0,
  105764. value: this.currentVRCamera.rotationQuaternion
  105765. });
  105766. animationRotationKeys.push({
  105767. frame: 6,
  105768. value: target
  105769. });
  105770. animationRotation.setKeys(animationRotationKeys);
  105771. animationRotation.setEasingFunction(this._circleEase);
  105772. this.currentVRCamera.animations.push(animationRotation);
  105773. this._postProcessMove.animations = [];
  105774. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105775. var vignetteWeightKeys = [];
  105776. vignetteWeightKeys.push({
  105777. frame: 0,
  105778. value: 0
  105779. });
  105780. vignetteWeightKeys.push({
  105781. frame: 3,
  105782. value: 4
  105783. });
  105784. vignetteWeightKeys.push({
  105785. frame: 6,
  105786. value: 0
  105787. });
  105788. animationPP.setKeys(vignetteWeightKeys);
  105789. animationPP.setEasingFunction(this._circleEase);
  105790. this._postProcessMove.animations.push(animationPP);
  105791. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105792. var vignetteStretchKeys = [];
  105793. vignetteStretchKeys.push({
  105794. frame: 0,
  105795. value: 0
  105796. });
  105797. vignetteStretchKeys.push({
  105798. frame: 3,
  105799. value: 10
  105800. });
  105801. vignetteStretchKeys.push({
  105802. frame: 6,
  105803. value: 0
  105804. });
  105805. animationPP2.setKeys(vignetteStretchKeys);
  105806. animationPP2.setEasingFunction(this._circleEase);
  105807. this._postProcessMove.animations.push(animationPP2);
  105808. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105809. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105810. this._postProcessMove.samples = 4;
  105811. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105812. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  105813. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105814. });
  105815. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  105816. };
  105817. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  105818. if (hit.pickedPoint) {
  105819. if (gazer._teleportationRequestInitiated) {
  105820. this._displayTeleportationTarget();
  105821. this._haloCenter.copyFrom(hit.pickedPoint);
  105822. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  105823. }
  105824. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  105825. if (pickNormal) {
  105826. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105827. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105828. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  105829. }
  105830. this._teleportationTarget.position.y += 0.1;
  105831. }
  105832. };
  105833. /**
  105834. * Teleports the users feet to the desired location
  105835. * @param location The location where the user's feet should be placed
  105836. */
  105837. VRExperienceHelper.prototype.teleportCamera = function (location) {
  105838. var _this = this;
  105839. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105840. return;
  105841. }
  105842. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  105843. // offset of the headset from the anchor.
  105844. if (this.webVRCamera.leftCamera) {
  105845. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  105846. this._workingVector.subtractInPlace(this.webVRCamera.position);
  105847. location.subtractToRef(this._workingVector, this._workingVector);
  105848. }
  105849. else {
  105850. this._workingVector.copyFrom(location);
  105851. }
  105852. // Add height to account for user's height offset
  105853. if (this.isInVRMode) {
  105854. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  105855. }
  105856. else {
  105857. this._workingVector.y += this._defaultHeight;
  105858. }
  105859. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  105860. // Create animation from the camera's position to the new location
  105861. this.currentVRCamera.animations = [];
  105862. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105863. var animationCameraTeleportationKeys = [{
  105864. frame: 0,
  105865. value: this.currentVRCamera.position
  105866. },
  105867. {
  105868. frame: 11,
  105869. value: this._workingVector
  105870. }
  105871. ];
  105872. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  105873. animationCameraTeleportation.setEasingFunction(this._circleEase);
  105874. this.currentVRCamera.animations.push(animationCameraTeleportation);
  105875. this._postProcessMove.animations = [];
  105876. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105877. var vignetteWeightKeys = [];
  105878. vignetteWeightKeys.push({
  105879. frame: 0,
  105880. value: 0
  105881. });
  105882. vignetteWeightKeys.push({
  105883. frame: 5,
  105884. value: 8
  105885. });
  105886. vignetteWeightKeys.push({
  105887. frame: 11,
  105888. value: 0
  105889. });
  105890. animationPP.setKeys(vignetteWeightKeys);
  105891. this._postProcessMove.animations.push(animationPP);
  105892. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105893. var vignetteStretchKeys = [];
  105894. vignetteStretchKeys.push({
  105895. frame: 0,
  105896. value: 0
  105897. });
  105898. vignetteStretchKeys.push({
  105899. frame: 5,
  105900. value: 10
  105901. });
  105902. vignetteStretchKeys.push({
  105903. frame: 11,
  105904. value: 0
  105905. });
  105906. animationPP2.setKeys(vignetteStretchKeys);
  105907. this._postProcessMove.animations.push(animationPP2);
  105908. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105909. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105910. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105911. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  105912. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105913. });
  105914. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  105915. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  105916. });
  105917. this._hideTeleportationTarget();
  105918. };
  105919. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  105920. if (normal) {
  105921. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  105922. if (angle < Math.PI / 2) {
  105923. normal.scaleInPlace(-1);
  105924. }
  105925. }
  105926. return normal;
  105927. };
  105928. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  105929. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105930. return;
  105931. }
  105932. var ray = gazer._getForwardRay(this._rayLength);
  105933. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105934. if (hit) {
  105935. // Populate the contrllers mesh that can be used for drag/drop
  105936. if (gazer._laserPointer) {
  105937. hit.originMesh = gazer._laserPointer.parent;
  105938. }
  105939. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  105940. }
  105941. gazer._currentHit = hit;
  105942. // Moving the gazeTracker on the mesh face targetted
  105943. if (hit && hit.pickedPoint) {
  105944. if (this._displayGaze) {
  105945. var multiplier = 1;
  105946. gazer._gazeTracker.isVisible = true;
  105947. if (gazer._isActionableMesh) {
  105948. multiplier = 3;
  105949. }
  105950. if (this.updateGazeTrackerScale) {
  105951. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  105952. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  105953. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  105954. }
  105955. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  105956. // To avoid z-fighting
  105957. var deltaFighting = 0.002;
  105958. if (pickNormal) {
  105959. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105960. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105961. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  105962. }
  105963. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  105964. if (gazer._gazeTracker.position.x < 0) {
  105965. gazer._gazeTracker.position.x += deltaFighting;
  105966. }
  105967. else {
  105968. gazer._gazeTracker.position.x -= deltaFighting;
  105969. }
  105970. if (gazer._gazeTracker.position.y < 0) {
  105971. gazer._gazeTracker.position.y += deltaFighting;
  105972. }
  105973. else {
  105974. gazer._gazeTracker.position.y -= deltaFighting;
  105975. }
  105976. if (gazer._gazeTracker.position.z < 0) {
  105977. gazer._gazeTracker.position.z += deltaFighting;
  105978. }
  105979. else {
  105980. gazer._gazeTracker.position.z -= deltaFighting;
  105981. }
  105982. }
  105983. // Changing the size of the laser pointer based on the distance from the targetted point
  105984. gazer._updatePointerDistance(hit.distance);
  105985. }
  105986. else {
  105987. gazer._updatePointerDistance();
  105988. gazer._gazeTracker.isVisible = false;
  105989. }
  105990. if (hit && hit.pickedMesh) {
  105991. // The object selected is the floor, we're in a teleportation scenario
  105992. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  105993. // Moving the teleportation area to this targetted point
  105994. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  105995. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  105996. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  105997. }
  105998. gazer._currentMeshSelected = null;
  105999. if (gazer._teleportationRequestInitiated) {
  106000. this._moveTeleportationSelectorTo(hit, gazer, ray);
  106001. }
  106002. return;
  106003. }
  106004. // If not, we're in a selection scenario
  106005. //this._teleportationAllowed = false;
  106006. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  106007. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  106008. this.onNewMeshPicked.notifyObservers(hit);
  106009. gazer._currentMeshSelected = hit.pickedMesh;
  106010. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  106011. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  106012. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  106013. gazer._isActionableMesh = true;
  106014. }
  106015. else {
  106016. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106017. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106018. gazer._isActionableMesh = false;
  106019. }
  106020. try {
  106021. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  106022. }
  106023. catch (err) {
  106024. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  106025. }
  106026. }
  106027. else {
  106028. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106029. gazer._currentMeshSelected = null;
  106030. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106031. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106032. }
  106033. }
  106034. }
  106035. else {
  106036. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106037. gazer._currentMeshSelected = null;
  106038. //this._teleportationAllowed = false;
  106039. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106040. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106041. }
  106042. };
  106043. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  106044. if (mesh) {
  106045. this.onSelectedMeshUnselected.notifyObservers(mesh);
  106046. }
  106047. };
  106048. /**
  106049. * Sets the color of the laser ray from the vr controllers.
  106050. * @param color new color for the ray.
  106051. */
  106052. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  106053. if (this._leftController) {
  106054. this._leftController._setLaserPointerColor(color);
  106055. }
  106056. if (this._rightController) {
  106057. this._rightController._setLaserPointerColor(color);
  106058. }
  106059. };
  106060. /**
  106061. * Sets the color of the ray from the vr headsets gaze.
  106062. * @param color new color for the ray.
  106063. */
  106064. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  106065. if (!this._cameraGazer._gazeTracker.material) {
  106066. return;
  106067. }
  106068. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  106069. if (this._leftController) {
  106070. this._leftController._gazeTracker.material.emissiveColor = color;
  106071. }
  106072. if (this._rightController) {
  106073. this._rightController._gazeTracker.material.emissiveColor = color;
  106074. }
  106075. };
  106076. /**
  106077. * Exits VR and disposes of the vr experience helper
  106078. */
  106079. VRExperienceHelper.prototype.dispose = function () {
  106080. if (this.isInVRMode) {
  106081. this.exitVR();
  106082. }
  106083. if (this._postProcessMove) {
  106084. this._postProcessMove.dispose();
  106085. }
  106086. if (this._webVRCamera) {
  106087. this._webVRCamera.dispose();
  106088. }
  106089. if (this._vrDeviceOrientationCamera) {
  106090. this._vrDeviceOrientationCamera.dispose();
  106091. }
  106092. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  106093. document.body.removeChild(this._btnVR);
  106094. }
  106095. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  106096. this._deviceOrientationCamera.dispose();
  106097. }
  106098. if (this._cameraGazer) {
  106099. this._cameraGazer.dispose();
  106100. }
  106101. if (this._leftController) {
  106102. this._leftController.dispose();
  106103. }
  106104. if (this._rightController) {
  106105. this._rightController.dispose();
  106106. }
  106107. if (this._teleportationTarget) {
  106108. this._teleportationTarget.dispose();
  106109. }
  106110. this._floorMeshesCollection = [];
  106111. document.removeEventListener("keydown", this._onKeyDown);
  106112. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106113. window.removeEventListener("resize", this._onResize);
  106114. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  106115. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  106116. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  106117. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  106118. document.onmsfullscreenchange = null;
  106119. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  106120. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  106121. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  106122. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106123. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  106124. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  106125. this._scene.unregisterBeforeRender(this.beforeRender);
  106126. };
  106127. /**
  106128. * Gets the name of the VRExperienceHelper class
  106129. * @returns "VRExperienceHelper"
  106130. */
  106131. VRExperienceHelper.prototype.getClassName = function () {
  106132. return "VRExperienceHelper";
  106133. };
  106134. return VRExperienceHelper;
  106135. }());
  106136. BABYLON.VRExperienceHelper = VRExperienceHelper;
  106137. })(BABYLON || (BABYLON = {}));
  106138. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  106139. // Mainly based on these 2 articles :
  106140. // 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
  106141. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  106142. var BABYLON;
  106143. (function (BABYLON) {
  106144. /**
  106145. * Defines the potential axis of a Joystick
  106146. */
  106147. var JoystickAxis;
  106148. (function (JoystickAxis) {
  106149. /** X axis */
  106150. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  106151. /** Y axis */
  106152. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  106153. /** Z axis */
  106154. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  106155. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  106156. /**
  106157. * Class used to define virtual joystick (used in touch mode)
  106158. */
  106159. var VirtualJoystick = /** @class */ (function () {
  106160. /**
  106161. * Creates a new virtual joystick
  106162. * @param leftJoystick defines that the joystick is for left hand (false by default)
  106163. */
  106164. function VirtualJoystick(leftJoystick) {
  106165. var _this = this;
  106166. if (leftJoystick) {
  106167. this._leftJoystick = true;
  106168. }
  106169. else {
  106170. this._leftJoystick = false;
  106171. }
  106172. VirtualJoystick._globalJoystickIndex++;
  106173. // By default left & right arrow keys are moving the X
  106174. // and up & down keys are moving the Y
  106175. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106176. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106177. this.reverseLeftRight = false;
  106178. this.reverseUpDown = false;
  106179. // collections of pointers
  106180. this._touches = new BABYLON.StringDictionary();
  106181. this.deltaPosition = BABYLON.Vector3.Zero();
  106182. this._joystickSensibility = 25;
  106183. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  106184. this._onResize = function (evt) {
  106185. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  106186. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  106187. if (VirtualJoystick.vjCanvas) {
  106188. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  106189. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  106190. }
  106191. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  106192. };
  106193. // injecting a canvas element on top of the canvas 3D game
  106194. if (!VirtualJoystick.vjCanvas) {
  106195. window.addEventListener("resize", this._onResize, false);
  106196. VirtualJoystick.vjCanvas = document.createElement("canvas");
  106197. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  106198. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  106199. VirtualJoystick.vjCanvas.width = window.innerWidth;
  106200. VirtualJoystick.vjCanvas.height = window.innerHeight;
  106201. VirtualJoystick.vjCanvas.style.width = "100%";
  106202. VirtualJoystick.vjCanvas.style.height = "100%";
  106203. VirtualJoystick.vjCanvas.style.position = "absolute";
  106204. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  106205. VirtualJoystick.vjCanvas.style.top = "0px";
  106206. VirtualJoystick.vjCanvas.style.left = "0px";
  106207. VirtualJoystick.vjCanvas.style.zIndex = "5";
  106208. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  106209. // Support for jQuery PEP polyfill
  106210. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  106211. var context = VirtualJoystick.vjCanvas.getContext('2d');
  106212. if (!context) {
  106213. throw new Error("Unable to create canvas for virtual joystick");
  106214. }
  106215. VirtualJoystick.vjCanvasContext = context;
  106216. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  106217. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106218. document.body.appendChild(VirtualJoystick.vjCanvas);
  106219. }
  106220. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  106221. this.pressed = false;
  106222. // default joystick color
  106223. this._joystickColor = "cyan";
  106224. this._joystickPointerID = -1;
  106225. // current joystick position
  106226. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  106227. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  106228. // origin joystick position
  106229. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  106230. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  106231. this._onPointerDownHandlerRef = function (evt) {
  106232. _this._onPointerDown(evt);
  106233. };
  106234. this._onPointerMoveHandlerRef = function (evt) {
  106235. _this._onPointerMove(evt);
  106236. };
  106237. this._onPointerUpHandlerRef = function (evt) {
  106238. _this._onPointerUp(evt);
  106239. };
  106240. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  106241. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  106242. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  106243. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  106244. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  106245. evt.preventDefault(); // Disables system menu
  106246. }, false);
  106247. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106248. }
  106249. /**
  106250. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  106251. * @param newJoystickSensibility defines the new sensibility
  106252. */
  106253. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  106254. this._joystickSensibility = newJoystickSensibility;
  106255. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  106256. };
  106257. VirtualJoystick.prototype._onPointerDown = function (e) {
  106258. var positionOnScreenCondition;
  106259. e.preventDefault();
  106260. if (this._leftJoystick === true) {
  106261. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  106262. }
  106263. else {
  106264. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  106265. }
  106266. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  106267. // First contact will be dedicated to the virtual joystick
  106268. this._joystickPointerID = e.pointerId;
  106269. this._joystickPointerStartPos.x = e.clientX;
  106270. this._joystickPointerStartPos.y = e.clientY;
  106271. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  106272. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  106273. this._deltaJoystickVector.x = 0;
  106274. this._deltaJoystickVector.y = 0;
  106275. this.pressed = true;
  106276. this._touches.add(e.pointerId.toString(), e);
  106277. }
  106278. else {
  106279. // You can only trigger the action buttons with a joystick declared
  106280. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  106281. this._action();
  106282. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  106283. }
  106284. }
  106285. };
  106286. VirtualJoystick.prototype._onPointerMove = function (e) {
  106287. // If the current pointer is the one associated to the joystick (first touch contact)
  106288. if (this._joystickPointerID == e.pointerId) {
  106289. this._joystickPointerPos.x = e.clientX;
  106290. this._joystickPointerPos.y = e.clientY;
  106291. this._deltaJoystickVector = this._joystickPointerPos.clone();
  106292. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  106293. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  106294. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  106295. switch (this._axisTargetedByLeftAndRight) {
  106296. case JoystickAxis.X:
  106297. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  106298. break;
  106299. case JoystickAxis.Y:
  106300. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  106301. break;
  106302. case JoystickAxis.Z:
  106303. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  106304. break;
  106305. }
  106306. var directionUpDown = this.reverseUpDown ? 1 : -1;
  106307. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  106308. switch (this._axisTargetedByUpAndDown) {
  106309. case JoystickAxis.X:
  106310. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  106311. break;
  106312. case JoystickAxis.Y:
  106313. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  106314. break;
  106315. case JoystickAxis.Z:
  106316. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  106317. break;
  106318. }
  106319. }
  106320. else {
  106321. var data = this._touches.get(e.pointerId.toString());
  106322. if (data) {
  106323. data.x = e.clientX;
  106324. data.y = e.clientY;
  106325. }
  106326. }
  106327. };
  106328. VirtualJoystick.prototype._onPointerUp = function (e) {
  106329. if (this._joystickPointerID == e.pointerId) {
  106330. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  106331. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  106332. this._joystickPointerID = -1;
  106333. this.pressed = false;
  106334. }
  106335. else {
  106336. var touch = this._touches.get(e.pointerId.toString());
  106337. if (touch) {
  106338. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106339. }
  106340. }
  106341. this._deltaJoystickVector.x = 0;
  106342. this._deltaJoystickVector.y = 0;
  106343. this._touches.remove(e.pointerId.toString());
  106344. };
  106345. /**
  106346. * Change the color of the virtual joystick
  106347. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  106348. */
  106349. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  106350. this._joystickColor = newColor;
  106351. };
  106352. /**
  106353. * Defines a callback to call when the joystick is touched
  106354. * @param action defines the callback
  106355. */
  106356. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  106357. this._action = action;
  106358. };
  106359. /**
  106360. * Defines which axis you'd like to control for left & right
  106361. * @param axis defines the axis to use
  106362. */
  106363. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  106364. switch (axis) {
  106365. case JoystickAxis.X:
  106366. case JoystickAxis.Y:
  106367. case JoystickAxis.Z:
  106368. this._axisTargetedByLeftAndRight = axis;
  106369. break;
  106370. default:
  106371. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106372. break;
  106373. }
  106374. };
  106375. /**
  106376. * Defines which axis you'd like to control for up & down
  106377. * @param axis defines the axis to use
  106378. */
  106379. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  106380. switch (axis) {
  106381. case JoystickAxis.X:
  106382. case JoystickAxis.Y:
  106383. case JoystickAxis.Z:
  106384. this._axisTargetedByUpAndDown = axis;
  106385. break;
  106386. default:
  106387. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106388. break;
  106389. }
  106390. };
  106391. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  106392. var _this = this;
  106393. if (this.pressed) {
  106394. this._touches.forEach(function (key, touch) {
  106395. if (touch.pointerId === _this._joystickPointerID) {
  106396. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  106397. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  106398. VirtualJoystick.vjCanvasContext.beginPath();
  106399. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106400. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106401. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  106402. VirtualJoystick.vjCanvasContext.stroke();
  106403. VirtualJoystick.vjCanvasContext.closePath();
  106404. VirtualJoystick.vjCanvasContext.beginPath();
  106405. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106406. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106407. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  106408. VirtualJoystick.vjCanvasContext.stroke();
  106409. VirtualJoystick.vjCanvasContext.closePath();
  106410. VirtualJoystick.vjCanvasContext.beginPath();
  106411. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106412. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  106413. VirtualJoystick.vjCanvasContext.stroke();
  106414. VirtualJoystick.vjCanvasContext.closePath();
  106415. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  106416. }
  106417. else {
  106418. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106419. VirtualJoystick.vjCanvasContext.beginPath();
  106420. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  106421. VirtualJoystick.vjCanvasContext.beginPath();
  106422. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  106423. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106424. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  106425. VirtualJoystick.vjCanvasContext.stroke();
  106426. VirtualJoystick.vjCanvasContext.closePath();
  106427. touch.prevX = touch.x;
  106428. touch.prevY = touch.y;
  106429. }
  106430. });
  106431. }
  106432. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106433. };
  106434. /**
  106435. * Release internal HTML canvas
  106436. */
  106437. VirtualJoystick.prototype.releaseCanvas = function () {
  106438. if (VirtualJoystick.vjCanvas) {
  106439. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  106440. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  106441. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  106442. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  106443. window.removeEventListener("resize", this._onResize);
  106444. document.body.removeChild(VirtualJoystick.vjCanvas);
  106445. VirtualJoystick.vjCanvas = null;
  106446. }
  106447. };
  106448. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  106449. VirtualJoystick._globalJoystickIndex = 0;
  106450. return VirtualJoystick;
  106451. }());
  106452. BABYLON.VirtualJoystick = VirtualJoystick;
  106453. })(BABYLON || (BABYLON = {}));
  106454. //# sourceMappingURL=babylon.virtualJoystick.js.map
  106455. var BABYLON;
  106456. (function (BABYLON) {
  106457. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  106458. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  106459. });
  106460. /**
  106461. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  106462. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106463. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106464. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106465. */
  106466. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  106467. __extends(VirtualJoysticksCamera, _super);
  106468. /**
  106469. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  106470. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106471. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106472. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106473. * @param name Define the name of the camera in the scene
  106474. * @param position Define the start position of the camera in the scene
  106475. * @param scene Define the scene the camera belongs to
  106476. */
  106477. function VirtualJoysticksCamera(name, position, scene) {
  106478. var _this = _super.call(this, name, position, scene) || this;
  106479. _this.inputs.addVirtualJoystick();
  106480. return _this;
  106481. }
  106482. /**
  106483. * Gets the current object class name.
  106484. * @return the class name
  106485. */
  106486. VirtualJoysticksCamera.prototype.getClassName = function () {
  106487. return "VirtualJoysticksCamera";
  106488. };
  106489. return VirtualJoysticksCamera;
  106490. }(BABYLON.FreeCamera));
  106491. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  106492. })(BABYLON || (BABYLON = {}));
  106493. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  106494. var BABYLON;
  106495. (function (BABYLON) {
  106496. /**
  106497. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  106498. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  106499. */
  106500. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  106501. function FreeCameraVirtualJoystickInput() {
  106502. }
  106503. /**
  106504. * Gets the left stick of the virtual joystick.
  106505. * @returns The virtual Joystick
  106506. */
  106507. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  106508. return this._leftjoystick;
  106509. };
  106510. /**
  106511. * Gets the right stick of the virtual joystick.
  106512. * @returns The virtual Joystick
  106513. */
  106514. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  106515. return this._rightjoystick;
  106516. };
  106517. /**
  106518. * Update the current camera state depending on the inputs that have been used this frame.
  106519. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  106520. */
  106521. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  106522. if (this._leftjoystick) {
  106523. var camera = this.camera;
  106524. var speed = camera._computeLocalCameraSpeed() * 50;
  106525. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  106526. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  106527. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  106528. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  106529. if (!this._leftjoystick.pressed) {
  106530. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  106531. }
  106532. if (!this._rightjoystick.pressed) {
  106533. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  106534. }
  106535. }
  106536. };
  106537. /**
  106538. * Attach the input controls to a specific dom element to get the input from.
  106539. * @param element Defines the element the controls should be listened from
  106540. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  106541. */
  106542. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  106543. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  106544. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  106545. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  106546. this._leftjoystick.setJoystickSensibility(0.15);
  106547. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  106548. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  106549. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  106550. this._rightjoystick.reverseUpDown = true;
  106551. this._rightjoystick.setJoystickSensibility(0.05);
  106552. this._rightjoystick.setJoystickColor("yellow");
  106553. };
  106554. /**
  106555. * Detach the current controls from the specified dom element.
  106556. * @param element Defines the element to stop listening the inputs from
  106557. */
  106558. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  106559. this._leftjoystick.releaseCanvas();
  106560. this._rightjoystick.releaseCanvas();
  106561. };
  106562. /**
  106563. * Gets the class name of the current intput.
  106564. * @returns the class name
  106565. */
  106566. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  106567. return "FreeCameraVirtualJoystickInput";
  106568. };
  106569. /**
  106570. * Get the friendly name associated with the input class.
  106571. * @returns the input friendly name
  106572. */
  106573. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  106574. return "virtualJoystick";
  106575. };
  106576. return FreeCameraVirtualJoystickInput;
  106577. }());
  106578. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  106579. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  106580. })(BABYLON || (BABYLON = {}));
  106581. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  106582. var BABYLON;
  106583. (function (BABYLON) {
  106584. /**
  106585. * Class used to specify simplification options
  106586. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106587. */
  106588. var SimplificationSettings = /** @class */ (function () {
  106589. /**
  106590. * Creates a SimplificationSettings
  106591. * @param quality expected quality
  106592. * @param distance distance when this optimized version should be used
  106593. * @param optimizeMesh already optimized mesh
  106594. */
  106595. function SimplificationSettings(
  106596. /** expected quality */
  106597. quality,
  106598. /** distance when this optimized version should be used */
  106599. distance,
  106600. /** already optimized mesh */
  106601. optimizeMesh) {
  106602. this.quality = quality;
  106603. this.distance = distance;
  106604. this.optimizeMesh = optimizeMesh;
  106605. }
  106606. return SimplificationSettings;
  106607. }());
  106608. BABYLON.SimplificationSettings = SimplificationSettings;
  106609. /**
  106610. * Queue used to order the simplification tasks
  106611. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106612. */
  106613. var SimplificationQueue = /** @class */ (function () {
  106614. /**
  106615. * Creates a new queue
  106616. */
  106617. function SimplificationQueue() {
  106618. this.running = false;
  106619. this._simplificationArray = [];
  106620. }
  106621. /**
  106622. * Adds a new simplification task
  106623. * @param task defines a task to add
  106624. */
  106625. SimplificationQueue.prototype.addTask = function (task) {
  106626. this._simplificationArray.push(task);
  106627. };
  106628. /**
  106629. * Execute next task
  106630. */
  106631. SimplificationQueue.prototype.executeNext = function () {
  106632. var task = this._simplificationArray.pop();
  106633. if (task) {
  106634. this.running = true;
  106635. this.runSimplification(task);
  106636. }
  106637. else {
  106638. this.running = false;
  106639. }
  106640. };
  106641. /**
  106642. * Execute a simplification task
  106643. * @param task defines the task to run
  106644. */
  106645. SimplificationQueue.prototype.runSimplification = function (task) {
  106646. var _this = this;
  106647. if (task.parallelProcessing) {
  106648. //parallel simplifier
  106649. task.settings.forEach(function (setting) {
  106650. var simplifier = _this.getSimplifier(task);
  106651. simplifier.simplify(setting, function (newMesh) {
  106652. task.mesh.addLODLevel(setting.distance, newMesh);
  106653. newMesh.isVisible = true;
  106654. //check if it is the last
  106655. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  106656. //all done, run the success callback.
  106657. task.successCallback();
  106658. }
  106659. _this.executeNext();
  106660. });
  106661. });
  106662. }
  106663. else {
  106664. //single simplifier.
  106665. var simplifier = this.getSimplifier(task);
  106666. var runDecimation = function (setting, callback) {
  106667. simplifier.simplify(setting, function (newMesh) {
  106668. task.mesh.addLODLevel(setting.distance, newMesh);
  106669. newMesh.isVisible = true;
  106670. //run the next quality level
  106671. callback();
  106672. });
  106673. };
  106674. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  106675. runDecimation(task.settings[loop.index], function () {
  106676. loop.executeNext();
  106677. });
  106678. }, function () {
  106679. //execution ended, run the success callback.
  106680. if (task.successCallback) {
  106681. task.successCallback();
  106682. }
  106683. _this.executeNext();
  106684. });
  106685. }
  106686. };
  106687. SimplificationQueue.prototype.getSimplifier = function (task) {
  106688. switch (task.simplificationType) {
  106689. case SimplificationType.QUADRATIC:
  106690. default:
  106691. return new QuadraticErrorSimplification(task.mesh);
  106692. }
  106693. };
  106694. return SimplificationQueue;
  106695. }());
  106696. BABYLON.SimplificationQueue = SimplificationQueue;
  106697. /**
  106698. * The implemented types of simplification
  106699. * At the moment only Quadratic Error Decimation is implemented
  106700. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106701. */
  106702. var SimplificationType;
  106703. (function (SimplificationType) {
  106704. /** Quadratic error decimation */
  106705. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  106706. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  106707. var DecimationTriangle = /** @class */ (function () {
  106708. function DecimationTriangle(vertices) {
  106709. this.vertices = vertices;
  106710. this.error = new Array(4);
  106711. this.deleted = false;
  106712. this.isDirty = false;
  106713. this.deletePending = false;
  106714. this.borderFactor = 0;
  106715. }
  106716. return DecimationTriangle;
  106717. }());
  106718. var DecimationVertex = /** @class */ (function () {
  106719. function DecimationVertex(position, id) {
  106720. this.position = position;
  106721. this.id = id;
  106722. this.isBorder = true;
  106723. this.q = new QuadraticMatrix();
  106724. this.triangleCount = 0;
  106725. this.triangleStart = 0;
  106726. this.originalOffsets = [];
  106727. }
  106728. DecimationVertex.prototype.updatePosition = function (newPosition) {
  106729. this.position.copyFrom(newPosition);
  106730. };
  106731. return DecimationVertex;
  106732. }());
  106733. var QuadraticMatrix = /** @class */ (function () {
  106734. function QuadraticMatrix(data) {
  106735. this.data = new Array(10);
  106736. for (var i = 0; i < 10; ++i) {
  106737. if (data && data[i]) {
  106738. this.data[i] = data[i];
  106739. }
  106740. else {
  106741. this.data[i] = 0;
  106742. }
  106743. }
  106744. }
  106745. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  106746. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  106747. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  106748. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  106749. return det;
  106750. };
  106751. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  106752. for (var i = 0; i < 10; ++i) {
  106753. this.data[i] += matrix.data[i];
  106754. }
  106755. };
  106756. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  106757. for (var i = 0; i < 10; ++i) {
  106758. this.data[i] += data[i];
  106759. }
  106760. };
  106761. QuadraticMatrix.prototype.add = function (matrix) {
  106762. var m = new QuadraticMatrix();
  106763. for (var i = 0; i < 10; ++i) {
  106764. m.data[i] = this.data[i] + matrix.data[i];
  106765. }
  106766. return m;
  106767. };
  106768. QuadraticMatrix.FromData = function (a, b, c, d) {
  106769. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  106770. };
  106771. //returning an array to avoid garbage collection
  106772. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  106773. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  106774. };
  106775. return QuadraticMatrix;
  106776. }());
  106777. var Reference = /** @class */ (function () {
  106778. function Reference(vertexId, triangleId) {
  106779. this.vertexId = vertexId;
  106780. this.triangleId = triangleId;
  106781. }
  106782. return Reference;
  106783. }());
  106784. /**
  106785. * An implementation of the Quadratic Error simplification algorithm.
  106786. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  106787. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  106788. * @author RaananW
  106789. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106790. */
  106791. var QuadraticErrorSimplification = /** @class */ (function () {
  106792. function QuadraticErrorSimplification(_mesh) {
  106793. this._mesh = _mesh;
  106794. this.syncIterations = 5000;
  106795. this.aggressiveness = 7;
  106796. this.decimationIterations = 100;
  106797. this.boundingBoxEpsilon = BABYLON.Epsilon;
  106798. }
  106799. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  106800. var _this = this;
  106801. this.initDecimatedMesh();
  106802. //iterating through the submeshes array, one after the other.
  106803. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  106804. _this.initWithMesh(loop.index, function () {
  106805. _this.runDecimation(settings, loop.index, function () {
  106806. loop.executeNext();
  106807. });
  106808. }, settings.optimizeMesh);
  106809. }, function () {
  106810. setTimeout(function () {
  106811. successCallback(_this._reconstructedMesh);
  106812. }, 0);
  106813. });
  106814. };
  106815. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  106816. var _this = this;
  106817. var targetCount = ~~(this.triangles.length * settings.quality);
  106818. var deletedTriangles = 0;
  106819. var triangleCount = this.triangles.length;
  106820. var iterationFunction = function (iteration, callback) {
  106821. setTimeout(function () {
  106822. if (iteration % 5 === 0) {
  106823. _this.updateMesh(iteration === 0);
  106824. }
  106825. for (var i = 0; i < _this.triangles.length; ++i) {
  106826. _this.triangles[i].isDirty = false;
  106827. }
  106828. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  106829. var trianglesIterator = function (i) {
  106830. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  106831. var t = _this.triangles[tIdx];
  106832. if (!t) {
  106833. return;
  106834. }
  106835. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  106836. return;
  106837. }
  106838. for (var j = 0; j < 3; ++j) {
  106839. if (t.error[j] < threshold) {
  106840. var deleted0 = [];
  106841. var deleted1 = [];
  106842. var v0 = t.vertices[j];
  106843. var v1 = t.vertices[(j + 1) % 3];
  106844. if (v0.isBorder || v1.isBorder) {
  106845. continue;
  106846. }
  106847. var p = BABYLON.Vector3.Zero();
  106848. var n = BABYLON.Vector3.Zero();
  106849. var uv = BABYLON.Vector2.Zero();
  106850. var color = new BABYLON.Color4(0, 0, 0, 1);
  106851. _this.calculateError(v0, v1, p, n, uv, color);
  106852. var delTr = new Array();
  106853. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  106854. continue;
  106855. }
  106856. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  106857. continue;
  106858. }
  106859. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  106860. continue;
  106861. }
  106862. var uniqueArray = new Array();
  106863. delTr.forEach(function (deletedT) {
  106864. if (uniqueArray.indexOf(deletedT) === -1) {
  106865. deletedT.deletePending = true;
  106866. uniqueArray.push(deletedT);
  106867. }
  106868. });
  106869. if (uniqueArray.length % 2 !== 0) {
  106870. continue;
  106871. }
  106872. v0.q = v1.q.add(v0.q);
  106873. v0.updatePosition(p);
  106874. var tStart = _this.references.length;
  106875. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  106876. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  106877. var tCount = _this.references.length - tStart;
  106878. if (tCount <= v0.triangleCount) {
  106879. if (tCount) {
  106880. for (var c = 0; c < tCount; c++) {
  106881. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  106882. }
  106883. }
  106884. }
  106885. else {
  106886. v0.triangleStart = tStart;
  106887. }
  106888. v0.triangleCount = tCount;
  106889. break;
  106890. }
  106891. }
  106892. };
  106893. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  106894. }, 0);
  106895. };
  106896. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  106897. if (triangleCount - deletedTriangles <= targetCount) {
  106898. loop.breakLoop();
  106899. }
  106900. else {
  106901. iterationFunction(loop.index, function () {
  106902. loop.executeNext();
  106903. });
  106904. }
  106905. }, function () {
  106906. setTimeout(function () {
  106907. //reconstruct this part of the mesh
  106908. _this.reconstructMesh(submeshIndex);
  106909. successCallback();
  106910. }, 0);
  106911. });
  106912. };
  106913. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  106914. var _this = this;
  106915. this.vertices = [];
  106916. this.triangles = [];
  106917. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106918. var indices = this._mesh.getIndices();
  106919. var submesh = this._mesh.subMeshes[submeshIndex];
  106920. var findInVertices = function (positionToSearch) {
  106921. if (optimizeMesh) {
  106922. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  106923. if (_this.vertices[ii].position.equals(positionToSearch)) {
  106924. return _this.vertices[ii];
  106925. }
  106926. }
  106927. }
  106928. return null;
  106929. };
  106930. var vertexReferences = [];
  106931. var vertexInit = function (i) {
  106932. if (!positionData) {
  106933. return;
  106934. }
  106935. var offset = i + submesh.verticesStart;
  106936. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  106937. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  106938. vertex.originalOffsets.push(offset);
  106939. if (vertex.id === _this.vertices.length) {
  106940. _this.vertices.push(vertex);
  106941. }
  106942. vertexReferences.push(vertex.id);
  106943. };
  106944. //var totalVertices = mesh.getTotalVertices();
  106945. var totalVertices = submesh.verticesCount;
  106946. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  106947. var indicesInit = function (i) {
  106948. if (!indices) {
  106949. return;
  106950. }
  106951. var offset = (submesh.indexStart / 3) + i;
  106952. var pos = (offset * 3);
  106953. var i0 = indices[pos + 0];
  106954. var i1 = indices[pos + 1];
  106955. var i2 = indices[pos + 2];
  106956. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  106957. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  106958. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  106959. var triangle = new DecimationTriangle([v0, v1, v2]);
  106960. triangle.originalOffset = pos;
  106961. _this.triangles.push(triangle);
  106962. };
  106963. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  106964. _this.init(callback);
  106965. });
  106966. });
  106967. };
  106968. QuadraticErrorSimplification.prototype.init = function (callback) {
  106969. var _this = this;
  106970. var triangleInit1 = function (i) {
  106971. var t = _this.triangles[i];
  106972. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  106973. for (var j = 0; j < 3; j++) {
  106974. 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))));
  106975. }
  106976. };
  106977. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  106978. var triangleInit2 = function (i) {
  106979. var t = _this.triangles[i];
  106980. for (var j = 0; j < 3; ++j) {
  106981. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  106982. }
  106983. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  106984. };
  106985. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  106986. callback();
  106987. });
  106988. });
  106989. };
  106990. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  106991. var newTriangles = [];
  106992. var i;
  106993. for (i = 0; i < this.vertices.length; ++i) {
  106994. this.vertices[i].triangleCount = 0;
  106995. }
  106996. var t;
  106997. var j;
  106998. for (i = 0; i < this.triangles.length; ++i) {
  106999. if (!this.triangles[i].deleted) {
  107000. t = this.triangles[i];
  107001. for (j = 0; j < 3; ++j) {
  107002. t.vertices[j].triangleCount = 1;
  107003. }
  107004. newTriangles.push(t);
  107005. }
  107006. }
  107007. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  107008. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  107009. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  107010. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  107011. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  107012. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  107013. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  107014. var vertexCount = 0;
  107015. for (i = 0; i < this.vertices.length; ++i) {
  107016. var vertex = this.vertices[i];
  107017. vertex.id = vertexCount;
  107018. if (vertex.triangleCount) {
  107019. vertex.originalOffsets.forEach(function (originalOffset) {
  107020. if (!normalData) {
  107021. return;
  107022. }
  107023. newPositionData.push(vertex.position.x);
  107024. newPositionData.push(vertex.position.y);
  107025. newPositionData.push(vertex.position.z);
  107026. newNormalData.push(normalData[originalOffset * 3]);
  107027. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  107028. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  107029. if (uvs && uvs.length) {
  107030. newUVsData.push(uvs[(originalOffset * 2)]);
  107031. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  107032. }
  107033. else if (colorsData && colorsData.length) {
  107034. newColorsData.push(colorsData[(originalOffset * 4)]);
  107035. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  107036. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  107037. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  107038. }
  107039. ++vertexCount;
  107040. });
  107041. }
  107042. }
  107043. var startingIndex = this._reconstructedMesh.getTotalIndices();
  107044. var startingVertex = this._reconstructedMesh.getTotalVertices();
  107045. var submeshesArray = this._reconstructedMesh.subMeshes;
  107046. this._reconstructedMesh.subMeshes = [];
  107047. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  107048. var originalIndices = this._mesh.getIndices();
  107049. for (i = 0; i < newTriangles.length; ++i) {
  107050. t = newTriangles[i]; //now get the new referencing point for each vertex
  107051. [0, 1, 2].forEach(function (idx) {
  107052. var id = originalIndices[t.originalOffset + idx];
  107053. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  107054. if (offset < 0) {
  107055. offset = 0;
  107056. }
  107057. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  107058. });
  107059. }
  107060. //overwriting the old vertex buffers and indices.
  107061. this._reconstructedMesh.setIndices(newIndicesArray);
  107062. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  107063. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  107064. if (newUVsData.length > 0) {
  107065. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  107066. }
  107067. if (newColorsData.length > 0) {
  107068. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  107069. }
  107070. //create submesh
  107071. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  107072. if (submeshIndex > 0) {
  107073. this._reconstructedMesh.subMeshes = [];
  107074. submeshesArray.forEach(function (submesh) {
  107075. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  107076. });
  107077. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  107078. }
  107079. };
  107080. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  107081. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  107082. this._reconstructedMesh.material = this._mesh.material;
  107083. this._reconstructedMesh.parent = this._mesh.parent;
  107084. this._reconstructedMesh.isVisible = false;
  107085. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  107086. };
  107087. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  107088. for (var i = 0; i < vertex1.triangleCount; ++i) {
  107089. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  107090. if (t.deleted) {
  107091. continue;
  107092. }
  107093. var s = this.references[vertex1.triangleStart + i].vertexId;
  107094. var v1 = t.vertices[(s + 1) % 3];
  107095. var v2 = t.vertices[(s + 2) % 3];
  107096. if ((v1 === vertex2 || v2 === vertex2)) {
  107097. deletedArray[i] = true;
  107098. delTr.push(t);
  107099. continue;
  107100. }
  107101. var d1 = v1.position.subtract(point);
  107102. d1 = d1.normalize();
  107103. var d2 = v2.position.subtract(point);
  107104. d2 = d2.normalize();
  107105. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  107106. return true;
  107107. }
  107108. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  107109. deletedArray[i] = false;
  107110. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  107111. return true;
  107112. }
  107113. }
  107114. return false;
  107115. };
  107116. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  107117. var newDeleted = deletedTriangles;
  107118. for (var i = 0; i < vertex.triangleCount; ++i) {
  107119. var ref = this.references[vertex.triangleStart + i];
  107120. var t = this.triangles[ref.triangleId];
  107121. if (t.deleted) {
  107122. continue;
  107123. }
  107124. if (deletedArray[i] && t.deletePending) {
  107125. t.deleted = true;
  107126. newDeleted++;
  107127. continue;
  107128. }
  107129. t.vertices[ref.vertexId] = origVertex;
  107130. t.isDirty = true;
  107131. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  107132. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  107133. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  107134. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  107135. this.references.push(ref);
  107136. }
  107137. return newDeleted;
  107138. };
  107139. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  107140. for (var i = 0; i < this.vertices.length; ++i) {
  107141. var vCount = [];
  107142. var vId = [];
  107143. var v = this.vertices[i];
  107144. var j;
  107145. for (j = 0; j < v.triangleCount; ++j) {
  107146. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  107147. for (var ii = 0; ii < 3; ii++) {
  107148. var ofs = 0;
  107149. var vv = triangle.vertices[ii];
  107150. while (ofs < vCount.length) {
  107151. if (vId[ofs] === vv.id) {
  107152. break;
  107153. }
  107154. ++ofs;
  107155. }
  107156. if (ofs === vCount.length) {
  107157. vCount.push(1);
  107158. vId.push(vv.id);
  107159. }
  107160. else {
  107161. vCount[ofs]++;
  107162. }
  107163. }
  107164. }
  107165. for (j = 0; j < vCount.length; ++j) {
  107166. if (vCount[j] === 1) {
  107167. this.vertices[vId[j]].isBorder = true;
  107168. }
  107169. else {
  107170. this.vertices[vId[j]].isBorder = false;
  107171. }
  107172. }
  107173. }
  107174. };
  107175. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  107176. if (identifyBorders === void 0) { identifyBorders = false; }
  107177. var i;
  107178. if (!identifyBorders) {
  107179. var newTrianglesVector = [];
  107180. for (i = 0; i < this.triangles.length; ++i) {
  107181. if (!this.triangles[i].deleted) {
  107182. newTrianglesVector.push(this.triangles[i]);
  107183. }
  107184. }
  107185. this.triangles = newTrianglesVector;
  107186. }
  107187. for (i = 0; i < this.vertices.length; ++i) {
  107188. this.vertices[i].triangleCount = 0;
  107189. this.vertices[i].triangleStart = 0;
  107190. }
  107191. var t;
  107192. var j;
  107193. var v;
  107194. for (i = 0; i < this.triangles.length; ++i) {
  107195. t = this.triangles[i];
  107196. for (j = 0; j < 3; ++j) {
  107197. v = t.vertices[j];
  107198. v.triangleCount++;
  107199. }
  107200. }
  107201. var tStart = 0;
  107202. for (i = 0; i < this.vertices.length; ++i) {
  107203. this.vertices[i].triangleStart = tStart;
  107204. tStart += this.vertices[i].triangleCount;
  107205. this.vertices[i].triangleCount = 0;
  107206. }
  107207. var newReferences = new Array(this.triangles.length * 3);
  107208. for (i = 0; i < this.triangles.length; ++i) {
  107209. t = this.triangles[i];
  107210. for (j = 0; j < 3; ++j) {
  107211. v = t.vertices[j];
  107212. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  107213. v.triangleCount++;
  107214. }
  107215. }
  107216. this.references = newReferences;
  107217. if (identifyBorders) {
  107218. this.identifyBorder();
  107219. }
  107220. };
  107221. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  107222. var x = point.x;
  107223. var y = point.y;
  107224. var z = point.z;
  107225. 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
  107226. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  107227. };
  107228. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  107229. var q = vertex1.q.add(vertex2.q);
  107230. var border = vertex1.isBorder && vertex2.isBorder;
  107231. var error = 0;
  107232. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  107233. if (qDet !== 0 && !border) {
  107234. if (!pointResult) {
  107235. pointResult = BABYLON.Vector3.Zero();
  107236. }
  107237. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  107238. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  107239. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  107240. error = this.vertexError(q, pointResult);
  107241. }
  107242. else {
  107243. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  107244. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  107245. var error1 = this.vertexError(q, vertex1.position);
  107246. var error2 = this.vertexError(q, vertex2.position);
  107247. var error3 = this.vertexError(q, p3);
  107248. error = Math.min(error1, error2, error3);
  107249. if (error === error1) {
  107250. if (pointResult) {
  107251. pointResult.copyFrom(vertex1.position);
  107252. }
  107253. }
  107254. else if (error === error2) {
  107255. if (pointResult) {
  107256. pointResult.copyFrom(vertex2.position);
  107257. }
  107258. }
  107259. else {
  107260. if (pointResult) {
  107261. pointResult.copyFrom(p3);
  107262. }
  107263. }
  107264. }
  107265. return error;
  107266. };
  107267. return QuadraticErrorSimplification;
  107268. }());
  107269. })(BABYLON || (BABYLON = {}));
  107270. //# sourceMappingURL=babylon.meshSimplification.js.map
  107271. var BABYLON;
  107272. (function (BABYLON) {
  107273. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  107274. get: function () {
  107275. if (!this._simplificationQueue) {
  107276. this._simplificationQueue = new BABYLON.SimplificationQueue();
  107277. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  107278. if (!component) {
  107279. component = new SimplicationQueueSceneComponent(this);
  107280. this._addComponent(component);
  107281. }
  107282. }
  107283. return this._simplificationQueue;
  107284. },
  107285. set: function (value) {
  107286. this._simplificationQueue = value;
  107287. },
  107288. enumerable: true,
  107289. configurable: true
  107290. });
  107291. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  107292. if (parallelProcessing === void 0) { parallelProcessing = true; }
  107293. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  107294. this.getScene().simplificationQueue.addTask({
  107295. settings: settings,
  107296. parallelProcessing: parallelProcessing,
  107297. mesh: this,
  107298. simplificationType: simplificationType,
  107299. successCallback: successCallback
  107300. });
  107301. return this;
  107302. };
  107303. /**
  107304. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  107305. * created in a scene
  107306. */
  107307. var SimplicationQueueSceneComponent = /** @class */ (function () {
  107308. /**
  107309. * Creates a new instance of the component for the given scene
  107310. * @param scene Defines the scene to register the component in
  107311. */
  107312. function SimplicationQueueSceneComponent(scene) {
  107313. /**
  107314. * The component name helpfull to identify the component in the list of scene components.
  107315. */
  107316. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  107317. this.scene = scene;
  107318. }
  107319. /**
  107320. * Registers the component in a given scene
  107321. */
  107322. SimplicationQueueSceneComponent.prototype.register = function () {
  107323. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  107324. };
  107325. /**
  107326. * Rebuilds the elements related to this component in case of
  107327. * context lost for instance.
  107328. */
  107329. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  107330. // Nothing to do for this component
  107331. };
  107332. /**
  107333. * Disposes the component and the associated ressources
  107334. */
  107335. SimplicationQueueSceneComponent.prototype.dispose = function () {
  107336. // Nothing to do for this component
  107337. };
  107338. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  107339. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  107340. this.scene._simplificationQueue.executeNext();
  107341. }
  107342. };
  107343. return SimplicationQueueSceneComponent;
  107344. }());
  107345. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  107346. })(BABYLON || (BABYLON = {}));
  107347. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  107348. var BABYLON;
  107349. (function (BABYLON) {
  107350. /**
  107351. * Class used to represent a specific level of detail of a mesh
  107352. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  107353. */
  107354. var MeshLODLevel = /** @class */ (function () {
  107355. /**
  107356. * Creates a new LOD level
  107357. * @param distance defines the distance where this level should star being displayed
  107358. * @param mesh defines the mesh to use to render this level
  107359. */
  107360. function MeshLODLevel(
  107361. /** Defines the distance where this level should star being displayed */
  107362. distance,
  107363. /** Defines the mesh to use to render this level */
  107364. mesh) {
  107365. this.distance = distance;
  107366. this.mesh = mesh;
  107367. }
  107368. return MeshLODLevel;
  107369. }());
  107370. BABYLON.MeshLODLevel = MeshLODLevel;
  107371. })(BABYLON || (BABYLON = {}));
  107372. //# sourceMappingURL=babylon.meshLODLevel.js.map
  107373. var BABYLON;
  107374. (function (BABYLON) {
  107375. /**
  107376. * Defines the root class used to create scene optimization to use with SceneOptimizer
  107377. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107378. */
  107379. var SceneOptimization = /** @class */ (function () {
  107380. /**
  107381. * Creates the SceneOptimization object
  107382. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107383. * @param desc defines the description associated with the optimization
  107384. */
  107385. function SceneOptimization(
  107386. /**
  107387. * Defines the priority of this optimization (0 by default which means first in the list)
  107388. */
  107389. priority) {
  107390. if (priority === void 0) { priority = 0; }
  107391. this.priority = priority;
  107392. }
  107393. /**
  107394. * Gets a string describing the action executed by the current optimization
  107395. * @returns description string
  107396. */
  107397. SceneOptimization.prototype.getDescription = function () {
  107398. return "";
  107399. };
  107400. /**
  107401. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107402. * @param scene defines the current scene where to apply this optimization
  107403. * @param optimizer defines the current optimizer
  107404. * @returns true if everything that can be done was applied
  107405. */
  107406. SceneOptimization.prototype.apply = function (scene, optimizer) {
  107407. return true;
  107408. };
  107409. return SceneOptimization;
  107410. }());
  107411. BABYLON.SceneOptimization = SceneOptimization;
  107412. /**
  107413. * Defines an optimization used to reduce the size of render target textures
  107414. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107415. */
  107416. var TextureOptimization = /** @class */ (function (_super) {
  107417. __extends(TextureOptimization, _super);
  107418. /**
  107419. * Creates the TextureOptimization object
  107420. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107421. * @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
  107422. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107423. */
  107424. function TextureOptimization(
  107425. /**
  107426. * Defines the priority of this optimization (0 by default which means first in the list)
  107427. */
  107428. priority,
  107429. /**
  107430. * 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
  107431. */
  107432. maximumSize,
  107433. /**
  107434. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107435. */
  107436. step) {
  107437. if (priority === void 0) { priority = 0; }
  107438. if (maximumSize === void 0) { maximumSize = 1024; }
  107439. if (step === void 0) { step = 0.5; }
  107440. var _this = _super.call(this, priority) || this;
  107441. _this.priority = priority;
  107442. _this.maximumSize = maximumSize;
  107443. _this.step = step;
  107444. return _this;
  107445. }
  107446. /**
  107447. * Gets a string describing the action executed by the current optimization
  107448. * @returns description string
  107449. */
  107450. TextureOptimization.prototype.getDescription = function () {
  107451. return "Reducing render target texture size to " + this.maximumSize;
  107452. };
  107453. /**
  107454. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107455. * @param scene defines the current scene where to apply this optimization
  107456. * @param optimizer defines the current optimizer
  107457. * @returns true if everything that can be done was applied
  107458. */
  107459. TextureOptimization.prototype.apply = function (scene, optimizer) {
  107460. var allDone = true;
  107461. for (var index = 0; index < scene.textures.length; index++) {
  107462. var texture = scene.textures[index];
  107463. if (!texture.canRescale || texture.getContext) {
  107464. continue;
  107465. }
  107466. var currentSize = texture.getSize();
  107467. var maxDimension = Math.max(currentSize.width, currentSize.height);
  107468. if (maxDimension > this.maximumSize) {
  107469. texture.scale(this.step);
  107470. allDone = false;
  107471. }
  107472. }
  107473. return allDone;
  107474. };
  107475. return TextureOptimization;
  107476. }(SceneOptimization));
  107477. BABYLON.TextureOptimization = TextureOptimization;
  107478. /**
  107479. * Defines an optimization used to increase or decrease the rendering resolution
  107480. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107481. */
  107482. var HardwareScalingOptimization = /** @class */ (function (_super) {
  107483. __extends(HardwareScalingOptimization, _super);
  107484. /**
  107485. * Creates the HardwareScalingOptimization object
  107486. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107487. * @param maximumScale defines the maximum scale to use (2 by default)
  107488. * @param step defines the step to use between two passes (0.5 by default)
  107489. */
  107490. function HardwareScalingOptimization(
  107491. /**
  107492. * Defines the priority of this optimization (0 by default which means first in the list)
  107493. */
  107494. priority,
  107495. /**
  107496. * Defines the maximum scale to use (2 by default)
  107497. */
  107498. maximumScale,
  107499. /**
  107500. * Defines the step to use between two passes (0.5 by default)
  107501. */
  107502. step) {
  107503. if (priority === void 0) { priority = 0; }
  107504. if (maximumScale === void 0) { maximumScale = 2; }
  107505. if (step === void 0) { step = 0.25; }
  107506. var _this = _super.call(this, priority) || this;
  107507. _this.priority = priority;
  107508. _this.maximumScale = maximumScale;
  107509. _this.step = step;
  107510. _this._currentScale = -1;
  107511. _this._directionOffset = 1;
  107512. return _this;
  107513. }
  107514. /**
  107515. * Gets a string describing the action executed by the current optimization
  107516. * @return description string
  107517. */
  107518. HardwareScalingOptimization.prototype.getDescription = function () {
  107519. return "Setting hardware scaling level to " + this._currentScale;
  107520. };
  107521. /**
  107522. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107523. * @param scene defines the current scene where to apply this optimization
  107524. * @param optimizer defines the current optimizer
  107525. * @returns true if everything that can be done was applied
  107526. */
  107527. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  107528. if (this._currentScale === -1) {
  107529. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  107530. if (this._currentScale > this.maximumScale) {
  107531. this._directionOffset = -1;
  107532. }
  107533. }
  107534. this._currentScale += this._directionOffset * this.step;
  107535. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  107536. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  107537. };
  107538. return HardwareScalingOptimization;
  107539. }(SceneOptimization));
  107540. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  107541. /**
  107542. * Defines an optimization used to remove shadows
  107543. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107544. */
  107545. var ShadowsOptimization = /** @class */ (function (_super) {
  107546. __extends(ShadowsOptimization, _super);
  107547. function ShadowsOptimization() {
  107548. return _super !== null && _super.apply(this, arguments) || this;
  107549. }
  107550. /**
  107551. * Gets a string describing the action executed by the current optimization
  107552. * @return description string
  107553. */
  107554. ShadowsOptimization.prototype.getDescription = function () {
  107555. return "Turning shadows on/off";
  107556. };
  107557. /**
  107558. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107559. * @param scene defines the current scene where to apply this optimization
  107560. * @param optimizer defines the current optimizer
  107561. * @returns true if everything that can be done was applied
  107562. */
  107563. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  107564. scene.shadowsEnabled = optimizer.isInImprovementMode;
  107565. return true;
  107566. };
  107567. return ShadowsOptimization;
  107568. }(SceneOptimization));
  107569. BABYLON.ShadowsOptimization = ShadowsOptimization;
  107570. /**
  107571. * Defines an optimization used to turn post-processes off
  107572. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107573. */
  107574. var PostProcessesOptimization = /** @class */ (function (_super) {
  107575. __extends(PostProcessesOptimization, _super);
  107576. function PostProcessesOptimization() {
  107577. return _super !== null && _super.apply(this, arguments) || this;
  107578. }
  107579. /**
  107580. * Gets a string describing the action executed by the current optimization
  107581. * @return description string
  107582. */
  107583. PostProcessesOptimization.prototype.getDescription = function () {
  107584. return "Turning post-processes on/off";
  107585. };
  107586. /**
  107587. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107588. * @param scene defines the current scene where to apply this optimization
  107589. * @param optimizer defines the current optimizer
  107590. * @returns true if everything that can be done was applied
  107591. */
  107592. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  107593. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  107594. return true;
  107595. };
  107596. return PostProcessesOptimization;
  107597. }(SceneOptimization));
  107598. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  107599. /**
  107600. * Defines an optimization used to turn lens flares off
  107601. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107602. */
  107603. var LensFlaresOptimization = /** @class */ (function (_super) {
  107604. __extends(LensFlaresOptimization, _super);
  107605. function LensFlaresOptimization() {
  107606. return _super !== null && _super.apply(this, arguments) || this;
  107607. }
  107608. /**
  107609. * Gets a string describing the action executed by the current optimization
  107610. * @return description string
  107611. */
  107612. LensFlaresOptimization.prototype.getDescription = function () {
  107613. return "Turning lens flares on/off";
  107614. };
  107615. /**
  107616. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107617. * @param scene defines the current scene where to apply this optimization
  107618. * @param optimizer defines the current optimizer
  107619. * @returns true if everything that can be done was applied
  107620. */
  107621. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  107622. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  107623. return true;
  107624. };
  107625. return LensFlaresOptimization;
  107626. }(SceneOptimization));
  107627. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  107628. /**
  107629. * Defines an optimization based on user defined callback.
  107630. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107631. */
  107632. var CustomOptimization = /** @class */ (function (_super) {
  107633. __extends(CustomOptimization, _super);
  107634. function CustomOptimization() {
  107635. return _super !== null && _super.apply(this, arguments) || this;
  107636. }
  107637. /**
  107638. * Gets a string describing the action executed by the current optimization
  107639. * @returns description string
  107640. */
  107641. CustomOptimization.prototype.getDescription = function () {
  107642. if (this.onGetDescription) {
  107643. return this.onGetDescription();
  107644. }
  107645. return "Running user defined callback";
  107646. };
  107647. /**
  107648. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107649. * @param scene defines the current scene where to apply this optimization
  107650. * @param optimizer defines the current optimizer
  107651. * @returns true if everything that can be done was applied
  107652. */
  107653. CustomOptimization.prototype.apply = function (scene, optimizer) {
  107654. if (this.onApply) {
  107655. return this.onApply(scene, optimizer);
  107656. }
  107657. return true;
  107658. };
  107659. return CustomOptimization;
  107660. }(SceneOptimization));
  107661. BABYLON.CustomOptimization = CustomOptimization;
  107662. /**
  107663. * Defines an optimization used to turn particles off
  107664. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107665. */
  107666. var ParticlesOptimization = /** @class */ (function (_super) {
  107667. __extends(ParticlesOptimization, _super);
  107668. function ParticlesOptimization() {
  107669. return _super !== null && _super.apply(this, arguments) || this;
  107670. }
  107671. /**
  107672. * Gets a string describing the action executed by the current optimization
  107673. * @return description string
  107674. */
  107675. ParticlesOptimization.prototype.getDescription = function () {
  107676. return "Turning particles on/off";
  107677. };
  107678. /**
  107679. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107680. * @param scene defines the current scene where to apply this optimization
  107681. * @param optimizer defines the current optimizer
  107682. * @returns true if everything that can be done was applied
  107683. */
  107684. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  107685. scene.particlesEnabled = optimizer.isInImprovementMode;
  107686. return true;
  107687. };
  107688. return ParticlesOptimization;
  107689. }(SceneOptimization));
  107690. BABYLON.ParticlesOptimization = ParticlesOptimization;
  107691. /**
  107692. * Defines an optimization used to turn render targets off
  107693. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107694. */
  107695. var RenderTargetsOptimization = /** @class */ (function (_super) {
  107696. __extends(RenderTargetsOptimization, _super);
  107697. function RenderTargetsOptimization() {
  107698. return _super !== null && _super.apply(this, arguments) || this;
  107699. }
  107700. /**
  107701. * Gets a string describing the action executed by the current optimization
  107702. * @return description string
  107703. */
  107704. RenderTargetsOptimization.prototype.getDescription = function () {
  107705. return "Turning render targets off";
  107706. };
  107707. /**
  107708. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107709. * @param scene defines the current scene where to apply this optimization
  107710. * @param optimizer defines the current optimizer
  107711. * @returns true if everything that can be done was applied
  107712. */
  107713. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  107714. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  107715. return true;
  107716. };
  107717. return RenderTargetsOptimization;
  107718. }(SceneOptimization));
  107719. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  107720. /**
  107721. * Defines an optimization used to merge meshes with compatible materials
  107722. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107723. */
  107724. var MergeMeshesOptimization = /** @class */ (function (_super) {
  107725. __extends(MergeMeshesOptimization, _super);
  107726. function MergeMeshesOptimization() {
  107727. var _this = _super !== null && _super.apply(this, arguments) || this;
  107728. _this._canBeMerged = function (abstractMesh) {
  107729. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  107730. return false;
  107731. }
  107732. var mesh = abstractMesh;
  107733. if (mesh.isDisposed()) {
  107734. return false;
  107735. }
  107736. if (!mesh.isVisible || !mesh.isEnabled()) {
  107737. return false;
  107738. }
  107739. if (mesh.instances.length > 0) {
  107740. return false;
  107741. }
  107742. if (mesh.skeleton || mesh.hasLODLevels) {
  107743. return false;
  107744. }
  107745. return true;
  107746. };
  107747. return _this;
  107748. }
  107749. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  107750. /**
  107751. * Gets or sets a boolean which defines if optimization octree has to be updated
  107752. */
  107753. get: function () {
  107754. return MergeMeshesOptimization._UpdateSelectionTree;
  107755. },
  107756. /**
  107757. * Gets or sets a boolean which defines if optimization octree has to be updated
  107758. */
  107759. set: function (value) {
  107760. MergeMeshesOptimization._UpdateSelectionTree = value;
  107761. },
  107762. enumerable: true,
  107763. configurable: true
  107764. });
  107765. /**
  107766. * Gets a string describing the action executed by the current optimization
  107767. * @return description string
  107768. */
  107769. MergeMeshesOptimization.prototype.getDescription = function () {
  107770. return "Merging similar meshes together";
  107771. };
  107772. /**
  107773. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107774. * @param scene defines the current scene where to apply this optimization
  107775. * @param optimizer defines the current optimizer
  107776. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  107777. * @returns true if everything that can be done was applied
  107778. */
  107779. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  107780. var globalPool = scene.meshes.slice(0);
  107781. var globalLength = globalPool.length;
  107782. for (var index = 0; index < globalLength; index++) {
  107783. var currentPool = new Array();
  107784. var current = globalPool[index];
  107785. // Checks
  107786. if (!this._canBeMerged(current)) {
  107787. continue;
  107788. }
  107789. currentPool.push(current);
  107790. // Find compatible meshes
  107791. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  107792. var otherMesh = globalPool[subIndex];
  107793. if (!this._canBeMerged(otherMesh)) {
  107794. continue;
  107795. }
  107796. if (otherMesh.material !== current.material) {
  107797. continue;
  107798. }
  107799. if (otherMesh.checkCollisions !== current.checkCollisions) {
  107800. continue;
  107801. }
  107802. currentPool.push(otherMesh);
  107803. globalLength--;
  107804. globalPool.splice(subIndex, 1);
  107805. subIndex--;
  107806. }
  107807. if (currentPool.length < 2) {
  107808. continue;
  107809. }
  107810. // Merge meshes
  107811. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  107812. }
  107813. // Call the octree system optimization if it is defined.
  107814. var sceneAsAny = scene;
  107815. if (sceneAsAny.createOrUpdateSelectionOctree) {
  107816. if (updateSelectionTree != undefined) {
  107817. if (updateSelectionTree) {
  107818. sceneAsAny.createOrUpdateSelectionOctree();
  107819. }
  107820. }
  107821. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  107822. sceneAsAny.createOrUpdateSelectionOctree();
  107823. }
  107824. }
  107825. return true;
  107826. };
  107827. MergeMeshesOptimization._UpdateSelectionTree = false;
  107828. return MergeMeshesOptimization;
  107829. }(SceneOptimization));
  107830. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  107831. /**
  107832. * Defines a list of options used by SceneOptimizer
  107833. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107834. */
  107835. var SceneOptimizerOptions = /** @class */ (function () {
  107836. /**
  107837. * Creates a new list of options used by SceneOptimizer
  107838. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  107839. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  107840. */
  107841. function SceneOptimizerOptions(
  107842. /**
  107843. * Defines the target frame rate to reach (60 by default)
  107844. */
  107845. targetFrameRate,
  107846. /**
  107847. * Defines the interval between two checkes (2000ms by default)
  107848. */
  107849. trackerDuration) {
  107850. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  107851. if (trackerDuration === void 0) { trackerDuration = 2000; }
  107852. this.targetFrameRate = targetFrameRate;
  107853. this.trackerDuration = trackerDuration;
  107854. /**
  107855. * Gets the list of optimizations to apply
  107856. */
  107857. this.optimizations = new Array();
  107858. }
  107859. /**
  107860. * Add a new optimization
  107861. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  107862. * @returns the current SceneOptimizerOptions
  107863. */
  107864. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  107865. this.optimizations.push(optimization);
  107866. return this;
  107867. };
  107868. /**
  107869. * Add a new custom optimization
  107870. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  107871. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  107872. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107873. * @returns the current SceneOptimizerOptions
  107874. */
  107875. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  107876. if (priority === void 0) { priority = 0; }
  107877. var optimization = new CustomOptimization(priority);
  107878. optimization.onApply = onApply;
  107879. optimization.onGetDescription = onGetDescription;
  107880. this.optimizations.push(optimization);
  107881. return this;
  107882. };
  107883. /**
  107884. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  107885. * @param targetFrameRate defines the target frame rate (60 by default)
  107886. * @returns a SceneOptimizerOptions object
  107887. */
  107888. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  107889. var result = new SceneOptimizerOptions(targetFrameRate);
  107890. var priority = 0;
  107891. result.addOptimization(new MergeMeshesOptimization(priority));
  107892. result.addOptimization(new ShadowsOptimization(priority));
  107893. result.addOptimization(new LensFlaresOptimization(priority));
  107894. // Next priority
  107895. priority++;
  107896. result.addOptimization(new PostProcessesOptimization(priority));
  107897. result.addOptimization(new ParticlesOptimization(priority));
  107898. // Next priority
  107899. priority++;
  107900. result.addOptimization(new TextureOptimization(priority, 1024));
  107901. return result;
  107902. };
  107903. /**
  107904. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  107905. * @param targetFrameRate defines the target frame rate (60 by default)
  107906. * @returns a SceneOptimizerOptions object
  107907. */
  107908. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  107909. var result = new SceneOptimizerOptions(targetFrameRate);
  107910. var priority = 0;
  107911. result.addOptimization(new MergeMeshesOptimization(priority));
  107912. result.addOptimization(new ShadowsOptimization(priority));
  107913. result.addOptimization(new LensFlaresOptimization(priority));
  107914. // Next priority
  107915. priority++;
  107916. result.addOptimization(new PostProcessesOptimization(priority));
  107917. result.addOptimization(new ParticlesOptimization(priority));
  107918. // Next priority
  107919. priority++;
  107920. result.addOptimization(new TextureOptimization(priority, 512));
  107921. // Next priority
  107922. priority++;
  107923. result.addOptimization(new RenderTargetsOptimization(priority));
  107924. // Next priority
  107925. priority++;
  107926. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  107927. return result;
  107928. };
  107929. /**
  107930. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  107931. * @param targetFrameRate defines the target frame rate (60 by default)
  107932. * @returns a SceneOptimizerOptions object
  107933. */
  107934. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  107935. var result = new SceneOptimizerOptions(targetFrameRate);
  107936. var priority = 0;
  107937. result.addOptimization(new MergeMeshesOptimization(priority));
  107938. result.addOptimization(new ShadowsOptimization(priority));
  107939. result.addOptimization(new LensFlaresOptimization(priority));
  107940. // Next priority
  107941. priority++;
  107942. result.addOptimization(new PostProcessesOptimization(priority));
  107943. result.addOptimization(new ParticlesOptimization(priority));
  107944. // Next priority
  107945. priority++;
  107946. result.addOptimization(new TextureOptimization(priority, 256));
  107947. // Next priority
  107948. priority++;
  107949. result.addOptimization(new RenderTargetsOptimization(priority));
  107950. // Next priority
  107951. priority++;
  107952. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  107953. return result;
  107954. };
  107955. return SceneOptimizerOptions;
  107956. }());
  107957. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  107958. /**
  107959. * Class used to run optimizations in order to reach a target frame rate
  107960. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107961. */
  107962. var SceneOptimizer = /** @class */ (function () {
  107963. /**
  107964. * Creates a new SceneOptimizer
  107965. * @param scene defines the scene to work on
  107966. * @param options defines the options to use with the SceneOptimizer
  107967. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  107968. * @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)
  107969. */
  107970. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  107971. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  107972. if (improvementMode === void 0) { improvementMode = false; }
  107973. var _this = this;
  107974. this._isRunning = false;
  107975. this._currentPriorityLevel = 0;
  107976. this._targetFrameRate = 60;
  107977. this._trackerDuration = 2000;
  107978. this._currentFrameRate = 0;
  107979. this._improvementMode = false;
  107980. /**
  107981. * Defines an observable called when the optimizer reaches the target frame rate
  107982. */
  107983. this.onSuccessObservable = new BABYLON.Observable();
  107984. /**
  107985. * Defines an observable called when the optimizer enables an optimization
  107986. */
  107987. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  107988. /**
  107989. * Defines an observable called when the optimizer is not able to reach the target frame rate
  107990. */
  107991. this.onFailureObservable = new BABYLON.Observable();
  107992. if (!options) {
  107993. this._options = new SceneOptimizerOptions();
  107994. }
  107995. else {
  107996. this._options = options;
  107997. }
  107998. if (this._options.targetFrameRate) {
  107999. this._targetFrameRate = this._options.targetFrameRate;
  108000. }
  108001. if (this._options.trackerDuration) {
  108002. this._trackerDuration = this._options.trackerDuration;
  108003. }
  108004. if (autoGeneratePriorities) {
  108005. var priority = 0;
  108006. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  108007. var optim = _a[_i];
  108008. optim.priority = priority++;
  108009. }
  108010. }
  108011. this._improvementMode = improvementMode;
  108012. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  108013. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  108014. _this._sceneDisposeObserver = null;
  108015. _this.dispose();
  108016. });
  108017. }
  108018. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  108019. /**
  108020. * Gets a boolean indicating if the optimizer is in improvement mode
  108021. */
  108022. get: function () {
  108023. return this._improvementMode;
  108024. },
  108025. enumerable: true,
  108026. configurable: true
  108027. });
  108028. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  108029. /**
  108030. * Gets the current priority level (0 at start)
  108031. */
  108032. get: function () {
  108033. return this._currentPriorityLevel;
  108034. },
  108035. enumerable: true,
  108036. configurable: true
  108037. });
  108038. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  108039. /**
  108040. * Gets the current frame rate checked by the SceneOptimizer
  108041. */
  108042. get: function () {
  108043. return this._currentFrameRate;
  108044. },
  108045. enumerable: true,
  108046. configurable: true
  108047. });
  108048. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  108049. /**
  108050. * Gets or sets the current target frame rate (60 by default)
  108051. */
  108052. get: function () {
  108053. return this._targetFrameRate;
  108054. },
  108055. /**
  108056. * Gets or sets the current target frame rate (60 by default)
  108057. */
  108058. set: function (value) {
  108059. this._targetFrameRate = value;
  108060. },
  108061. enumerable: true,
  108062. configurable: true
  108063. });
  108064. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  108065. /**
  108066. * Gets or sets the current interval between two checks (every 2000ms by default)
  108067. */
  108068. get: function () {
  108069. return this._trackerDuration;
  108070. },
  108071. /**
  108072. * Gets or sets the current interval between two checks (every 2000ms by default)
  108073. */
  108074. set: function (value) {
  108075. this._trackerDuration = value;
  108076. },
  108077. enumerable: true,
  108078. configurable: true
  108079. });
  108080. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  108081. /**
  108082. * Gets the list of active optimizations
  108083. */
  108084. get: function () {
  108085. return this._options.optimizations;
  108086. },
  108087. enumerable: true,
  108088. configurable: true
  108089. });
  108090. /**
  108091. * Stops the current optimizer
  108092. */
  108093. SceneOptimizer.prototype.stop = function () {
  108094. this._isRunning = false;
  108095. };
  108096. /**
  108097. * Reset the optimizer to initial step (current priority level = 0)
  108098. */
  108099. SceneOptimizer.prototype.reset = function () {
  108100. this._currentPriorityLevel = 0;
  108101. };
  108102. /**
  108103. * Start the optimizer. By default it will try to reach a specific framerate
  108104. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  108105. */
  108106. SceneOptimizer.prototype.start = function () {
  108107. var _this = this;
  108108. if (this._isRunning) {
  108109. return;
  108110. }
  108111. this._isRunning = true;
  108112. // Let's wait for the scene to be ready before running our check
  108113. this._scene.executeWhenReady(function () {
  108114. setTimeout(function () {
  108115. _this._checkCurrentState();
  108116. }, _this._trackerDuration);
  108117. });
  108118. };
  108119. SceneOptimizer.prototype._checkCurrentState = function () {
  108120. var _this = this;
  108121. if (!this._isRunning) {
  108122. return;
  108123. }
  108124. var scene = this._scene;
  108125. var options = this._options;
  108126. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  108127. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  108128. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  108129. this._isRunning = false;
  108130. this.onSuccessObservable.notifyObservers(this);
  108131. return;
  108132. }
  108133. // Apply current level of optimizations
  108134. var allDone = true;
  108135. var noOptimizationApplied = true;
  108136. for (var index = 0; index < options.optimizations.length; index++) {
  108137. var optimization = options.optimizations[index];
  108138. if (optimization.priority === this._currentPriorityLevel) {
  108139. noOptimizationApplied = false;
  108140. allDone = allDone && optimization.apply(scene, this);
  108141. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  108142. }
  108143. }
  108144. // If no optimization was applied, this is a failure :(
  108145. if (noOptimizationApplied) {
  108146. this._isRunning = false;
  108147. this.onFailureObservable.notifyObservers(this);
  108148. return;
  108149. }
  108150. // If all optimizations were done, move to next level
  108151. if (allDone) {
  108152. this._currentPriorityLevel++;
  108153. }
  108154. // Let's the system running for a specific amount of time before checking FPS
  108155. scene.executeWhenReady(function () {
  108156. setTimeout(function () {
  108157. _this._checkCurrentState();
  108158. }, _this._trackerDuration);
  108159. });
  108160. };
  108161. /**
  108162. * Release all resources
  108163. */
  108164. SceneOptimizer.prototype.dispose = function () {
  108165. this.stop();
  108166. this.onSuccessObservable.clear();
  108167. this.onFailureObservable.clear();
  108168. this.onNewOptimizationAppliedObservable.clear();
  108169. if (this._sceneDisposeObserver) {
  108170. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  108171. }
  108172. };
  108173. /**
  108174. * Helper function to create a SceneOptimizer with one single line of code
  108175. * @param scene defines the scene to work on
  108176. * @param options defines the options to use with the SceneOptimizer
  108177. * @param onSuccess defines a callback to call on success
  108178. * @param onFailure defines a callback to call on failure
  108179. * @returns the new SceneOptimizer object
  108180. */
  108181. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  108182. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  108183. if (onSuccess) {
  108184. optimizer.onSuccessObservable.add(function () {
  108185. onSuccess();
  108186. });
  108187. }
  108188. if (onFailure) {
  108189. optimizer.onFailureObservable.add(function () {
  108190. onFailure();
  108191. });
  108192. }
  108193. optimizer.start();
  108194. return optimizer;
  108195. };
  108196. return SceneOptimizer;
  108197. }());
  108198. BABYLON.SceneOptimizer = SceneOptimizer;
  108199. })(BABYLON || (BABYLON = {}));
  108200. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  108201. var BABYLON;
  108202. (function (BABYLON) {
  108203. /**
  108204. * Gets the outline renderer associated with the scene
  108205. * @returns a OutlineRenderer
  108206. */
  108207. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  108208. if (!this._outlineRenderer) {
  108209. this._outlineRenderer = new OutlineRenderer(this);
  108210. }
  108211. return this._outlineRenderer;
  108212. };
  108213. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  108214. get: function () {
  108215. return this._renderOutline;
  108216. },
  108217. set: function (value) {
  108218. if (value) {
  108219. // Lazy Load the component.
  108220. this.getScene().getOutlineRenderer();
  108221. }
  108222. this._renderOutline = value;
  108223. },
  108224. enumerable: true,
  108225. configurable: true
  108226. });
  108227. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  108228. get: function () {
  108229. return this._renderOverlay;
  108230. },
  108231. set: function (value) {
  108232. if (value) {
  108233. // Lazy Load the component.
  108234. this.getScene().getOutlineRenderer();
  108235. }
  108236. this._renderOverlay = value;
  108237. },
  108238. enumerable: true,
  108239. configurable: true
  108240. });
  108241. /**
  108242. * This class is responsible to draw bothe outline/overlay of meshes.
  108243. * It should not be used directly but through the available method on mesh.
  108244. */
  108245. var OutlineRenderer = /** @class */ (function () {
  108246. /**
  108247. * Instantiates a new outline renderer. (There could be only one per scene).
  108248. * @param scene Defines the scene it belongs to
  108249. */
  108250. function OutlineRenderer(scene) {
  108251. /**
  108252. * The name of the component. Each component must have a unique name.
  108253. */
  108254. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  108255. /**
  108256. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  108257. */
  108258. this.zOffset = 1;
  108259. this.scene = scene;
  108260. this._engine = scene.getEngine();
  108261. this.scene._addComponent(this);
  108262. }
  108263. /**
  108264. * Register the component to one instance of a scene.
  108265. */
  108266. OutlineRenderer.prototype.register = function () {
  108267. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  108268. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  108269. };
  108270. /**
  108271. * Rebuilds the elements related to this component in case of
  108272. * context lost for instance.
  108273. */
  108274. OutlineRenderer.prototype.rebuild = function () {
  108275. // Nothing to do here.
  108276. };
  108277. /**
  108278. * Disposes the component and the associated ressources.
  108279. */
  108280. OutlineRenderer.prototype.dispose = function () {
  108281. // Nothing to do here.
  108282. };
  108283. /**
  108284. * Renders the outline in the canvas.
  108285. * @param subMesh Defines the sumesh to render
  108286. * @param batch Defines the batch of meshes in case of instances
  108287. * @param useOverlay Defines if the rendering is for the overlay or the outline
  108288. */
  108289. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  108290. var _this = this;
  108291. if (useOverlay === void 0) { useOverlay = false; }
  108292. var scene = this.scene;
  108293. var engine = scene.getEngine();
  108294. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  108295. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  108296. return;
  108297. }
  108298. var mesh = subMesh.getRenderingMesh();
  108299. var material = subMesh.getMaterial();
  108300. if (!material || !scene.activeCamera) {
  108301. return;
  108302. }
  108303. engine.enableEffect(this._effect);
  108304. // Logarithmic depth
  108305. if (material.useLogarithmicDepth) {
  108306. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  108307. }
  108308. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  108309. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  108310. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  108311. // Bones
  108312. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  108313. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  108314. }
  108315. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  108316. // Alpha test
  108317. if (material && material.needAlphaTesting()) {
  108318. var alphaTexture = material.getAlphaTestTexture();
  108319. if (alphaTexture) {
  108320. this._effect.setTexture("diffuseSampler", alphaTexture);
  108321. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  108322. }
  108323. }
  108324. engine.setZOffset(-this.zOffset);
  108325. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  108326. engine.setZOffset(0);
  108327. };
  108328. /**
  108329. * Returns whether or not the outline renderer is ready for a given submesh.
  108330. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  108331. * @param subMesh Defines the submesh to check readyness for
  108332. * @param useInstances Defines wheter wee are trying to render instances or not
  108333. * @returns true if ready otherwise false
  108334. */
  108335. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  108336. var defines = [];
  108337. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  108338. var mesh = subMesh.getMesh();
  108339. var material = subMesh.getMaterial();
  108340. if (material) {
  108341. // Alpha test
  108342. if (material.needAlphaTesting()) {
  108343. defines.push("#define ALPHATEST");
  108344. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  108345. attribs.push(BABYLON.VertexBuffer.UVKind);
  108346. defines.push("#define UV1");
  108347. }
  108348. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  108349. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  108350. defines.push("#define UV2");
  108351. }
  108352. }
  108353. //Logarithmic depth
  108354. if (material.useLogarithmicDepth) {
  108355. defines.push("#define LOGARITHMICDEPTH");
  108356. }
  108357. }
  108358. // Bones
  108359. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  108360. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  108361. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  108362. if (mesh.numBoneInfluencers > 4) {
  108363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  108364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  108365. }
  108366. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  108367. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  108368. }
  108369. else {
  108370. defines.push("#define NUM_BONE_INFLUENCERS 0");
  108371. }
  108372. // Instances
  108373. if (useInstances) {
  108374. defines.push("#define INSTANCES");
  108375. attribs.push("world0");
  108376. attribs.push("world1");
  108377. attribs.push("world2");
  108378. attribs.push("world3");
  108379. }
  108380. // Get correct effect
  108381. var join = defines.join("\n");
  108382. if (this._cachedDefines !== join) {
  108383. this._cachedDefines = join;
  108384. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  108385. }
  108386. return this._effect.isReady();
  108387. };
  108388. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  108389. // Outline - step 1
  108390. this._savedDepthWrite = this._engine.getDepthWrite();
  108391. if (mesh.renderOutline) {
  108392. this._engine.setDepthWrite(false);
  108393. this.render(subMesh, batch);
  108394. this._engine.setDepthWrite(this._savedDepthWrite);
  108395. }
  108396. };
  108397. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  108398. // Outline - step 2
  108399. if (mesh.renderOutline && this._savedDepthWrite) {
  108400. this._engine.setDepthWrite(true);
  108401. this._engine.setColorWrite(false);
  108402. this.render(subMesh, batch);
  108403. this._engine.setColorWrite(true);
  108404. }
  108405. // Overlay
  108406. if (mesh.renderOverlay) {
  108407. var currentMode = this._engine.getAlphaMode();
  108408. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108409. this.render(subMesh, batch, true);
  108410. this._engine.setAlphaMode(currentMode);
  108411. }
  108412. };
  108413. return OutlineRenderer;
  108414. }());
  108415. BABYLON.OutlineRenderer = OutlineRenderer;
  108416. })(BABYLON || (BABYLON = {}));
  108417. //# sourceMappingURL=babylon.outlineRenderer.js.map
  108418. var BABYLON;
  108419. (function (BABYLON) {
  108420. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  108421. if (this._edgesRenderer) {
  108422. this._edgesRenderer.dispose();
  108423. this._edgesRenderer = null;
  108424. }
  108425. return this;
  108426. };
  108427. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108428. if (epsilon === void 0) { epsilon = 0.95; }
  108429. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108430. this.disableEdgesRendering();
  108431. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108432. return this;
  108433. };
  108434. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  108435. get: function () {
  108436. return this._edgesRenderer;
  108437. },
  108438. enumerable: true,
  108439. configurable: true
  108440. });
  108441. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108442. if (epsilon === void 0) { epsilon = 0.95; }
  108443. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108444. this.disableEdgesRendering();
  108445. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108446. return this;
  108447. };
  108448. /**
  108449. * FaceAdjacencies Helper class to generate edges
  108450. */
  108451. var FaceAdjacencies = /** @class */ (function () {
  108452. function FaceAdjacencies() {
  108453. this.edges = new Array();
  108454. this.edgesConnectedCount = 0;
  108455. }
  108456. return FaceAdjacencies;
  108457. }());
  108458. /**
  108459. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  108460. */
  108461. var EdgesRenderer = /** @class */ (function () {
  108462. /**
  108463. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  108464. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  108465. * @param source Mesh used to create edges
  108466. * @param epsilon sum of angles in adjacency to check for edge
  108467. * @param checkVerticesInsteadOfIndices
  108468. * @param generateEdgesLines - should generate Lines or only prepare resources.
  108469. */
  108470. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  108471. if (epsilon === void 0) { epsilon = 0.95; }
  108472. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108473. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  108474. var _this = this;
  108475. /**
  108476. * Define the size of the edges with an orthographic camera
  108477. */
  108478. this.edgesWidthScalerForOrthographic = 1000.0;
  108479. /**
  108480. * Define the size of the edges with a perspective camera
  108481. */
  108482. this.edgesWidthScalerForPerspective = 50.0;
  108483. this._linesPositions = new Array();
  108484. this._linesNormals = new Array();
  108485. this._linesIndices = new Array();
  108486. this._buffers = {};
  108487. this._checkVerticesInsteadOfIndices = false;
  108488. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  108489. this.isEnabled = true;
  108490. this._source = source;
  108491. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  108492. this._epsilon = epsilon;
  108493. this._prepareRessources();
  108494. if (generateEdgesLines) {
  108495. this._generateEdgesLines();
  108496. }
  108497. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  108498. _this._rebuild();
  108499. });
  108500. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  108501. _this.dispose();
  108502. });
  108503. }
  108504. EdgesRenderer.prototype._prepareRessources = function () {
  108505. if (this._lineShader) {
  108506. return;
  108507. }
  108508. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  108509. attributes: ["position", "normal"],
  108510. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  108511. });
  108512. this._lineShader.disableDepthWrite = true;
  108513. this._lineShader.backFaceCulling = false;
  108514. };
  108515. /** @hidden */
  108516. EdgesRenderer.prototype._rebuild = function () {
  108517. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108518. if (buffer) {
  108519. buffer._rebuild();
  108520. }
  108521. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108522. if (buffer) {
  108523. buffer._rebuild();
  108524. }
  108525. var scene = this._source.getScene();
  108526. var engine = scene.getEngine();
  108527. this._ib = engine.createIndexBuffer(this._linesIndices);
  108528. };
  108529. /**
  108530. * Releases the required resources for the edges renderer
  108531. */
  108532. EdgesRenderer.prototype.dispose = function () {
  108533. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  108534. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  108535. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108536. if (buffer) {
  108537. buffer.dispose();
  108538. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  108539. }
  108540. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108541. if (buffer) {
  108542. buffer.dispose();
  108543. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  108544. }
  108545. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  108546. this._lineShader.dispose();
  108547. };
  108548. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  108549. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  108550. return 0;
  108551. }
  108552. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  108553. return 1;
  108554. }
  108555. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  108556. return 2;
  108557. }
  108558. return -1;
  108559. };
  108560. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  108561. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  108562. return 0;
  108563. }
  108564. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  108565. return 1;
  108566. }
  108567. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  108568. return 2;
  108569. }
  108570. return -1;
  108571. };
  108572. /**
  108573. * Checks if the pair of p0 and p1 is en edge
  108574. * @param faceIndex
  108575. * @param edge
  108576. * @param faceNormals
  108577. * @param p0
  108578. * @param p1
  108579. * @private
  108580. */
  108581. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108582. var needToCreateLine;
  108583. if (edge === undefined) {
  108584. needToCreateLine = true;
  108585. }
  108586. else {
  108587. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  108588. needToCreateLine = dotProduct < this._epsilon;
  108589. }
  108590. if (needToCreateLine) {
  108591. var offset = this._linesPositions.length / 3;
  108592. var normal = p0.subtract(p1);
  108593. normal.normalize();
  108594. // Positions
  108595. this._linesPositions.push(p0.x);
  108596. this._linesPositions.push(p0.y);
  108597. this._linesPositions.push(p0.z);
  108598. this._linesPositions.push(p0.x);
  108599. this._linesPositions.push(p0.y);
  108600. this._linesPositions.push(p0.z);
  108601. this._linesPositions.push(p1.x);
  108602. this._linesPositions.push(p1.y);
  108603. this._linesPositions.push(p1.z);
  108604. this._linesPositions.push(p1.x);
  108605. this._linesPositions.push(p1.y);
  108606. this._linesPositions.push(p1.z);
  108607. // Normals
  108608. this._linesNormals.push(p1.x);
  108609. this._linesNormals.push(p1.y);
  108610. this._linesNormals.push(p1.z);
  108611. this._linesNormals.push(-1);
  108612. this._linesNormals.push(p1.x);
  108613. this._linesNormals.push(p1.y);
  108614. this._linesNormals.push(p1.z);
  108615. this._linesNormals.push(1);
  108616. this._linesNormals.push(p0.x);
  108617. this._linesNormals.push(p0.y);
  108618. this._linesNormals.push(p0.z);
  108619. this._linesNormals.push(-1);
  108620. this._linesNormals.push(p0.x);
  108621. this._linesNormals.push(p0.y);
  108622. this._linesNormals.push(p0.z);
  108623. this._linesNormals.push(1);
  108624. // Indices
  108625. this._linesIndices.push(offset);
  108626. this._linesIndices.push(offset + 1);
  108627. this._linesIndices.push(offset + 2);
  108628. this._linesIndices.push(offset);
  108629. this._linesIndices.push(offset + 2);
  108630. this._linesIndices.push(offset + 3);
  108631. }
  108632. };
  108633. /**
  108634. * Generates lines edges from adjacencjes
  108635. * @private
  108636. */
  108637. EdgesRenderer.prototype._generateEdgesLines = function () {
  108638. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108639. var indices = this._source.getIndices();
  108640. if (!indices || !positions) {
  108641. return;
  108642. }
  108643. // First let's find adjacencies
  108644. var adjacencies = new Array();
  108645. var faceNormals = new Array();
  108646. var index;
  108647. var faceAdjacencies;
  108648. // Prepare faces
  108649. for (index = 0; index < indices.length; index += 3) {
  108650. faceAdjacencies = new FaceAdjacencies();
  108651. var p0Index = indices[index];
  108652. var p1Index = indices[index + 1];
  108653. var p2Index = indices[index + 2];
  108654. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  108655. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  108656. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  108657. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  108658. faceNormal.normalize();
  108659. faceNormals.push(faceNormal);
  108660. adjacencies.push(faceAdjacencies);
  108661. }
  108662. // Scan
  108663. for (index = 0; index < adjacencies.length; index++) {
  108664. faceAdjacencies = adjacencies[index];
  108665. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  108666. var otherFaceAdjacencies = adjacencies[otherIndex];
  108667. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  108668. break;
  108669. }
  108670. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  108671. continue;
  108672. }
  108673. var otherP0 = indices[otherIndex * 3];
  108674. var otherP1 = indices[otherIndex * 3 + 1];
  108675. var otherP2 = indices[otherIndex * 3 + 2];
  108676. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  108677. var otherEdgeIndex = 0;
  108678. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  108679. continue;
  108680. }
  108681. switch (edgeIndex) {
  108682. case 0:
  108683. if (this._checkVerticesInsteadOfIndices) {
  108684. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108685. }
  108686. else {
  108687. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  108688. }
  108689. break;
  108690. case 1:
  108691. if (this._checkVerticesInsteadOfIndices) {
  108692. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108693. }
  108694. else {
  108695. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  108696. }
  108697. break;
  108698. case 2:
  108699. if (this._checkVerticesInsteadOfIndices) {
  108700. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108701. }
  108702. else {
  108703. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  108704. }
  108705. break;
  108706. }
  108707. if (otherEdgeIndex === -1) {
  108708. continue;
  108709. }
  108710. faceAdjacencies.edges[edgeIndex] = otherIndex;
  108711. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  108712. faceAdjacencies.edgesConnectedCount++;
  108713. otherFaceAdjacencies.edgesConnectedCount++;
  108714. if (faceAdjacencies.edgesConnectedCount === 3) {
  108715. break;
  108716. }
  108717. }
  108718. }
  108719. }
  108720. // Create lines
  108721. for (index = 0; index < adjacencies.length; index++) {
  108722. // 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
  108723. var current = adjacencies[index];
  108724. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108725. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  108726. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  108727. }
  108728. // Merge into a single mesh
  108729. var engine = this._source.getScene().getEngine();
  108730. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108731. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108732. this._ib = engine.createIndexBuffer(this._linesIndices);
  108733. this._indicesCount = this._linesIndices.length;
  108734. };
  108735. /**
  108736. * Checks wether or not the edges renderer is ready to render.
  108737. * @return true if ready, otherwise false.
  108738. */
  108739. EdgesRenderer.prototype.isReady = function () {
  108740. return this._lineShader.isReady();
  108741. };
  108742. /**
  108743. * Renders the edges of the attached mesh,
  108744. */
  108745. EdgesRenderer.prototype.render = function () {
  108746. var scene = this._source.getScene();
  108747. if (!this.isReady() || !scene.activeCamera) {
  108748. return;
  108749. }
  108750. var engine = scene.getEngine();
  108751. this._lineShader._preBind();
  108752. if (this._source.edgesColor.a !== 1) {
  108753. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108754. }
  108755. else {
  108756. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108757. }
  108758. // VBOs
  108759. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  108760. scene.resetCachedMaterial();
  108761. this._lineShader.setColor4("color", this._source.edgesColor);
  108762. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  108763. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  108764. }
  108765. else {
  108766. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  108767. }
  108768. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  108769. this._lineShader.bind(this._source.getWorldMatrix());
  108770. // Draw order
  108771. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  108772. this._lineShader.unbind();
  108773. };
  108774. return EdgesRenderer;
  108775. }());
  108776. BABYLON.EdgesRenderer = EdgesRenderer;
  108777. })(BABYLON || (BABYLON = {}));
  108778. //# sourceMappingURL=babylon.edgesRenderer.js.map
  108779. var BABYLON;
  108780. (function (BABYLON) {
  108781. /**
  108782. * FaceAdjacencies Helper class to generate edges
  108783. */
  108784. var FaceAdjacencies = /** @class */ (function () {
  108785. function FaceAdjacencies() {
  108786. this.edges = new Array();
  108787. this.edgesConnectedCount = 0;
  108788. }
  108789. return FaceAdjacencies;
  108790. }());
  108791. /**
  108792. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  108793. */
  108794. var LineEdgesRenderer = /** @class */ (function (_super) {
  108795. __extends(LineEdgesRenderer, _super);
  108796. /**
  108797. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  108798. * @param source LineMesh used to generate edges
  108799. * @param epsilon not important (specified angle for edge detection)
  108800. * @param checkVerticesInsteadOfIndices not important for LineMesh
  108801. */
  108802. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  108803. if (epsilon === void 0) { epsilon = 0.95; }
  108804. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108805. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  108806. _this._generateEdgesLines();
  108807. return _this;
  108808. }
  108809. /**
  108810. * Always create the edge since its a line so only important things are p0 and p1
  108811. * @param faceIndex not important for LineMesh
  108812. * @param edge not important for LineMesh
  108813. * @param faceNormals not important for LineMesh
  108814. * @param p0 beginnig of line
  108815. * @param p1 end of line
  108816. */
  108817. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108818. var offset = this._linesPositions.length / 3;
  108819. var normal = p0.subtract(p1);
  108820. normal.normalize();
  108821. // Positions
  108822. this._linesPositions.push(p0.x);
  108823. this._linesPositions.push(p0.y);
  108824. this._linesPositions.push(p0.z);
  108825. this._linesPositions.push(p0.x);
  108826. this._linesPositions.push(p0.y);
  108827. this._linesPositions.push(p0.z);
  108828. this._linesPositions.push(p1.x);
  108829. this._linesPositions.push(p1.y);
  108830. this._linesPositions.push(p1.z);
  108831. this._linesPositions.push(p1.x);
  108832. this._linesPositions.push(p1.y);
  108833. this._linesPositions.push(p1.z);
  108834. // Normals
  108835. this._linesNormals.push(p1.x);
  108836. this._linesNormals.push(p1.y);
  108837. this._linesNormals.push(p1.z);
  108838. this._linesNormals.push(-1);
  108839. this._linesNormals.push(p1.x);
  108840. this._linesNormals.push(p1.y);
  108841. this._linesNormals.push(p1.z);
  108842. this._linesNormals.push(1);
  108843. this._linesNormals.push(p0.x);
  108844. this._linesNormals.push(p0.y);
  108845. this._linesNormals.push(p0.z);
  108846. this._linesNormals.push(-1);
  108847. this._linesNormals.push(p0.x);
  108848. this._linesNormals.push(p0.y);
  108849. this._linesNormals.push(p0.z);
  108850. this._linesNormals.push(1);
  108851. // Indices
  108852. this._linesIndices.push(offset);
  108853. this._linesIndices.push(offset + 1);
  108854. this._linesIndices.push(offset + 2);
  108855. this._linesIndices.push(offset);
  108856. this._linesIndices.push(offset + 2);
  108857. this._linesIndices.push(offset + 3);
  108858. };
  108859. /**
  108860. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  108861. */
  108862. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  108863. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108864. var indices = this._source.getIndices();
  108865. if (!indices || !positions) {
  108866. return;
  108867. }
  108868. // First let's find adjacencies
  108869. var adjacencies = new Array();
  108870. var faceNormals = new Array();
  108871. var index;
  108872. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  108873. var currentAdjecancy = new FaceAdjacencies();
  108874. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  108875. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  108876. adjacencies.push(currentAdjecancy);
  108877. }
  108878. // Create lines
  108879. for (index = 0; index < adjacencies.length; index++) {
  108880. // 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
  108881. var current = adjacencies[index];
  108882. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108883. }
  108884. // Merge into a single mesh
  108885. var engine = this._source.getScene().getEngine();
  108886. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108887. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108888. this._ib = engine.createIndexBuffer(this._linesIndices);
  108889. this._indicesCount = this._linesIndices.length;
  108890. };
  108891. return LineEdgesRenderer;
  108892. }(BABYLON.EdgesRenderer));
  108893. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  108894. })(BABYLON || (BABYLON = {}));
  108895. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  108896. var BABYLON;
  108897. (function (BABYLON) {
  108898. // Adds the parser to the scene parsers.
  108899. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  108900. if (parsedData.effectLayers) {
  108901. if (!container.effectLayers) {
  108902. container.effectLayers = new Array();
  108903. }
  108904. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  108905. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  108906. container.effectLayers.push(effectLayer);
  108907. }
  108908. }
  108909. });
  108910. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  108911. var index = this.effectLayers.indexOf(toRemove);
  108912. if (index !== -1) {
  108913. this.effectLayers.splice(index, 1);
  108914. }
  108915. return index;
  108916. };
  108917. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  108918. this.effectLayers.push(newEffectLayer);
  108919. };
  108920. /**
  108921. * Defines the layer scene component responsible to manage any effect layers
  108922. * in a given scene.
  108923. */
  108924. var EffectLayerSceneComponent = /** @class */ (function () {
  108925. /**
  108926. * Creates a new instance of the component for the given scene
  108927. * @param scene Defines the scene to register the component in
  108928. */
  108929. function EffectLayerSceneComponent(scene) {
  108930. /**
  108931. * The component name helpfull to identify the component in the list of scene components.
  108932. */
  108933. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  108934. this._renderEffects = false;
  108935. this._needStencil = false;
  108936. this._previousStencilState = false;
  108937. this.scene = scene;
  108938. this._engine = scene.getEngine();
  108939. scene.effectLayers = new Array();
  108940. }
  108941. /**
  108942. * Registers the component in a given scene
  108943. */
  108944. EffectLayerSceneComponent.prototype.register = function () {
  108945. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  108946. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  108947. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  108948. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  108949. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  108950. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  108951. };
  108952. /**
  108953. * Rebuilds the elements related to this component in case of
  108954. * context lost for instance.
  108955. */
  108956. EffectLayerSceneComponent.prototype.rebuild = function () {
  108957. var layers = this.scene.effectLayers;
  108958. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  108959. var effectLayer = layers_1[_i];
  108960. effectLayer._rebuild();
  108961. }
  108962. };
  108963. /**
  108964. * Serializes the component data to the specified json object
  108965. * @param serializationObject The object to serialize to
  108966. */
  108967. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  108968. // Effect layers
  108969. serializationObject.effectLayers = [];
  108970. var layers = this.scene.effectLayers;
  108971. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  108972. var effectLayer = layers_2[_i];
  108973. if (effectLayer.serialize) {
  108974. serializationObject.effectLayers.push(effectLayer.serialize());
  108975. }
  108976. }
  108977. };
  108978. /**
  108979. * Adds all the element from the container to the scene
  108980. * @param container the container holding the elements
  108981. */
  108982. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  108983. var _this = this;
  108984. if (!container.effectLayers) {
  108985. return;
  108986. }
  108987. container.effectLayers.forEach(function (o) {
  108988. _this.scene.addEffectLayer(o);
  108989. });
  108990. };
  108991. /**
  108992. * Removes all the elements in the container from the scene
  108993. * @param container contains the elements to remove
  108994. */
  108995. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  108996. var _this = this;
  108997. if (!container.effectLayers) {
  108998. return;
  108999. }
  109000. container.effectLayers.forEach(function (o) {
  109001. _this.scene.removeEffectLayer(o);
  109002. });
  109003. };
  109004. /**
  109005. * Disposes the component and the associated ressources.
  109006. */
  109007. EffectLayerSceneComponent.prototype.dispose = function () {
  109008. var layers = this.scene.effectLayers;
  109009. while (layers.length) {
  109010. layers[0].dispose();
  109011. }
  109012. };
  109013. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  109014. var layers = this.scene.effectLayers;
  109015. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  109016. var layer = layers_3[_i];
  109017. if (!layer.hasMesh(mesh)) {
  109018. continue;
  109019. }
  109020. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  109021. var subMesh = _b[_a];
  109022. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  109023. return false;
  109024. }
  109025. }
  109026. }
  109027. return true;
  109028. };
  109029. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  109030. this._renderEffects = false;
  109031. this._needStencil = false;
  109032. var layers = this.scene.effectLayers;
  109033. if (layers && layers.length > 0) {
  109034. this._previousStencilState = this._engine.getStencilBuffer();
  109035. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  109036. var effectLayer = layers_4[_i];
  109037. if (effectLayer.shouldRender() &&
  109038. (!effectLayer.camera ||
  109039. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  109040. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  109041. this._renderEffects = true;
  109042. this._needStencil = this._needStencil || effectLayer.needStencil();
  109043. var renderTarget = effectLayer._mainTexture;
  109044. if (renderTarget._shouldRender()) {
  109045. this.scene.incrementRenderId();
  109046. renderTarget.render(false, false);
  109047. }
  109048. }
  109049. }
  109050. this.scene.incrementRenderId();
  109051. }
  109052. };
  109053. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  109054. // Activate effect Layer stencil
  109055. if (this._needStencil) {
  109056. this._engine.setStencilBuffer(true);
  109057. }
  109058. };
  109059. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  109060. // Restore effect Layer stencil
  109061. if (this._needStencil) {
  109062. this._engine.setStencilBuffer(this._previousStencilState);
  109063. }
  109064. };
  109065. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  109066. if (this._renderEffects) {
  109067. this._engine.setDepthBuffer(false);
  109068. var layers = this.scene.effectLayers;
  109069. for (var i = 0; i < layers.length; i++) {
  109070. var effectLayer = layers[i];
  109071. if (effectLayer.renderingGroupId === renderingGroupId) {
  109072. if (effectLayer.shouldRender()) {
  109073. effectLayer.render();
  109074. }
  109075. }
  109076. }
  109077. this._engine.setDepthBuffer(true);
  109078. }
  109079. };
  109080. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  109081. if (this._renderEffects) {
  109082. this._draw(-1);
  109083. }
  109084. };
  109085. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  109086. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  109087. this._draw(index);
  109088. }
  109089. };
  109090. return EffectLayerSceneComponent;
  109091. }());
  109092. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  109093. })(BABYLON || (BABYLON = {}));
  109094. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  109095. var __assign = (this && this.__assign) || function () {
  109096. __assign = Object.assign || function(t) {
  109097. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109098. s = arguments[i];
  109099. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109100. t[p] = s[p];
  109101. }
  109102. return t;
  109103. };
  109104. return __assign.apply(this, arguments);
  109105. };
  109106. var BABYLON;
  109107. (function (BABYLON) {
  109108. /**
  109109. * The effect layer Helps adding post process effect blended with the main pass.
  109110. *
  109111. * This can be for instance use to generate glow or higlight effects on the scene.
  109112. *
  109113. * The effect layer class can not be used directly and is intented to inherited from to be
  109114. * customized per effects.
  109115. */
  109116. var EffectLayer = /** @class */ (function () {
  109117. /**
  109118. * Instantiates a new effect Layer and references it in the scene.
  109119. * @param name The name of the layer
  109120. * @param scene The scene to use the layer in
  109121. */
  109122. function EffectLayer(
  109123. /** The Friendly of the effect in the scene */
  109124. name, scene) {
  109125. this._vertexBuffers = {};
  109126. this._maxSize = 0;
  109127. this._mainTextureDesiredSize = { width: 0, height: 0 };
  109128. this._shouldRender = true;
  109129. this._postProcesses = [];
  109130. this._textures = [];
  109131. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  109132. /**
  109133. * The clear color of the texture used to generate the glow map.
  109134. */
  109135. this.neutralColor = new BABYLON.Color4();
  109136. /**
  109137. * Specifies wether the highlight layer is enabled or not.
  109138. */
  109139. this.isEnabled = true;
  109140. /**
  109141. * An event triggered when the effect layer has been disposed.
  109142. */
  109143. this.onDisposeObservable = new BABYLON.Observable();
  109144. /**
  109145. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  109146. */
  109147. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  109148. /**
  109149. * An event triggered when the generated texture is being merged in the scene.
  109150. */
  109151. this.onBeforeComposeObservable = new BABYLON.Observable();
  109152. /**
  109153. * An event triggered when the generated texture has been merged in the scene.
  109154. */
  109155. this.onAfterComposeObservable = new BABYLON.Observable();
  109156. /**
  109157. * An event triggered when the efffect layer changes its size.
  109158. */
  109159. this.onSizeChangedObservable = new BABYLON.Observable();
  109160. this.name = name;
  109161. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  109162. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  109163. if (!component) {
  109164. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  109165. this._scene._addComponent(component);
  109166. }
  109167. this._engine = this._scene.getEngine();
  109168. this._maxSize = this._engine.getCaps().maxTextureSize;
  109169. this._scene.effectLayers.push(this);
  109170. // Generate Buffers
  109171. this._generateIndexBuffer();
  109172. this._genrateVertexBuffer();
  109173. }
  109174. Object.defineProperty(EffectLayer.prototype, "camera", {
  109175. /**
  109176. * Gets the camera attached to the layer.
  109177. */
  109178. get: function () {
  109179. return this._effectLayerOptions.camera;
  109180. },
  109181. enumerable: true,
  109182. configurable: true
  109183. });
  109184. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  109185. /**
  109186. * Gets the rendering group id the layer should render in.
  109187. */
  109188. get: function () {
  109189. return this._effectLayerOptions.renderingGroupId;
  109190. },
  109191. enumerable: true,
  109192. configurable: true
  109193. });
  109194. /**
  109195. * Initializes the effect layer with the required options.
  109196. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  109197. */
  109198. EffectLayer.prototype._init = function (options) {
  109199. // Adapt options
  109200. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  109201. this._setMainTextureSize();
  109202. this._createMainTexture();
  109203. this._createTextureAndPostProcesses();
  109204. this._mergeEffect = this._createMergeEffect();
  109205. };
  109206. /**
  109207. * Generates the index buffer of the full screen quad blending to the main canvas.
  109208. */
  109209. EffectLayer.prototype._generateIndexBuffer = function () {
  109210. // Indices
  109211. var indices = [];
  109212. indices.push(0);
  109213. indices.push(1);
  109214. indices.push(2);
  109215. indices.push(0);
  109216. indices.push(2);
  109217. indices.push(3);
  109218. this._indexBuffer = this._engine.createIndexBuffer(indices);
  109219. };
  109220. /**
  109221. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  109222. */
  109223. EffectLayer.prototype._genrateVertexBuffer = function () {
  109224. // VBO
  109225. var vertices = [];
  109226. vertices.push(1, 1);
  109227. vertices.push(-1, 1);
  109228. vertices.push(-1, -1);
  109229. vertices.push(1, -1);
  109230. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  109231. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  109232. };
  109233. /**
  109234. * Sets the main texture desired size which is the closest power of two
  109235. * of the engine canvas size.
  109236. */
  109237. EffectLayer.prototype._setMainTextureSize = function () {
  109238. if (this._effectLayerOptions.mainTextureFixedSize) {
  109239. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  109240. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  109241. }
  109242. else {
  109243. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  109244. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  109245. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  109246. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  109247. }
  109248. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  109249. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  109250. };
  109251. /**
  109252. * Creates the main texture for the effect layer.
  109253. */
  109254. EffectLayer.prototype._createMainTexture = function () {
  109255. var _this = this;
  109256. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  109257. width: this._mainTextureDesiredSize.width,
  109258. height: this._mainTextureDesiredSize.height
  109259. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  109260. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  109261. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109262. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109263. this._mainTexture.anisotropicFilteringLevel = 1;
  109264. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  109265. this._mainTexture.renderParticles = false;
  109266. this._mainTexture.renderList = null;
  109267. this._mainTexture.ignoreCameraViewport = true;
  109268. // Custom render function
  109269. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  109270. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  109271. var index;
  109272. var engine = _this._scene.getEngine();
  109273. if (depthOnlySubMeshes.length) {
  109274. engine.setColorWrite(false);
  109275. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  109276. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  109277. }
  109278. engine.setColorWrite(true);
  109279. }
  109280. for (index = 0; index < opaqueSubMeshes.length; index++) {
  109281. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  109282. }
  109283. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  109284. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  109285. }
  109286. for (index = 0; index < transparentSubMeshes.length; index++) {
  109287. _this._renderSubMesh(transparentSubMeshes.data[index]);
  109288. }
  109289. };
  109290. this._mainTexture.onClearObservable.add(function (engine) {
  109291. engine.clear(_this.neutralColor, true, true, true);
  109292. });
  109293. };
  109294. /**
  109295. * Checks for the readiness of the element composing the layer.
  109296. * @param subMesh the mesh to check for
  109297. * @param useInstances specify wether or not to use instances to render the mesh
  109298. * @param emissiveTexture the associated emissive texture used to generate the glow
  109299. * @return true if ready otherwise, false
  109300. */
  109301. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  109302. var material = subMesh.getMaterial();
  109303. if (!material) {
  109304. return false;
  109305. }
  109306. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  109307. return false;
  109308. }
  109309. var defines = [];
  109310. var attribs = [BABYLON.VertexBuffer.PositionKind];
  109311. var mesh = subMesh.getMesh();
  109312. var uv1 = false;
  109313. var uv2 = false;
  109314. // Alpha test
  109315. if (material && material.needAlphaTesting()) {
  109316. var alphaTexture = material.getAlphaTestTexture();
  109317. if (alphaTexture) {
  109318. defines.push("#define ALPHATEST");
  109319. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109320. alphaTexture.coordinatesIndex === 1) {
  109321. defines.push("#define DIFFUSEUV2");
  109322. uv2 = true;
  109323. }
  109324. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109325. defines.push("#define DIFFUSEUV1");
  109326. uv1 = true;
  109327. }
  109328. }
  109329. }
  109330. // Emissive
  109331. if (emissiveTexture) {
  109332. defines.push("#define EMISSIVE");
  109333. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109334. emissiveTexture.coordinatesIndex === 1) {
  109335. defines.push("#define EMISSIVEUV2");
  109336. uv2 = true;
  109337. }
  109338. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109339. defines.push("#define EMISSIVEUV1");
  109340. uv1 = true;
  109341. }
  109342. }
  109343. if (uv1) {
  109344. attribs.push(BABYLON.VertexBuffer.UVKind);
  109345. defines.push("#define UV1");
  109346. }
  109347. if (uv2) {
  109348. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109349. defines.push("#define UV2");
  109350. }
  109351. // Bones
  109352. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  109353. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  109354. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  109355. if (mesh.numBoneInfluencers > 4) {
  109356. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  109357. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  109358. }
  109359. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  109360. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  109361. }
  109362. else {
  109363. defines.push("#define NUM_BONE_INFLUENCERS 0");
  109364. }
  109365. // Morph targets
  109366. var manager = mesh.morphTargetManager;
  109367. var morphInfluencers = 0;
  109368. if (manager) {
  109369. if (manager.numInfluencers > 0) {
  109370. defines.push("#define MORPHTARGETS");
  109371. morphInfluencers = manager.numInfluencers;
  109372. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  109373. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  109374. }
  109375. }
  109376. // Instances
  109377. if (useInstances) {
  109378. defines.push("#define INSTANCES");
  109379. attribs.push("world0");
  109380. attribs.push("world1");
  109381. attribs.push("world2");
  109382. attribs.push("world3");
  109383. }
  109384. // Get correct effect
  109385. var join = defines.join("\n");
  109386. if (this._cachedDefines !== join) {
  109387. this._cachedDefines = join;
  109388. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  109389. }
  109390. return this._effectLayerMapGenerationEffect.isReady();
  109391. };
  109392. /**
  109393. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  109394. */
  109395. EffectLayer.prototype.render = function () {
  109396. var currentEffect = this._mergeEffect;
  109397. // Check
  109398. if (!currentEffect.isReady()) {
  109399. return;
  109400. }
  109401. for (var i = 0; i < this._postProcesses.length; i++) {
  109402. if (!this._postProcesses[i].isReady()) {
  109403. return;
  109404. }
  109405. }
  109406. var engine = this._scene.getEngine();
  109407. this.onBeforeComposeObservable.notifyObservers(this);
  109408. // Render
  109409. engine.enableEffect(currentEffect);
  109410. engine.setState(false);
  109411. // VBOs
  109412. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  109413. // Cache
  109414. var previousAlphaMode = engine.getAlphaMode();
  109415. // Go Blend.
  109416. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  109417. // Blends the map on the main canvas.
  109418. this._internalRender(currentEffect);
  109419. // Restore Alpha
  109420. engine.setAlphaMode(previousAlphaMode);
  109421. this.onAfterComposeObservable.notifyObservers(this);
  109422. // Handle size changes.
  109423. var size = this._mainTexture.getSize();
  109424. this._setMainTextureSize();
  109425. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  109426. // Recreate RTT and post processes on size change.
  109427. this.onSizeChangedObservable.notifyObservers(this);
  109428. this._disposeTextureAndPostProcesses();
  109429. this._createMainTexture();
  109430. this._createTextureAndPostProcesses();
  109431. }
  109432. };
  109433. /**
  109434. * Determine if a given mesh will be used in the current effect.
  109435. * @param mesh mesh to test
  109436. * @returns true if the mesh will be used
  109437. */
  109438. EffectLayer.prototype.hasMesh = function (mesh) {
  109439. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  109440. return true;
  109441. }
  109442. return false;
  109443. };
  109444. /**
  109445. * Returns true if the layer contains information to display, otherwise false.
  109446. * @returns true if the glow layer should be rendered
  109447. */
  109448. EffectLayer.prototype.shouldRender = function () {
  109449. return this.isEnabled && this._shouldRender;
  109450. };
  109451. /**
  109452. * Returns true if the mesh should render, otherwise false.
  109453. * @param mesh The mesh to render
  109454. * @returns true if it should render otherwise false
  109455. */
  109456. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  109457. return true;
  109458. };
  109459. /**
  109460. * Returns true if the mesh should render, otherwise false.
  109461. * @param mesh The mesh to render
  109462. * @returns true if it should render otherwise false
  109463. */
  109464. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  109465. return true;
  109466. };
  109467. /**
  109468. * Renders the submesh passed in parameter to the generation map.
  109469. */
  109470. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  109471. var _this = this;
  109472. if (!this.shouldRender()) {
  109473. return;
  109474. }
  109475. var material = subMesh.getMaterial();
  109476. var mesh = subMesh.getRenderingMesh();
  109477. var scene = this._scene;
  109478. var engine = scene.getEngine();
  109479. if (!material) {
  109480. return;
  109481. }
  109482. // Do not block in blend mode.
  109483. if (material.needAlphaBlendingForMesh(mesh)) {
  109484. return;
  109485. }
  109486. // Culling
  109487. engine.setState(material.backFaceCulling);
  109488. // Managing instances
  109489. var batch = mesh._getInstancesRenderList(subMesh._id);
  109490. if (batch.mustReturn) {
  109491. return;
  109492. }
  109493. // Early Exit per mesh
  109494. if (!this._shouldRenderMesh(mesh)) {
  109495. return;
  109496. }
  109497. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  109498. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  109499. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  109500. engine.enableEffect(this._effectLayerMapGenerationEffect);
  109501. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  109502. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  109503. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  109504. // Alpha test
  109505. if (material && material.needAlphaTesting()) {
  109506. var alphaTexture = material.getAlphaTestTexture();
  109507. if (alphaTexture) {
  109508. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  109509. var textureMatrix = alphaTexture.getTextureMatrix();
  109510. if (textureMatrix) {
  109511. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  109512. }
  109513. }
  109514. }
  109515. // Glow emissive only
  109516. if (this._emissiveTextureAndColor.texture) {
  109517. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  109518. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  109519. }
  109520. // Bones
  109521. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  109522. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  109523. }
  109524. // Morph targets
  109525. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  109526. // Draw
  109527. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  109528. }
  109529. else {
  109530. // Need to reset refresh rate of the main map
  109531. this._mainTexture.resetRefreshCounter();
  109532. }
  109533. };
  109534. /**
  109535. * Rebuild the required buffers.
  109536. * @hidden Internal use only.
  109537. */
  109538. EffectLayer.prototype._rebuild = function () {
  109539. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109540. if (vb) {
  109541. vb._rebuild();
  109542. }
  109543. this._generateIndexBuffer();
  109544. };
  109545. /**
  109546. * Dispose only the render target textures and post process.
  109547. */
  109548. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  109549. this._mainTexture.dispose();
  109550. for (var i = 0; i < this._postProcesses.length; i++) {
  109551. if (this._postProcesses[i]) {
  109552. this._postProcesses[i].dispose();
  109553. }
  109554. }
  109555. this._postProcesses = [];
  109556. for (var i = 0; i < this._textures.length; i++) {
  109557. if (this._textures[i]) {
  109558. this._textures[i].dispose();
  109559. }
  109560. }
  109561. this._textures = [];
  109562. };
  109563. /**
  109564. * Dispose the highlight layer and free resources.
  109565. */
  109566. EffectLayer.prototype.dispose = function () {
  109567. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109568. if (vertexBuffer) {
  109569. vertexBuffer.dispose();
  109570. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  109571. }
  109572. if (this._indexBuffer) {
  109573. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  109574. this._indexBuffer = null;
  109575. }
  109576. // Clean textures and post processes
  109577. this._disposeTextureAndPostProcesses();
  109578. // Remove from scene
  109579. var index = this._scene.effectLayers.indexOf(this, 0);
  109580. if (index > -1) {
  109581. this._scene.effectLayers.splice(index, 1);
  109582. }
  109583. // Callback
  109584. this.onDisposeObservable.notifyObservers(this);
  109585. this.onDisposeObservable.clear();
  109586. this.onBeforeRenderMainTextureObservable.clear();
  109587. this.onBeforeComposeObservable.clear();
  109588. this.onAfterComposeObservable.clear();
  109589. this.onSizeChangedObservable.clear();
  109590. };
  109591. /**
  109592. * Gets the class name of the effect layer
  109593. * @returns the string with the class name of the effect layer
  109594. */
  109595. EffectLayer.prototype.getClassName = function () {
  109596. return "EffectLayer";
  109597. };
  109598. /**
  109599. * Creates an effect layer from parsed effect layer data
  109600. * @param parsedEffectLayer defines effect layer data
  109601. * @param scene defines the current scene
  109602. * @param rootUrl defines the root URL containing the effect layer information
  109603. * @returns a parsed effect Layer
  109604. */
  109605. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  109606. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  109607. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  109608. };
  109609. __decorate([
  109610. BABYLON.serialize()
  109611. ], EffectLayer.prototype, "name", void 0);
  109612. __decorate([
  109613. BABYLON.serializeAsColor4()
  109614. ], EffectLayer.prototype, "neutralColor", void 0);
  109615. __decorate([
  109616. BABYLON.serialize()
  109617. ], EffectLayer.prototype, "isEnabled", void 0);
  109618. __decorate([
  109619. BABYLON.serializeAsCameraReference()
  109620. ], EffectLayer.prototype, "camera", null);
  109621. __decorate([
  109622. BABYLON.serialize()
  109623. ], EffectLayer.prototype, "renderingGroupId", null);
  109624. return EffectLayer;
  109625. }());
  109626. BABYLON.EffectLayer = EffectLayer;
  109627. })(BABYLON || (BABYLON = {}));
  109628. //# sourceMappingURL=babylon.effectLayer.js.map
  109629. var BABYLON;
  109630. (function (BABYLON) {
  109631. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  109632. for (var index = 0; index < this.effectLayers.length; index++) {
  109633. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  109634. return this.effectLayers[index];
  109635. }
  109636. }
  109637. return null;
  109638. };
  109639. /**
  109640. * Special Glow Blur post process only blurring the alpha channel
  109641. * It enforces keeping the most luminous color in the color channel.
  109642. */
  109643. var GlowBlurPostProcess = /** @class */ (function (_super) {
  109644. __extends(GlowBlurPostProcess, _super);
  109645. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  109646. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  109647. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  109648. _this.direction = direction;
  109649. _this.kernel = kernel;
  109650. _this.onApplyObservable.add(function (effect) {
  109651. effect.setFloat2("screenSize", _this.width, _this.height);
  109652. effect.setVector2("direction", _this.direction);
  109653. effect.setFloat("blurWidth", _this.kernel);
  109654. });
  109655. return _this;
  109656. }
  109657. return GlowBlurPostProcess;
  109658. }(BABYLON.PostProcess));
  109659. /**
  109660. * The highlight layer Helps adding a glow effect around a mesh.
  109661. *
  109662. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  109663. * glowy meshes to your scene.
  109664. *
  109665. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  109666. */
  109667. var HighlightLayer = /** @class */ (function (_super) {
  109668. __extends(HighlightLayer, _super);
  109669. /**
  109670. * Instantiates a new highlight Layer and references it to the scene..
  109671. * @param name The name of the layer
  109672. * @param scene The scene to use the layer in
  109673. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  109674. */
  109675. function HighlightLayer(name, scene, options) {
  109676. var _this = _super.call(this, name, scene) || this;
  109677. _this.name = name;
  109678. /**
  109679. * Specifies whether or not the inner glow is ACTIVE in the layer.
  109680. */
  109681. _this.innerGlow = true;
  109682. /**
  109683. * Specifies whether or not the outer glow is ACTIVE in the layer.
  109684. */
  109685. _this.outerGlow = true;
  109686. /**
  109687. * An event triggered when the highlight layer is being blurred.
  109688. */
  109689. _this.onBeforeBlurObservable = new BABYLON.Observable();
  109690. /**
  109691. * An event triggered when the highlight layer has been blurred.
  109692. */
  109693. _this.onAfterBlurObservable = new BABYLON.Observable();
  109694. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  109695. _this._meshes = {};
  109696. _this._excludedMeshes = {};
  109697. _this.neutralColor = HighlightLayer.NeutralColor;
  109698. // Warn on stencil
  109699. if (!_this._engine.isStencilEnable) {
  109700. 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 }");
  109701. }
  109702. // Adapt options
  109703. _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);
  109704. // Initialize the layer
  109705. _this._init({
  109706. alphaBlendingMode: _this._options.alphaBlendingMode,
  109707. camera: _this._options.camera,
  109708. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  109709. mainTextureRatio: _this._options.mainTextureRatio,
  109710. renderingGroupId: _this._options.renderingGroupId
  109711. });
  109712. // Do not render as long as no meshes have been added
  109713. _this._shouldRender = false;
  109714. return _this;
  109715. }
  109716. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  109717. /**
  109718. * Gets the horizontal size of the blur.
  109719. */
  109720. get: function () {
  109721. return this._horizontalBlurPostprocess.kernel;
  109722. },
  109723. /**
  109724. * Specifies the horizontal size of the blur.
  109725. */
  109726. set: function (value) {
  109727. this._horizontalBlurPostprocess.kernel = value;
  109728. },
  109729. enumerable: true,
  109730. configurable: true
  109731. });
  109732. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  109733. /**
  109734. * Gets the vertical size of the blur.
  109735. */
  109736. get: function () {
  109737. return this._verticalBlurPostprocess.kernel;
  109738. },
  109739. /**
  109740. * Specifies the vertical size of the blur.
  109741. */
  109742. set: function (value) {
  109743. this._verticalBlurPostprocess.kernel = value;
  109744. },
  109745. enumerable: true,
  109746. configurable: true
  109747. });
  109748. /**
  109749. * Get the effect name of the layer.
  109750. * @return The effect name
  109751. */
  109752. HighlightLayer.prototype.getEffectName = function () {
  109753. return HighlightLayer.EffectName;
  109754. };
  109755. /**
  109756. * Create the merge effect. This is the shader use to blit the information back
  109757. * to the main canvas at the end of the scene rendering.
  109758. */
  109759. HighlightLayer.prototype._createMergeEffect = function () {
  109760. // Effect
  109761. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  109762. };
  109763. /**
  109764. * Creates the render target textures and post processes used in the highlight layer.
  109765. */
  109766. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  109767. var _this = this;
  109768. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  109769. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  109770. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  109771. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  109772. var textureType = 0;
  109773. if (this._engine.getCaps().textureHalfFloatRender) {
  109774. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  109775. }
  109776. else {
  109777. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109778. }
  109779. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  109780. width: blurTextureWidth,
  109781. height: blurTextureHeight
  109782. }, this._scene, false, true, textureType);
  109783. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109784. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109785. this._blurTexture.anisotropicFilteringLevel = 16;
  109786. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  109787. this._blurTexture.renderParticles = false;
  109788. this._blurTexture.ignoreCameraViewport = true;
  109789. this._textures = [this._blurTexture];
  109790. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  109791. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109792. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  109793. effect.setTexture("textureSampler", _this._mainTexture);
  109794. });
  109795. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109796. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109797. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109798. });
  109799. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109800. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  109801. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109802. });
  109803. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109804. }
  109805. else {
  109806. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  109807. width: blurTextureWidth,
  109808. height: blurTextureHeight
  109809. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109810. this._horizontalBlurPostprocess.width = blurTextureWidth;
  109811. this._horizontalBlurPostprocess.height = blurTextureHeight;
  109812. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109813. effect.setTexture("textureSampler", _this._mainTexture);
  109814. });
  109815. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  109816. width: blurTextureWidth,
  109817. height: blurTextureHeight
  109818. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109819. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109820. }
  109821. this._mainTexture.onAfterUnbindObservable.add(function () {
  109822. _this.onBeforeBlurObservable.notifyObservers(_this);
  109823. var internalTexture = _this._blurTexture.getInternalTexture();
  109824. if (internalTexture) {
  109825. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  109826. }
  109827. _this.onAfterBlurObservable.notifyObservers(_this);
  109828. });
  109829. // Prevent autoClear.
  109830. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  109831. };
  109832. /**
  109833. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  109834. */
  109835. HighlightLayer.prototype.needStencil = function () {
  109836. return true;
  109837. };
  109838. /**
  109839. * Checks for the readiness of the element composing the layer.
  109840. * @param subMesh the mesh to check for
  109841. * @param useInstances specify wether or not to use instances to render the mesh
  109842. * @param emissiveTexture the associated emissive texture used to generate the glow
  109843. * @return true if ready otherwise, false
  109844. */
  109845. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  109846. var material = subMesh.getMaterial();
  109847. var mesh = subMesh.getRenderingMesh();
  109848. if (!material || !mesh || !this._meshes) {
  109849. return false;
  109850. }
  109851. var emissiveTexture = null;
  109852. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109853. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109854. emissiveTexture = material.emissiveTexture;
  109855. }
  109856. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  109857. };
  109858. /**
  109859. * Implementation specific of rendering the generating effect on the main canvas.
  109860. * @param effect The effect used to render through
  109861. */
  109862. HighlightLayer.prototype._internalRender = function (effect) {
  109863. // Texture
  109864. effect.setTexture("textureSampler", this._blurTexture);
  109865. // Cache
  109866. var engine = this._engine;
  109867. var previousStencilBuffer = engine.getStencilBuffer();
  109868. var previousStencilFunction = engine.getStencilFunction();
  109869. var previousStencilMask = engine.getStencilMask();
  109870. var previousStencilOperationPass = engine.getStencilOperationPass();
  109871. var previousStencilOperationFail = engine.getStencilOperationFail();
  109872. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  109873. var previousStencilReference = engine.getStencilFunctionReference();
  109874. // Stencil operations
  109875. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  109876. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  109877. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  109878. // Draw order
  109879. engine.setStencilMask(0x00);
  109880. engine.setStencilBuffer(true);
  109881. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  109882. // 2 passes inner outer
  109883. if (this.outerGlow) {
  109884. effect.setFloat("offset", 0);
  109885. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  109886. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109887. }
  109888. if (this.innerGlow) {
  109889. effect.setFloat("offset", 1);
  109890. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  109891. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109892. }
  109893. // Restore Cache
  109894. engine.setStencilFunction(previousStencilFunction);
  109895. engine.setStencilMask(previousStencilMask);
  109896. engine.setStencilBuffer(previousStencilBuffer);
  109897. engine.setStencilOperationPass(previousStencilOperationPass);
  109898. engine.setStencilOperationFail(previousStencilOperationFail);
  109899. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  109900. engine.setStencilFunctionReference(previousStencilReference);
  109901. };
  109902. /**
  109903. * Returns true if the layer contains information to display, otherwise false.
  109904. */
  109905. HighlightLayer.prototype.shouldRender = function () {
  109906. if (_super.prototype.shouldRender.call(this)) {
  109907. return this._meshes ? true : false;
  109908. }
  109909. return false;
  109910. };
  109911. /**
  109912. * Returns true if the mesh should render, otherwise false.
  109913. * @param mesh The mesh to render
  109914. * @returns true if it should render otherwise false
  109915. */
  109916. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  109917. // Excluded Mesh
  109918. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  109919. return false;
  109920. }
  109921. if (!_super.prototype.hasMesh.call(this, mesh)) {
  109922. return false;
  109923. }
  109924. return true;
  109925. };
  109926. /**
  109927. * Sets the required values for both the emissive texture and and the main color.
  109928. */
  109929. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  109930. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109931. if (highlightLayerMesh) {
  109932. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  109933. }
  109934. else {
  109935. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  109936. }
  109937. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109938. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  109939. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  109940. }
  109941. else {
  109942. this._emissiveTextureAndColor.texture = null;
  109943. }
  109944. };
  109945. /**
  109946. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  109947. * @param mesh The mesh to exclude from the highlight layer
  109948. */
  109949. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  109950. if (!this._excludedMeshes) {
  109951. return;
  109952. }
  109953. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109954. if (!meshExcluded) {
  109955. this._excludedMeshes[mesh.uniqueId] = {
  109956. mesh: mesh,
  109957. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  109958. mesh.getEngine().setStencilBuffer(false);
  109959. }),
  109960. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  109961. mesh.getEngine().setStencilBuffer(true);
  109962. }),
  109963. };
  109964. }
  109965. };
  109966. /**
  109967. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  109968. * @param mesh The mesh to highlight
  109969. */
  109970. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  109971. if (!this._excludedMeshes) {
  109972. return;
  109973. }
  109974. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109975. if (meshExcluded) {
  109976. if (meshExcluded.beforeRender) {
  109977. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  109978. }
  109979. if (meshExcluded.afterRender) {
  109980. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  109981. }
  109982. }
  109983. this._excludedMeshes[mesh.uniqueId] = null;
  109984. };
  109985. /**
  109986. * Determine if a given mesh will be highlighted by the current HighlightLayer
  109987. * @param mesh mesh to test
  109988. * @returns true if the mesh will be highlighted by the current HighlightLayer
  109989. */
  109990. HighlightLayer.prototype.hasMesh = function (mesh) {
  109991. if (!this._meshes) {
  109992. return false;
  109993. }
  109994. if (!_super.prototype.hasMesh.call(this, mesh)) {
  109995. return false;
  109996. }
  109997. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  109998. };
  109999. /**
  110000. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  110001. * @param mesh The mesh to highlight
  110002. * @param color The color of the highlight
  110003. * @param glowEmissiveOnly Extract the glow from the emissive texture
  110004. */
  110005. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  110006. var _this = this;
  110007. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  110008. if (!this._meshes) {
  110009. return;
  110010. }
  110011. var meshHighlight = this._meshes[mesh.uniqueId];
  110012. if (meshHighlight) {
  110013. meshHighlight.color = color;
  110014. }
  110015. else {
  110016. this._meshes[mesh.uniqueId] = {
  110017. mesh: mesh,
  110018. color: color,
  110019. // Lambda required for capture due to Observable this context
  110020. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  110021. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  110022. _this._defaultStencilReference(mesh);
  110023. }
  110024. else {
  110025. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  110026. }
  110027. }),
  110028. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  110029. glowEmissiveOnly: glowEmissiveOnly
  110030. };
  110031. mesh.onDisposeObservable.add(function () {
  110032. _this._disposeMesh(mesh);
  110033. });
  110034. }
  110035. this._shouldRender = true;
  110036. };
  110037. /**
  110038. * Remove a mesh from the highlight layer in order to make it stop glowing.
  110039. * @param mesh The mesh to highlight
  110040. */
  110041. HighlightLayer.prototype.removeMesh = function (mesh) {
  110042. if (!this._meshes) {
  110043. return;
  110044. }
  110045. var meshHighlight = this._meshes[mesh.uniqueId];
  110046. if (meshHighlight) {
  110047. if (meshHighlight.observerHighlight) {
  110048. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  110049. }
  110050. if (meshHighlight.observerDefault) {
  110051. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  110052. }
  110053. delete this._meshes[mesh.uniqueId];
  110054. }
  110055. this._shouldRender = false;
  110056. for (var meshHighlightToCheck in this._meshes) {
  110057. if (this._meshes[meshHighlightToCheck]) {
  110058. this._shouldRender = true;
  110059. break;
  110060. }
  110061. }
  110062. };
  110063. /**
  110064. * Force the stencil to the normal expected value for none glowing parts
  110065. */
  110066. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  110067. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  110068. };
  110069. /**
  110070. * Free any resources and references associated to a mesh.
  110071. * Internal use
  110072. * @param mesh The mesh to free.
  110073. * @hidden
  110074. */
  110075. HighlightLayer.prototype._disposeMesh = function (mesh) {
  110076. this.removeMesh(mesh);
  110077. this.removeExcludedMesh(mesh);
  110078. };
  110079. /**
  110080. * Dispose the highlight layer and free resources.
  110081. */
  110082. HighlightLayer.prototype.dispose = function () {
  110083. if (this._meshes) {
  110084. // Clean mesh references
  110085. for (var id in this._meshes) {
  110086. var meshHighlight = this._meshes[id];
  110087. if (meshHighlight && meshHighlight.mesh) {
  110088. if (meshHighlight.observerHighlight) {
  110089. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  110090. }
  110091. if (meshHighlight.observerDefault) {
  110092. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  110093. }
  110094. }
  110095. }
  110096. this._meshes = null;
  110097. }
  110098. if (this._excludedMeshes) {
  110099. for (var id in this._excludedMeshes) {
  110100. var meshHighlight = this._excludedMeshes[id];
  110101. if (meshHighlight) {
  110102. if (meshHighlight.beforeRender) {
  110103. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  110104. }
  110105. if (meshHighlight.afterRender) {
  110106. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  110107. }
  110108. }
  110109. }
  110110. this._excludedMeshes = null;
  110111. }
  110112. _super.prototype.dispose.call(this);
  110113. };
  110114. /**
  110115. * Gets the class name of the effect layer
  110116. * @returns the string with the class name of the effect layer
  110117. */
  110118. HighlightLayer.prototype.getClassName = function () {
  110119. return "HighlightLayer";
  110120. };
  110121. /**
  110122. * Serializes this Highlight layer
  110123. * @returns a serialized Highlight layer object
  110124. */
  110125. HighlightLayer.prototype.serialize = function () {
  110126. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110127. serializationObject.customType = "BABYLON.HighlightLayer";
  110128. // Highlighted meshes
  110129. serializationObject.meshes = [];
  110130. if (this._meshes) {
  110131. for (var m in this._meshes) {
  110132. var mesh = this._meshes[m];
  110133. if (mesh) {
  110134. serializationObject.meshes.push({
  110135. glowEmissiveOnly: mesh.glowEmissiveOnly,
  110136. color: mesh.color.asArray(),
  110137. meshId: mesh.mesh.id
  110138. });
  110139. }
  110140. }
  110141. }
  110142. // Excluded meshes
  110143. serializationObject.excludedMeshes = [];
  110144. if (this._excludedMeshes) {
  110145. for (var e in this._excludedMeshes) {
  110146. var excludedMesh = this._excludedMeshes[e];
  110147. if (excludedMesh) {
  110148. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  110149. }
  110150. }
  110151. }
  110152. return serializationObject;
  110153. };
  110154. /**
  110155. * Creates a Highlight layer from parsed Highlight layer data
  110156. * @param parsedHightlightLayer defines the Highlight layer data
  110157. * @param scene defines the current scene
  110158. * @param rootUrl defines the root URL containing the Highlight layer information
  110159. * @returns a parsed Highlight layer
  110160. */
  110161. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  110162. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  110163. var index;
  110164. // Excluded meshes
  110165. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  110166. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  110167. if (mesh) {
  110168. hl.addExcludedMesh(mesh);
  110169. }
  110170. }
  110171. // Included meshes
  110172. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  110173. var highlightedMesh = parsedHightlightLayer.meshes[index];
  110174. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  110175. if (mesh) {
  110176. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  110177. }
  110178. }
  110179. return hl;
  110180. };
  110181. /**
  110182. * Effect Name of the highlight layer.
  110183. */
  110184. HighlightLayer.EffectName = "HighlightLayer";
  110185. /**
  110186. * The neutral color used during the preparation of the glow effect.
  110187. * This is black by default as the blend operation is a blend operation.
  110188. */
  110189. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  110190. /**
  110191. * Stencil value used for glowing meshes.
  110192. */
  110193. HighlightLayer.GlowingMeshStencilReference = 0x02;
  110194. /**
  110195. * Stencil value used for the other meshes in the scene.
  110196. */
  110197. HighlightLayer.NormalMeshStencilReference = 0x01;
  110198. __decorate([
  110199. BABYLON.serialize()
  110200. ], HighlightLayer.prototype, "innerGlow", void 0);
  110201. __decorate([
  110202. BABYLON.serialize()
  110203. ], HighlightLayer.prototype, "outerGlow", void 0);
  110204. __decorate([
  110205. BABYLON.serialize()
  110206. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  110207. __decorate([
  110208. BABYLON.serialize()
  110209. ], HighlightLayer.prototype, "blurVerticalSize", null);
  110210. __decorate([
  110211. BABYLON.serialize("options")
  110212. ], HighlightLayer.prototype, "_options", void 0);
  110213. return HighlightLayer;
  110214. }(BABYLON.EffectLayer));
  110215. BABYLON.HighlightLayer = HighlightLayer;
  110216. })(BABYLON || (BABYLON = {}));
  110217. //# sourceMappingURL=babylon.highlightLayer.js.map
  110218. var BABYLON;
  110219. (function (BABYLON) {
  110220. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  110221. for (var index = 0; index < this.effectLayers.length; index++) {
  110222. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  110223. return this.effectLayers[index];
  110224. }
  110225. }
  110226. return null;
  110227. };
  110228. /**
  110229. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  110230. *
  110231. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  110232. * glowy meshes to your scene.
  110233. *
  110234. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  110235. */
  110236. var GlowLayer = /** @class */ (function (_super) {
  110237. __extends(GlowLayer, _super);
  110238. /**
  110239. * Instantiates a new glow Layer and references it to the scene.
  110240. * @param name The name of the layer
  110241. * @param scene The scene to use the layer in
  110242. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  110243. */
  110244. function GlowLayer(name, scene, options) {
  110245. var _this = _super.call(this, name, scene) || this;
  110246. _this._intensity = 1.0;
  110247. _this._includedOnlyMeshes = [];
  110248. _this._excludedMeshes = [];
  110249. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  110250. // Adapt options
  110251. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  110252. // Initialize the layer
  110253. _this._init({
  110254. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  110255. camera: _this._options.camera,
  110256. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  110257. mainTextureRatio: _this._options.mainTextureRatio,
  110258. renderingGroupId: _this._options.renderingGroupId
  110259. });
  110260. return _this;
  110261. }
  110262. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  110263. /**
  110264. * Gets the kernel size of the blur.
  110265. */
  110266. get: function () {
  110267. return this._horizontalBlurPostprocess1.kernel;
  110268. },
  110269. /**
  110270. * Sets the kernel size of the blur.
  110271. */
  110272. set: function (value) {
  110273. this._horizontalBlurPostprocess1.kernel = value;
  110274. this._verticalBlurPostprocess1.kernel = value;
  110275. this._horizontalBlurPostprocess2.kernel = value;
  110276. this._verticalBlurPostprocess2.kernel = value;
  110277. },
  110278. enumerable: true,
  110279. configurable: true
  110280. });
  110281. Object.defineProperty(GlowLayer.prototype, "intensity", {
  110282. /**
  110283. * Gets the glow intensity.
  110284. */
  110285. get: function () {
  110286. return this._intensity;
  110287. },
  110288. /**
  110289. * Sets the glow intensity.
  110290. */
  110291. set: function (value) {
  110292. this._intensity = value;
  110293. },
  110294. enumerable: true,
  110295. configurable: true
  110296. });
  110297. /**
  110298. * Get the effect name of the layer.
  110299. * @return The effect name
  110300. */
  110301. GlowLayer.prototype.getEffectName = function () {
  110302. return GlowLayer.EffectName;
  110303. };
  110304. /**
  110305. * Create the merge effect. This is the shader use to blit the information back
  110306. * to the main canvas at the end of the scene rendering.
  110307. */
  110308. GlowLayer.prototype._createMergeEffect = function () {
  110309. // Effect
  110310. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  110311. };
  110312. /**
  110313. * Creates the render target textures and post processes used in the glow layer.
  110314. */
  110315. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  110316. var _this = this;
  110317. var blurTextureWidth = this._mainTextureDesiredSize.width;
  110318. var blurTextureHeight = this._mainTextureDesiredSize.height;
  110319. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  110320. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  110321. var textureType = 0;
  110322. if (this._engine.getCaps().textureHalfFloatRender) {
  110323. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  110324. }
  110325. else {
  110326. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  110327. }
  110328. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  110329. width: blurTextureWidth,
  110330. height: blurTextureHeight
  110331. }, this._scene, false, true, textureType);
  110332. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110333. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110334. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110335. this._blurTexture1.renderParticles = false;
  110336. this._blurTexture1.ignoreCameraViewport = true;
  110337. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  110338. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  110339. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  110340. width: blurTextureWidth2,
  110341. height: blurTextureHeight2
  110342. }, this._scene, false, true, textureType);
  110343. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110344. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110345. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110346. this._blurTexture2.renderParticles = false;
  110347. this._blurTexture2.ignoreCameraViewport = true;
  110348. this._textures = [this._blurTexture1, this._blurTexture2];
  110349. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110350. width: blurTextureWidth,
  110351. height: blurTextureHeight
  110352. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110353. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  110354. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  110355. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  110356. effect.setTexture("textureSampler", _this._mainTexture);
  110357. });
  110358. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110359. width: blurTextureWidth,
  110360. height: blurTextureHeight
  110361. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110362. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110363. width: blurTextureWidth2,
  110364. height: blurTextureHeight2
  110365. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110366. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  110367. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  110368. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  110369. effect.setTexture("textureSampler", _this._blurTexture1);
  110370. });
  110371. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110372. width: blurTextureWidth2,
  110373. height: blurTextureHeight2
  110374. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110375. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110376. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  110377. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110378. this._mainTexture.samples = this._options.mainTextureSamples;
  110379. this._mainTexture.onAfterUnbindObservable.add(function () {
  110380. var internalTexture = _this._blurTexture1.getInternalTexture();
  110381. if (internalTexture) {
  110382. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  110383. internalTexture = _this._blurTexture2.getInternalTexture();
  110384. if (internalTexture) {
  110385. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  110386. }
  110387. }
  110388. });
  110389. // Prevent autoClear.
  110390. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  110391. };
  110392. /**
  110393. * Checks for the readiness of the element composing the layer.
  110394. * @param subMesh the mesh to check for
  110395. * @param useInstances specify wether or not to use instances to render the mesh
  110396. * @param emissiveTexture the associated emissive texture used to generate the glow
  110397. * @return true if ready otherwise, false
  110398. */
  110399. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  110400. var material = subMesh.getMaterial();
  110401. var mesh = subMesh.getRenderingMesh();
  110402. if (!material || !mesh) {
  110403. return false;
  110404. }
  110405. var emissiveTexture = material.emissiveTexture;
  110406. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  110407. };
  110408. /**
  110409. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  110410. */
  110411. GlowLayer.prototype.needStencil = function () {
  110412. return false;
  110413. };
  110414. /**
  110415. * Implementation specific of rendering the generating effect on the main canvas.
  110416. * @param effect The effect used to render through
  110417. */
  110418. GlowLayer.prototype._internalRender = function (effect) {
  110419. // Texture
  110420. effect.setTexture("textureSampler", this._blurTexture1);
  110421. effect.setTexture("textureSampler2", this._blurTexture2);
  110422. effect.setFloat("offset", this._intensity);
  110423. // Cache
  110424. var engine = this._engine;
  110425. var previousStencilBuffer = engine.getStencilBuffer();
  110426. // Draw order
  110427. engine.setStencilBuffer(false);
  110428. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110429. // Draw order
  110430. engine.setStencilBuffer(previousStencilBuffer);
  110431. };
  110432. /**
  110433. * Sets the required values for both the emissive texture and and the main color.
  110434. */
  110435. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  110436. var textureLevel = 1.0;
  110437. if (this.customEmissiveTextureSelector) {
  110438. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  110439. }
  110440. else {
  110441. if (material) {
  110442. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  110443. if (this._emissiveTextureAndColor.texture) {
  110444. textureLevel = this._emissiveTextureAndColor.texture.level;
  110445. }
  110446. }
  110447. else {
  110448. this._emissiveTextureAndColor.texture = null;
  110449. }
  110450. }
  110451. if (this.customEmissiveColorSelector) {
  110452. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  110453. }
  110454. else {
  110455. if (material.emissiveColor) {
  110456. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  110457. }
  110458. else {
  110459. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  110460. }
  110461. }
  110462. };
  110463. /**
  110464. * Returns true if the mesh should render, otherwise false.
  110465. * @param mesh The mesh to render
  110466. * @returns true if it should render otherwise false
  110467. */
  110468. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  110469. return this.hasMesh(mesh);
  110470. };
  110471. /**
  110472. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  110473. * @param mesh The mesh to exclude from the glow layer
  110474. */
  110475. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  110476. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  110477. this._excludedMeshes.push(mesh.uniqueId);
  110478. }
  110479. };
  110480. /**
  110481. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  110482. * @param mesh The mesh to remove
  110483. */
  110484. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  110485. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  110486. if (index !== -1) {
  110487. this._excludedMeshes.splice(index, 1);
  110488. }
  110489. };
  110490. /**
  110491. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  110492. * @param mesh The mesh to include in the glow layer
  110493. */
  110494. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  110495. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  110496. this._includedOnlyMeshes.push(mesh.uniqueId);
  110497. }
  110498. };
  110499. /**
  110500. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  110501. * @param mesh The mesh to remove
  110502. */
  110503. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  110504. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  110505. if (index !== -1) {
  110506. this._includedOnlyMeshes.splice(index, 1);
  110507. }
  110508. };
  110509. /**
  110510. * Determine if a given mesh will be used in the glow layer
  110511. * @param mesh The mesh to test
  110512. * @returns true if the mesh will be highlighted by the current glow layer
  110513. */
  110514. GlowLayer.prototype.hasMesh = function (mesh) {
  110515. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110516. return false;
  110517. }
  110518. // Included Mesh
  110519. if (this._includedOnlyMeshes.length) {
  110520. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  110521. }
  110522. // Excluded Mesh
  110523. if (this._excludedMeshes.length) {
  110524. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  110525. }
  110526. return true;
  110527. };
  110528. /**
  110529. * Free any resources and references associated to a mesh.
  110530. * Internal use
  110531. * @param mesh The mesh to free.
  110532. * @hidden
  110533. */
  110534. GlowLayer.prototype._disposeMesh = function (mesh) {
  110535. this.removeIncludedOnlyMesh(mesh);
  110536. this.removeExcludedMesh(mesh);
  110537. };
  110538. /**
  110539. * Gets the class name of the effect layer
  110540. * @returns the string with the class name of the effect layer
  110541. */
  110542. GlowLayer.prototype.getClassName = function () {
  110543. return "GlowLayer";
  110544. };
  110545. /**
  110546. * Serializes this glow layer
  110547. * @returns a serialized glow layer object
  110548. */
  110549. GlowLayer.prototype.serialize = function () {
  110550. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110551. serializationObject.customType = "BABYLON.GlowLayer";
  110552. var index;
  110553. // Included meshes
  110554. serializationObject.includedMeshes = [];
  110555. if (this._includedOnlyMeshes.length) {
  110556. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  110557. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  110558. if (mesh) {
  110559. serializationObject.includedMeshes.push(mesh.id);
  110560. }
  110561. }
  110562. }
  110563. // Excluded meshes
  110564. serializationObject.excludedMeshes = [];
  110565. if (this._excludedMeshes.length) {
  110566. for (index = 0; index < this._excludedMeshes.length; index++) {
  110567. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  110568. if (mesh) {
  110569. serializationObject.excludedMeshes.push(mesh.id);
  110570. }
  110571. }
  110572. }
  110573. return serializationObject;
  110574. };
  110575. /**
  110576. * Creates a Glow Layer from parsed glow layer data
  110577. * @param parsedGlowLayer defines glow layer data
  110578. * @param scene defines the current scene
  110579. * @param rootUrl defines the root URL containing the glow layer information
  110580. * @returns a parsed Glow Layer
  110581. */
  110582. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  110583. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  110584. var index;
  110585. // Excluded meshes
  110586. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  110587. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  110588. if (mesh) {
  110589. gl.addExcludedMesh(mesh);
  110590. }
  110591. }
  110592. // Included meshes
  110593. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  110594. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  110595. if (mesh) {
  110596. gl.addIncludedOnlyMesh(mesh);
  110597. }
  110598. }
  110599. return gl;
  110600. };
  110601. /**
  110602. * Effect Name of the layer.
  110603. */
  110604. GlowLayer.EffectName = "GlowLayer";
  110605. /**
  110606. * The default blur kernel size used for the glow.
  110607. */
  110608. GlowLayer.DefaultBlurKernelSize = 32;
  110609. /**
  110610. * The default texture size ratio used for the glow.
  110611. */
  110612. GlowLayer.DefaultTextureRatio = 0.5;
  110613. __decorate([
  110614. BABYLON.serialize()
  110615. ], GlowLayer.prototype, "blurKernelSize", null);
  110616. __decorate([
  110617. BABYLON.serialize()
  110618. ], GlowLayer.prototype, "intensity", null);
  110619. __decorate([
  110620. BABYLON.serialize("options")
  110621. ], GlowLayer.prototype, "_options", void 0);
  110622. return GlowLayer;
  110623. }(BABYLON.EffectLayer));
  110624. BABYLON.GlowLayer = GlowLayer;
  110625. })(BABYLON || (BABYLON = {}));
  110626. //# sourceMappingURL=babylon.glowLayer.js.map
  110627. var BABYLON;
  110628. (function (BABYLON) {
  110629. /**
  110630. * Defines the list of states available for a task inside a AssetsManager
  110631. */
  110632. var AssetTaskState;
  110633. (function (AssetTaskState) {
  110634. /**
  110635. * Initialization
  110636. */
  110637. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  110638. /**
  110639. * Running
  110640. */
  110641. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  110642. /**
  110643. * Done
  110644. */
  110645. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  110646. /**
  110647. * Error
  110648. */
  110649. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  110650. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  110651. /**
  110652. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  110653. */
  110654. var AbstractAssetTask = /** @class */ (function () {
  110655. /**
  110656. * Creates a new AssetsManager
  110657. * @param name defines the name of the task
  110658. */
  110659. function AbstractAssetTask(
  110660. /**
  110661. * Task name
  110662. */ name) {
  110663. this.name = name;
  110664. this._isCompleted = false;
  110665. this._taskState = AssetTaskState.INIT;
  110666. }
  110667. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  110668. /**
  110669. * Get if the task is completed
  110670. */
  110671. get: function () {
  110672. return this._isCompleted;
  110673. },
  110674. enumerable: true,
  110675. configurable: true
  110676. });
  110677. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  110678. /**
  110679. * Gets the current state of the task
  110680. */
  110681. get: function () {
  110682. return this._taskState;
  110683. },
  110684. enumerable: true,
  110685. configurable: true
  110686. });
  110687. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  110688. /**
  110689. * Gets the current error object (if task is in error)
  110690. */
  110691. get: function () {
  110692. return this._errorObject;
  110693. },
  110694. enumerable: true,
  110695. configurable: true
  110696. });
  110697. /**
  110698. * Internal only
  110699. * @hidden
  110700. */
  110701. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  110702. if (this._errorObject) {
  110703. return;
  110704. }
  110705. this._errorObject = {
  110706. message: message,
  110707. exception: exception
  110708. };
  110709. };
  110710. /**
  110711. * Execute the current task
  110712. * @param scene defines the scene where you want your assets to be loaded
  110713. * @param onSuccess is a callback called when the task is successfully executed
  110714. * @param onError is a callback called if an error occurs
  110715. */
  110716. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  110717. var _this = this;
  110718. this._taskState = AssetTaskState.RUNNING;
  110719. this.runTask(scene, function () {
  110720. _this.onDoneCallback(onSuccess, onError);
  110721. }, function (msg, exception) {
  110722. _this.onErrorCallback(onError, msg, exception);
  110723. });
  110724. };
  110725. /**
  110726. * Execute the current task
  110727. * @param scene defines the scene where you want your assets to be loaded
  110728. * @param onSuccess is a callback called when the task is successfully executed
  110729. * @param onError is a callback called if an error occurs
  110730. */
  110731. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110732. throw new Error("runTask is not implemented");
  110733. };
  110734. /**
  110735. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  110736. * This can be used with failed tasks that have the reason for failure fixed.
  110737. */
  110738. AbstractAssetTask.prototype.reset = function () {
  110739. this._taskState = AssetTaskState.INIT;
  110740. };
  110741. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  110742. this._taskState = AssetTaskState.ERROR;
  110743. this._errorObject = {
  110744. message: message,
  110745. exception: exception
  110746. };
  110747. if (this.onError) {
  110748. this.onError(this, message, exception);
  110749. }
  110750. onError();
  110751. };
  110752. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  110753. try {
  110754. this._taskState = AssetTaskState.DONE;
  110755. this._isCompleted = true;
  110756. if (this.onSuccess) {
  110757. this.onSuccess(this);
  110758. }
  110759. onSuccess();
  110760. }
  110761. catch (e) {
  110762. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  110763. }
  110764. };
  110765. return AbstractAssetTask;
  110766. }());
  110767. BABYLON.AbstractAssetTask = AbstractAssetTask;
  110768. /**
  110769. * Class used to share progress information about assets loading
  110770. */
  110771. var AssetsProgressEvent = /** @class */ (function () {
  110772. /**
  110773. * Creates a AssetsProgressEvent
  110774. * @param remainingCount defines the number of remaining tasks to process
  110775. * @param totalCount defines the total number of tasks
  110776. * @param task defines the task that was just processed
  110777. */
  110778. function AssetsProgressEvent(remainingCount, totalCount, task) {
  110779. this.remainingCount = remainingCount;
  110780. this.totalCount = totalCount;
  110781. this.task = task;
  110782. }
  110783. return AssetsProgressEvent;
  110784. }());
  110785. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  110786. /**
  110787. * Define a task used by AssetsManager to load meshes
  110788. */
  110789. var MeshAssetTask = /** @class */ (function (_super) {
  110790. __extends(MeshAssetTask, _super);
  110791. /**
  110792. * Creates a new MeshAssetTask
  110793. * @param name defines the name of the task
  110794. * @param meshesNames defines the list of mesh's names you want to load
  110795. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  110796. * @param sceneFilename defines the filename of the scene to load from
  110797. */
  110798. function MeshAssetTask(
  110799. /**
  110800. * Defines the name of the task
  110801. */
  110802. name,
  110803. /**
  110804. * Defines the list of mesh's names you want to load
  110805. */
  110806. meshesNames,
  110807. /**
  110808. * Defines the root url to use as a base to load your meshes and associated resources
  110809. */
  110810. rootUrl,
  110811. /**
  110812. * Defines the filename of the scene to load from
  110813. */
  110814. sceneFilename) {
  110815. var _this = _super.call(this, name) || this;
  110816. _this.name = name;
  110817. _this.meshesNames = meshesNames;
  110818. _this.rootUrl = rootUrl;
  110819. _this.sceneFilename = sceneFilename;
  110820. return _this;
  110821. }
  110822. /**
  110823. * Execute the current task
  110824. * @param scene defines the scene where you want your assets to be loaded
  110825. * @param onSuccess is a callback called when the task is successfully executed
  110826. * @param onError is a callback called if an error occurs
  110827. */
  110828. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110829. var _this = this;
  110830. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  110831. _this.loadedMeshes = meshes;
  110832. _this.loadedParticleSystems = particleSystems;
  110833. _this.loadedSkeletons = skeletons;
  110834. onSuccess();
  110835. }, null, function (scene, message, exception) {
  110836. onError(message, exception);
  110837. });
  110838. };
  110839. return MeshAssetTask;
  110840. }(AbstractAssetTask));
  110841. BABYLON.MeshAssetTask = MeshAssetTask;
  110842. /**
  110843. * Define a task used by AssetsManager to load text content
  110844. */
  110845. var TextFileAssetTask = /** @class */ (function (_super) {
  110846. __extends(TextFileAssetTask, _super);
  110847. /**
  110848. * Creates a new TextFileAssetTask object
  110849. * @param name defines the name of the task
  110850. * @param url defines the location of the file to load
  110851. */
  110852. function TextFileAssetTask(
  110853. /**
  110854. * Defines the name of the task
  110855. */
  110856. name,
  110857. /**
  110858. * Defines the location of the file to load
  110859. */
  110860. url) {
  110861. var _this = _super.call(this, name) || this;
  110862. _this.name = name;
  110863. _this.url = url;
  110864. return _this;
  110865. }
  110866. /**
  110867. * Execute the current task
  110868. * @param scene defines the scene where you want your assets to be loaded
  110869. * @param onSuccess is a callback called when the task is successfully executed
  110870. * @param onError is a callback called if an error occurs
  110871. */
  110872. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110873. var _this = this;
  110874. scene._loadFile(this.url, function (data) {
  110875. _this.text = data;
  110876. onSuccess();
  110877. }, undefined, false, false, function (request, exception) {
  110878. if (request) {
  110879. onError(request.status + " " + request.statusText, exception);
  110880. }
  110881. });
  110882. };
  110883. return TextFileAssetTask;
  110884. }(AbstractAssetTask));
  110885. BABYLON.TextFileAssetTask = TextFileAssetTask;
  110886. /**
  110887. * Define a task used by AssetsManager to load binary data
  110888. */
  110889. var BinaryFileAssetTask = /** @class */ (function (_super) {
  110890. __extends(BinaryFileAssetTask, _super);
  110891. /**
  110892. * Creates a new BinaryFileAssetTask object
  110893. * @param name defines the name of the new task
  110894. * @param url defines the location of the file to load
  110895. */
  110896. function BinaryFileAssetTask(
  110897. /**
  110898. * Defines the name of the task
  110899. */
  110900. name,
  110901. /**
  110902. * Defines the location of the file to load
  110903. */
  110904. url) {
  110905. var _this = _super.call(this, name) || this;
  110906. _this.name = name;
  110907. _this.url = url;
  110908. return _this;
  110909. }
  110910. /**
  110911. * Execute the current task
  110912. * @param scene defines the scene where you want your assets to be loaded
  110913. * @param onSuccess is a callback called when the task is successfully executed
  110914. * @param onError is a callback called if an error occurs
  110915. */
  110916. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110917. var _this = this;
  110918. scene._loadFile(this.url, function (data) {
  110919. _this.data = data;
  110920. onSuccess();
  110921. }, undefined, true, true, function (request, exception) {
  110922. if (request) {
  110923. onError(request.status + " " + request.statusText, exception);
  110924. }
  110925. });
  110926. };
  110927. return BinaryFileAssetTask;
  110928. }(AbstractAssetTask));
  110929. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  110930. /**
  110931. * Define a task used by AssetsManager to load images
  110932. */
  110933. var ImageAssetTask = /** @class */ (function (_super) {
  110934. __extends(ImageAssetTask, _super);
  110935. /**
  110936. * Creates a new ImageAssetTask
  110937. * @param name defines the name of the task
  110938. * @param url defines the location of the image to load
  110939. */
  110940. function ImageAssetTask(
  110941. /**
  110942. * Defines the name of the task
  110943. */
  110944. name,
  110945. /**
  110946. * Defines the location of the image to load
  110947. */
  110948. url) {
  110949. var _this = _super.call(this, name) || this;
  110950. _this.name = name;
  110951. _this.url = url;
  110952. return _this;
  110953. }
  110954. /**
  110955. * Execute the current task
  110956. * @param scene defines the scene where you want your assets to be loaded
  110957. * @param onSuccess is a callback called when the task is successfully executed
  110958. * @param onError is a callback called if an error occurs
  110959. */
  110960. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110961. var _this = this;
  110962. var img = new Image();
  110963. BABYLON.Tools.SetCorsBehavior(this.url, img);
  110964. img.onload = function () {
  110965. _this.image = img;
  110966. onSuccess();
  110967. };
  110968. img.onerror = function (err) {
  110969. onError("Error loading image", err);
  110970. };
  110971. img.src = this.url;
  110972. };
  110973. return ImageAssetTask;
  110974. }(AbstractAssetTask));
  110975. BABYLON.ImageAssetTask = ImageAssetTask;
  110976. /**
  110977. * Define a task used by AssetsManager to load 2D textures
  110978. */
  110979. var TextureAssetTask = /** @class */ (function (_super) {
  110980. __extends(TextureAssetTask, _super);
  110981. /**
  110982. * Creates a new TextureAssetTask object
  110983. * @param name defines the name of the task
  110984. * @param url defines the location of the file to load
  110985. * @param noMipmap defines if mipmap should not be generated (default is false)
  110986. * @param invertY defines if texture must be inverted on Y axis (default is false)
  110987. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  110988. */
  110989. function TextureAssetTask(
  110990. /**
  110991. * Defines the name of the task
  110992. */
  110993. name,
  110994. /**
  110995. * Defines the location of the file to load
  110996. */
  110997. url,
  110998. /**
  110999. * Defines if mipmap should not be generated (default is false)
  111000. */
  111001. noMipmap,
  111002. /**
  111003. * Defines if texture must be inverted on Y axis (default is false)
  111004. */
  111005. invertY,
  111006. /**
  111007. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  111008. */
  111009. samplingMode) {
  111010. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111011. var _this = _super.call(this, name) || this;
  111012. _this.name = name;
  111013. _this.url = url;
  111014. _this.noMipmap = noMipmap;
  111015. _this.invertY = invertY;
  111016. _this.samplingMode = samplingMode;
  111017. return _this;
  111018. }
  111019. /**
  111020. * Execute the current task
  111021. * @param scene defines the scene where you want your assets to be loaded
  111022. * @param onSuccess is a callback called when the task is successfully executed
  111023. * @param onError is a callback called if an error occurs
  111024. */
  111025. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  111026. var onload = function () {
  111027. onSuccess();
  111028. };
  111029. var onerror = function (message, exception) {
  111030. onError(message, exception);
  111031. };
  111032. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  111033. };
  111034. return TextureAssetTask;
  111035. }(AbstractAssetTask));
  111036. BABYLON.TextureAssetTask = TextureAssetTask;
  111037. /**
  111038. * Define a task used by AssetsManager to load cube textures
  111039. */
  111040. var CubeTextureAssetTask = /** @class */ (function (_super) {
  111041. __extends(CubeTextureAssetTask, _super);
  111042. /**
  111043. * Creates a new CubeTextureAssetTask
  111044. * @param name defines the name of the task
  111045. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  111046. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  111047. * @param noMipmap defines if mipmaps should not be generated (default is false)
  111048. * @param files defines the explicit list of files (undefined by default)
  111049. */
  111050. function CubeTextureAssetTask(
  111051. /**
  111052. * Defines the name of the task
  111053. */
  111054. name,
  111055. /**
  111056. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  111057. */
  111058. url,
  111059. /**
  111060. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  111061. */
  111062. extensions,
  111063. /**
  111064. * Defines if mipmaps should not be generated (default is false)
  111065. */
  111066. noMipmap,
  111067. /**
  111068. * Defines the explicit list of files (undefined by default)
  111069. */
  111070. files) {
  111071. var _this = _super.call(this, name) || this;
  111072. _this.name = name;
  111073. _this.url = url;
  111074. _this.extensions = extensions;
  111075. _this.noMipmap = noMipmap;
  111076. _this.files = files;
  111077. return _this;
  111078. }
  111079. /**
  111080. * Execute the current task
  111081. * @param scene defines the scene where you want your assets to be loaded
  111082. * @param onSuccess is a callback called when the task is successfully executed
  111083. * @param onError is a callback called if an error occurs
  111084. */
  111085. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  111086. var onload = function () {
  111087. onSuccess();
  111088. };
  111089. var onerror = function (message, exception) {
  111090. onError(message, exception);
  111091. };
  111092. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  111093. };
  111094. return CubeTextureAssetTask;
  111095. }(AbstractAssetTask));
  111096. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  111097. /**
  111098. * Define a task used by AssetsManager to load HDR cube textures
  111099. */
  111100. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  111101. __extends(HDRCubeTextureAssetTask, _super);
  111102. /**
  111103. * Creates a new HDRCubeTextureAssetTask object
  111104. * @param name defines the name of the task
  111105. * @param url defines the location of the file to load
  111106. * @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.
  111107. * @param noMipmap defines if mipmaps should not be generated (default is false)
  111108. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  111109. * @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)
  111110. * @param reserved Internal use only
  111111. */
  111112. function HDRCubeTextureAssetTask(
  111113. /**
  111114. * Defines the name of the task
  111115. */
  111116. name,
  111117. /**
  111118. * Defines the location of the file to load
  111119. */
  111120. url,
  111121. /**
  111122. * Defines the desired size (the more it increases the longer the generation will be)
  111123. */
  111124. size,
  111125. /**
  111126. * Defines if mipmaps should not be generated (default is false)
  111127. */
  111128. noMipmap,
  111129. /**
  111130. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  111131. */
  111132. generateHarmonics,
  111133. /**
  111134. * 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)
  111135. */
  111136. gammaSpace,
  111137. /**
  111138. * Internal Use Only
  111139. */
  111140. reserved) {
  111141. if (noMipmap === void 0) { noMipmap = false; }
  111142. if (generateHarmonics === void 0) { generateHarmonics = true; }
  111143. if (gammaSpace === void 0) { gammaSpace = false; }
  111144. if (reserved === void 0) { reserved = false; }
  111145. var _this = _super.call(this, name) || this;
  111146. _this.name = name;
  111147. _this.url = url;
  111148. _this.size = size;
  111149. _this.noMipmap = noMipmap;
  111150. _this.generateHarmonics = generateHarmonics;
  111151. _this.gammaSpace = gammaSpace;
  111152. _this.reserved = reserved;
  111153. return _this;
  111154. }
  111155. /**
  111156. * Execute the current task
  111157. * @param scene defines the scene where you want your assets to be loaded
  111158. * @param onSuccess is a callback called when the task is successfully executed
  111159. * @param onError is a callback called if an error occurs
  111160. */
  111161. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  111162. var onload = function () {
  111163. onSuccess();
  111164. };
  111165. var onerror = function (message, exception) {
  111166. onError(message, exception);
  111167. };
  111168. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  111169. };
  111170. return HDRCubeTextureAssetTask;
  111171. }(AbstractAssetTask));
  111172. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  111173. /**
  111174. * This class can be used to easily import assets into a scene
  111175. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  111176. */
  111177. var AssetsManager = /** @class */ (function () {
  111178. /**
  111179. * Creates a new AssetsManager
  111180. * @param scene defines the scene to work on
  111181. */
  111182. function AssetsManager(scene) {
  111183. this._isLoading = false;
  111184. this._tasks = new Array();
  111185. this._waitingTasksCount = 0;
  111186. this._totalTasksCount = 0;
  111187. /**
  111188. * Observable called when all tasks are processed
  111189. */
  111190. this.onTaskSuccessObservable = new BABYLON.Observable();
  111191. /**
  111192. * Observable called when a task had an error
  111193. */
  111194. this.onTaskErrorObservable = new BABYLON.Observable();
  111195. /**
  111196. * Observable called when a task is successful
  111197. */
  111198. this.onTasksDoneObservable = new BABYLON.Observable();
  111199. /**
  111200. * Observable called when a task is done (whatever the result is)
  111201. */
  111202. this.onProgressObservable = new BABYLON.Observable();
  111203. /**
  111204. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  111205. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  111206. */
  111207. this.useDefaultLoadingScreen = true;
  111208. this._scene = scene;
  111209. }
  111210. /**
  111211. * Add a MeshAssetTask to the list of active tasks
  111212. * @param taskName defines the name of the new task
  111213. * @param meshesNames defines the name of meshes to load
  111214. * @param rootUrl defines the root url to use to locate files
  111215. * @param sceneFilename defines the filename of the scene file
  111216. * @returns a new MeshAssetTask object
  111217. */
  111218. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  111219. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  111220. this._tasks.push(task);
  111221. return task;
  111222. };
  111223. /**
  111224. * Add a TextFileAssetTask to the list of active tasks
  111225. * @param taskName defines the name of the new task
  111226. * @param url defines the url of the file to load
  111227. * @returns a new TextFileAssetTask object
  111228. */
  111229. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  111230. var task = new TextFileAssetTask(taskName, url);
  111231. this._tasks.push(task);
  111232. return task;
  111233. };
  111234. /**
  111235. * Add a BinaryFileAssetTask to the list of active tasks
  111236. * @param taskName defines the name of the new task
  111237. * @param url defines the url of the file to load
  111238. * @returns a new BinaryFileAssetTask object
  111239. */
  111240. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  111241. var task = new BinaryFileAssetTask(taskName, url);
  111242. this._tasks.push(task);
  111243. return task;
  111244. };
  111245. /**
  111246. * Add a ImageAssetTask to the list of active tasks
  111247. * @param taskName defines the name of the new task
  111248. * @param url defines the url of the file to load
  111249. * @returns a new ImageAssetTask object
  111250. */
  111251. AssetsManager.prototype.addImageTask = function (taskName, url) {
  111252. var task = new ImageAssetTask(taskName, url);
  111253. this._tasks.push(task);
  111254. return task;
  111255. };
  111256. /**
  111257. * Add a TextureAssetTask to the list of active tasks
  111258. * @param taskName defines the name of the new task
  111259. * @param url defines the url of the file to load
  111260. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111261. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  111262. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  111263. * @returns a new TextureAssetTask object
  111264. */
  111265. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  111266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111267. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  111268. this._tasks.push(task);
  111269. return task;
  111270. };
  111271. /**
  111272. * Add a CubeTextureAssetTask to the list of active tasks
  111273. * @param taskName defines the name of the new task
  111274. * @param url defines the url of the file to load
  111275. * @param extensions defines the extension to use to load the cube map (can be null)
  111276. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111277. * @param files defines the list of files to load (can be null)
  111278. * @returns a new CubeTextureAssetTask object
  111279. */
  111280. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  111281. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  111282. this._tasks.push(task);
  111283. return task;
  111284. };
  111285. /**
  111286. *
  111287. * Add a HDRCubeTextureAssetTask to the list of active tasks
  111288. * @param taskName defines the name of the new task
  111289. * @param url defines the url of the file to load
  111290. * @param size defines the size you want for the cubemap (can be null)
  111291. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111292. * @param generateHarmonics defines if you want to automatically generate (true by default)
  111293. * @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)
  111294. * @param reserved Internal use only
  111295. * @returns a new HDRCubeTextureAssetTask object
  111296. */
  111297. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  111298. if (noMipmap === void 0) { noMipmap = false; }
  111299. if (generateHarmonics === void 0) { generateHarmonics = true; }
  111300. if (gammaSpace === void 0) { gammaSpace = false; }
  111301. if (reserved === void 0) { reserved = false; }
  111302. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  111303. this._tasks.push(task);
  111304. return task;
  111305. };
  111306. /**
  111307. * Remove a task from the assets manager.
  111308. * @param task the task to remove
  111309. */
  111310. AssetsManager.prototype.removeTask = function (task) {
  111311. var index = this._tasks.indexOf(task);
  111312. if (index > -1) {
  111313. this._tasks.splice(index, 1);
  111314. }
  111315. };
  111316. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  111317. this._waitingTasksCount--;
  111318. try {
  111319. if (this.onProgress) {
  111320. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  111321. }
  111322. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  111323. }
  111324. catch (e) {
  111325. BABYLON.Tools.Error("Error running progress callbacks.");
  111326. console.log(e);
  111327. }
  111328. if (this._waitingTasksCount === 0) {
  111329. try {
  111330. if (this.onFinish) {
  111331. this.onFinish(this._tasks);
  111332. }
  111333. // Let's remove successfull tasks
  111334. var currentTasks = this._tasks.slice();
  111335. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  111336. var task = currentTasks_1[_i];
  111337. if (task.taskState === AssetTaskState.DONE) {
  111338. var index = this._tasks.indexOf(task);
  111339. if (index > -1) {
  111340. this._tasks.splice(index, 1);
  111341. }
  111342. }
  111343. }
  111344. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111345. }
  111346. catch (e) {
  111347. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  111348. console.log(e);
  111349. }
  111350. this._isLoading = false;
  111351. this._scene.getEngine().hideLoadingUI();
  111352. }
  111353. };
  111354. AssetsManager.prototype._runTask = function (task) {
  111355. var _this = this;
  111356. var done = function () {
  111357. try {
  111358. if (_this.onTaskSuccess) {
  111359. _this.onTaskSuccess(task);
  111360. }
  111361. _this.onTaskSuccessObservable.notifyObservers(task);
  111362. _this._decreaseWaitingTasksCount(task);
  111363. }
  111364. catch (e) {
  111365. error("Error executing task success callbacks", e);
  111366. }
  111367. };
  111368. var error = function (message, exception) {
  111369. task._setErrorObject(message, exception);
  111370. if (_this.onTaskError) {
  111371. _this.onTaskError(task);
  111372. }
  111373. _this.onTaskErrorObservable.notifyObservers(task);
  111374. _this._decreaseWaitingTasksCount(task);
  111375. };
  111376. task.run(this._scene, done, error);
  111377. };
  111378. /**
  111379. * Reset the AssetsManager and remove all tasks
  111380. * @return the current instance of the AssetsManager
  111381. */
  111382. AssetsManager.prototype.reset = function () {
  111383. this._isLoading = false;
  111384. this._tasks = new Array();
  111385. return this;
  111386. };
  111387. /**
  111388. * Start the loading process
  111389. * @return the current instance of the AssetsManager
  111390. */
  111391. AssetsManager.prototype.load = function () {
  111392. if (this._isLoading) {
  111393. return this;
  111394. }
  111395. this._isLoading = true;
  111396. this._waitingTasksCount = this._tasks.length;
  111397. this._totalTasksCount = this._tasks.length;
  111398. if (this._waitingTasksCount === 0) {
  111399. this._isLoading = false;
  111400. if (this.onFinish) {
  111401. this.onFinish(this._tasks);
  111402. }
  111403. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111404. return this;
  111405. }
  111406. if (this.useDefaultLoadingScreen) {
  111407. this._scene.getEngine().displayLoadingUI();
  111408. }
  111409. for (var index = 0; index < this._tasks.length; index++) {
  111410. var task = this._tasks[index];
  111411. if (task.taskState === AssetTaskState.INIT) {
  111412. this._runTask(task);
  111413. }
  111414. }
  111415. return this;
  111416. };
  111417. return AssetsManager;
  111418. }());
  111419. BABYLON.AssetsManager = AssetsManager;
  111420. })(BABYLON || (BABYLON = {}));
  111421. //# sourceMappingURL=babylon.assetsManager.js.map
  111422. var BABYLON;
  111423. (function (BABYLON) {
  111424. var serializedGeometries = [];
  111425. var serializeGeometry = function (geometry, serializationGeometries) {
  111426. if (serializedGeometries[geometry.id]) {
  111427. return;
  111428. }
  111429. if (geometry.doNotSerialize) {
  111430. return;
  111431. }
  111432. if (geometry instanceof BABYLON.BoxGeometry) {
  111433. serializationGeometries.boxes.push(geometry.serialize());
  111434. }
  111435. else if (geometry instanceof BABYLON.SphereGeometry) {
  111436. serializationGeometries.spheres.push(geometry.serialize());
  111437. }
  111438. else if (geometry instanceof BABYLON.CylinderGeometry) {
  111439. serializationGeometries.cylinders.push(geometry.serialize());
  111440. }
  111441. else if (geometry instanceof BABYLON.TorusGeometry) {
  111442. serializationGeometries.toruses.push(geometry.serialize());
  111443. }
  111444. else if (geometry instanceof BABYLON.GroundGeometry) {
  111445. serializationGeometries.grounds.push(geometry.serialize());
  111446. }
  111447. else if (geometry instanceof BABYLON.Plane) {
  111448. serializationGeometries.planes.push(geometry.serialize());
  111449. }
  111450. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  111451. serializationGeometries.torusKnots.push(geometry.serialize());
  111452. }
  111453. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  111454. throw new Error("Unknown primitive type");
  111455. }
  111456. else {
  111457. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  111458. }
  111459. serializedGeometries[geometry.id] = true;
  111460. };
  111461. var serializeMesh = function (mesh, serializationScene) {
  111462. var serializationObject = {};
  111463. // Geometry
  111464. var geometry = mesh._geometry;
  111465. if (geometry) {
  111466. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  111467. // 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
  111468. serializeGeometry(geometry, serializationScene.geometries);
  111469. }
  111470. }
  111471. // Custom
  111472. if (mesh.serialize) {
  111473. mesh.serialize(serializationObject);
  111474. }
  111475. return serializationObject;
  111476. };
  111477. var finalizeSingleMesh = function (mesh, serializationObject) {
  111478. //only works if the mesh is already loaded
  111479. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111480. //serialize material
  111481. if (mesh.material) {
  111482. if (mesh.material instanceof BABYLON.MultiMaterial) {
  111483. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  111484. serializationObject.materials = serializationObject.materials || [];
  111485. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111486. serializationObject.multiMaterials.push(mesh.material.serialize());
  111487. var _loop_1 = function (submaterial) {
  111488. if (submaterial) {
  111489. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  111490. serializationObject.materials.push(submaterial.serialize());
  111491. }
  111492. }
  111493. };
  111494. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  111495. var submaterial = _a[_i];
  111496. _loop_1(submaterial);
  111497. }
  111498. }
  111499. }
  111500. else {
  111501. serializationObject.materials = serializationObject.materials || [];
  111502. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111503. serializationObject.materials.push(mesh.material.serialize());
  111504. }
  111505. }
  111506. }
  111507. //serialize geometry
  111508. var geometry = mesh._geometry;
  111509. if (geometry) {
  111510. if (!serializationObject.geometries) {
  111511. serializationObject.geometries = {};
  111512. serializationObject.geometries.boxes = [];
  111513. serializationObject.geometries.spheres = [];
  111514. serializationObject.geometries.cylinders = [];
  111515. serializationObject.geometries.toruses = [];
  111516. serializationObject.geometries.grounds = [];
  111517. serializationObject.geometries.planes = [];
  111518. serializationObject.geometries.torusKnots = [];
  111519. serializationObject.geometries.vertexData = [];
  111520. }
  111521. serializeGeometry(geometry, serializationObject.geometries);
  111522. }
  111523. // Skeletons
  111524. if (mesh.skeleton) {
  111525. serializationObject.skeletons = serializationObject.skeletons || [];
  111526. serializationObject.skeletons.push(mesh.skeleton.serialize());
  111527. }
  111528. //serialize the actual mesh
  111529. serializationObject.meshes = serializationObject.meshes || [];
  111530. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111531. }
  111532. };
  111533. /**
  111534. * Class used to serialize a scene into a string
  111535. */
  111536. var SceneSerializer = /** @class */ (function () {
  111537. function SceneSerializer() {
  111538. }
  111539. /**
  111540. * Clear cache used by a previous serialization
  111541. */
  111542. SceneSerializer.ClearCache = function () {
  111543. serializedGeometries = [];
  111544. };
  111545. /**
  111546. * Serialize a scene into a JSON compatible object
  111547. * @param scene defines the scene to serialize
  111548. * @returns a JSON compatible object
  111549. */
  111550. SceneSerializer.Serialize = function (scene) {
  111551. var serializationObject = {};
  111552. SceneSerializer.ClearCache();
  111553. // Scene
  111554. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  111555. serializationObject.autoClear = scene.autoClear;
  111556. serializationObject.clearColor = scene.clearColor.asArray();
  111557. serializationObject.ambientColor = scene.ambientColor.asArray();
  111558. serializationObject.gravity = scene.gravity.asArray();
  111559. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  111560. serializationObject.workerCollisions = scene.workerCollisions;
  111561. // Fog
  111562. if (scene.fogMode && scene.fogMode !== 0) {
  111563. serializationObject.fogMode = scene.fogMode;
  111564. serializationObject.fogColor = scene.fogColor.asArray();
  111565. serializationObject.fogStart = scene.fogStart;
  111566. serializationObject.fogEnd = scene.fogEnd;
  111567. serializationObject.fogDensity = scene.fogDensity;
  111568. }
  111569. //Physics
  111570. if (scene.isPhysicsEnabled()) {
  111571. var physicEngine = scene.getPhysicsEngine();
  111572. if (physicEngine) {
  111573. serializationObject.physicsEnabled = true;
  111574. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  111575. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  111576. }
  111577. }
  111578. // Metadata
  111579. if (scene.metadata) {
  111580. serializationObject.metadata = scene.metadata;
  111581. }
  111582. // Morph targets
  111583. serializationObject.morphTargetManagers = [];
  111584. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  111585. var abstractMesh = _a[_i];
  111586. var manager = abstractMesh.morphTargetManager;
  111587. if (manager) {
  111588. serializationObject.morphTargetManagers.push(manager.serialize());
  111589. }
  111590. }
  111591. // Lights
  111592. serializationObject.lights = [];
  111593. var index;
  111594. var light;
  111595. for (index = 0; index < scene.lights.length; index++) {
  111596. light = scene.lights[index];
  111597. if (!light.doNotSerialize) {
  111598. serializationObject.lights.push(light.serialize());
  111599. }
  111600. }
  111601. // Cameras
  111602. serializationObject.cameras = [];
  111603. for (index = 0; index < scene.cameras.length; index++) {
  111604. var camera = scene.cameras[index];
  111605. if (!camera.doNotSerialize) {
  111606. serializationObject.cameras.push(camera.serialize());
  111607. }
  111608. }
  111609. if (scene.activeCamera) {
  111610. serializationObject.activeCameraID = scene.activeCamera.id;
  111611. }
  111612. // Animations
  111613. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  111614. // Materials
  111615. serializationObject.materials = [];
  111616. serializationObject.multiMaterials = [];
  111617. var material;
  111618. for (index = 0; index < scene.materials.length; index++) {
  111619. material = scene.materials[index];
  111620. if (!material.doNotSerialize) {
  111621. serializationObject.materials.push(material.serialize());
  111622. }
  111623. }
  111624. // MultiMaterials
  111625. serializationObject.multiMaterials = [];
  111626. for (index = 0; index < scene.multiMaterials.length; index++) {
  111627. var multiMaterial = scene.multiMaterials[index];
  111628. serializationObject.multiMaterials.push(multiMaterial.serialize());
  111629. }
  111630. // Environment texture
  111631. if (scene.environmentTexture) {
  111632. serializationObject.environmentTexture = scene.environmentTexture.name;
  111633. }
  111634. // Skeletons
  111635. serializationObject.skeletons = [];
  111636. for (index = 0; index < scene.skeletons.length; index++) {
  111637. var skeleton = scene.skeletons[index];
  111638. if (!skeleton.doNotSerialize) {
  111639. serializationObject.skeletons.push(skeleton.serialize());
  111640. }
  111641. }
  111642. // Transform nodes
  111643. serializationObject.transformNodes = [];
  111644. for (index = 0; index < scene.transformNodes.length; index++) {
  111645. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  111646. }
  111647. // Geometries
  111648. serializationObject.geometries = {};
  111649. serializationObject.geometries.boxes = [];
  111650. serializationObject.geometries.spheres = [];
  111651. serializationObject.geometries.cylinders = [];
  111652. serializationObject.geometries.toruses = [];
  111653. serializationObject.geometries.grounds = [];
  111654. serializationObject.geometries.planes = [];
  111655. serializationObject.geometries.torusKnots = [];
  111656. serializationObject.geometries.vertexData = [];
  111657. serializedGeometries = [];
  111658. var geometries = scene.getGeometries();
  111659. for (index = 0; index < geometries.length; index++) {
  111660. var geometry = geometries[index];
  111661. if (geometry.isReady()) {
  111662. serializeGeometry(geometry, serializationObject.geometries);
  111663. }
  111664. }
  111665. // Meshes
  111666. serializationObject.meshes = [];
  111667. for (index = 0; index < scene.meshes.length; index++) {
  111668. var abstractMesh = scene.meshes[index];
  111669. if (abstractMesh instanceof BABYLON.Mesh) {
  111670. var mesh = abstractMesh;
  111671. if (!mesh.doNotSerialize) {
  111672. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111673. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111674. }
  111675. }
  111676. }
  111677. }
  111678. // Particles Systems
  111679. serializationObject.particleSystems = [];
  111680. for (index = 0; index < scene.particleSystems.length; index++) {
  111681. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  111682. }
  111683. // Action Manager
  111684. if (scene.actionManager) {
  111685. serializationObject.actions = scene.actionManager.serialize("scene");
  111686. }
  111687. // Components
  111688. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  111689. var component = _c[_b];
  111690. component.serialize(serializationObject);
  111691. }
  111692. return serializationObject;
  111693. };
  111694. /**
  111695. * Serialize a mesh into a JSON compatible object
  111696. * @param toSerialize defines the mesh to serialize
  111697. * @param withParents defines if parents must be serialized as well
  111698. * @param withChildren defines if children must be serialized as well
  111699. * @returns a JSON compatible object
  111700. */
  111701. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  111702. if (withParents === void 0) { withParents = false; }
  111703. if (withChildren === void 0) { withChildren = false; }
  111704. var serializationObject = {};
  111705. SceneSerializer.ClearCache();
  111706. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  111707. if (withParents || withChildren) {
  111708. //deliberate for loop! not for each, appended should be processed as well.
  111709. for (var i = 0; i < toSerialize.length; ++i) {
  111710. if (withChildren) {
  111711. toSerialize[i].getDescendants().forEach(function (node) {
  111712. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  111713. toSerialize.push(node);
  111714. }
  111715. });
  111716. }
  111717. //make sure the array doesn't contain the object already
  111718. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  111719. toSerialize.push(toSerialize[i].parent);
  111720. }
  111721. }
  111722. }
  111723. toSerialize.forEach(function (mesh) {
  111724. finalizeSingleMesh(mesh, serializationObject);
  111725. });
  111726. return serializationObject;
  111727. };
  111728. return SceneSerializer;
  111729. }());
  111730. BABYLON.SceneSerializer = SceneSerializer;
  111731. })(BABYLON || (BABYLON = {}));
  111732. //# sourceMappingURL=babylon.sceneSerializer.js.map
  111733. var BABYLON;
  111734. (function (BABYLON) {
  111735. /**
  111736. * Class used to generate realtime reflection / refraction cube textures
  111737. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  111738. */
  111739. var ReflectionProbe = /** @class */ (function () {
  111740. /**
  111741. * Creates a new reflection probe
  111742. * @param name defines the name of the probe
  111743. * @param size defines the texture resolution (for each face)
  111744. * @param scene defines the hosting scene
  111745. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  111746. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  111747. */
  111748. function ReflectionProbe(
  111749. /** defines the name of the probe */
  111750. name, size, scene, generateMipMaps, useFloat) {
  111751. if (generateMipMaps === void 0) { generateMipMaps = true; }
  111752. if (useFloat === void 0) { useFloat = false; }
  111753. var _this = this;
  111754. this.name = name;
  111755. this._viewMatrix = BABYLON.Matrix.Identity();
  111756. this._target = BABYLON.Vector3.Zero();
  111757. this._add = BABYLON.Vector3.Zero();
  111758. this._invertYAxis = false;
  111759. /** Gets or sets probe position (center of the cube map) */
  111760. this.position = BABYLON.Vector3.Zero();
  111761. this._scene = scene;
  111762. // Create the scene field if not exist.
  111763. if (!this._scene.reflectionProbes) {
  111764. this._scene.reflectionProbes = new Array();
  111765. }
  111766. this._scene.reflectionProbes.push(this);
  111767. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  111768. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  111769. switch (faceIndex) {
  111770. case 0:
  111771. _this._add.copyFromFloats(1, 0, 0);
  111772. break;
  111773. case 1:
  111774. _this._add.copyFromFloats(-1, 0, 0);
  111775. break;
  111776. case 2:
  111777. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  111778. break;
  111779. case 3:
  111780. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  111781. break;
  111782. case 4:
  111783. _this._add.copyFromFloats(0, 0, 1);
  111784. break;
  111785. case 5:
  111786. _this._add.copyFromFloats(0, 0, -1);
  111787. break;
  111788. }
  111789. if (_this._attachedMesh) {
  111790. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  111791. }
  111792. _this.position.addToRef(_this._add, _this._target);
  111793. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  111794. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  111795. scene._forcedViewPosition = _this.position;
  111796. });
  111797. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  111798. scene._forcedViewPosition = null;
  111799. scene.updateTransformMatrix(true);
  111800. });
  111801. if (scene.activeCamera) {
  111802. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  111803. }
  111804. }
  111805. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  111806. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  111807. get: function () {
  111808. return this._renderTargetTexture.samples;
  111809. },
  111810. set: function (value) {
  111811. this._renderTargetTexture.samples = value;
  111812. },
  111813. enumerable: true,
  111814. configurable: true
  111815. });
  111816. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  111817. /** Gets or sets the refresh rate to use (on every frame by default) */
  111818. get: function () {
  111819. return this._renderTargetTexture.refreshRate;
  111820. },
  111821. set: function (value) {
  111822. this._renderTargetTexture.refreshRate = value;
  111823. },
  111824. enumerable: true,
  111825. configurable: true
  111826. });
  111827. /**
  111828. * Gets the hosting scene
  111829. * @returns a Scene
  111830. */
  111831. ReflectionProbe.prototype.getScene = function () {
  111832. return this._scene;
  111833. };
  111834. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  111835. /** Gets the internal CubeTexture used to render to */
  111836. get: function () {
  111837. return this._renderTargetTexture;
  111838. },
  111839. enumerable: true,
  111840. configurable: true
  111841. });
  111842. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  111843. /** Gets the list of meshes to render */
  111844. get: function () {
  111845. return this._renderTargetTexture.renderList;
  111846. },
  111847. enumerable: true,
  111848. configurable: true
  111849. });
  111850. /**
  111851. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  111852. * @param mesh defines the mesh to attach to
  111853. */
  111854. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  111855. this._attachedMesh = mesh;
  111856. };
  111857. /**
  111858. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  111859. * @param renderingGroupId The rendering group id corresponding to its index
  111860. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  111861. */
  111862. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  111863. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  111864. };
  111865. /**
  111866. * Clean all associated resources
  111867. */
  111868. ReflectionProbe.prototype.dispose = function () {
  111869. var index = this._scene.reflectionProbes.indexOf(this);
  111870. if (index !== -1) {
  111871. // Remove from the scene if found
  111872. this._scene.reflectionProbes.splice(index, 1);
  111873. }
  111874. if (this._renderTargetTexture) {
  111875. this._renderTargetTexture.dispose();
  111876. this._renderTargetTexture = null;
  111877. }
  111878. };
  111879. return ReflectionProbe;
  111880. }());
  111881. BABYLON.ReflectionProbe = ReflectionProbe;
  111882. })(BABYLON || (BABYLON = {}));
  111883. //# sourceMappingURL=babylon.reflectionProbe.js.map
  111884. var BABYLON;
  111885. (function (BABYLON) {
  111886. /**
  111887. * Defines the layer scene component responsible to manage any layers
  111888. * in a given scene.
  111889. */
  111890. var LayerSceneComponent = /** @class */ (function () {
  111891. /**
  111892. * Creates a new instance of the component for the given scene
  111893. * @param scene Defines the scene to register the component in
  111894. */
  111895. function LayerSceneComponent(scene) {
  111896. /**
  111897. * The component name helpfull to identify the component in the list of scene components.
  111898. */
  111899. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  111900. this.scene = scene;
  111901. this._engine = scene.getEngine();
  111902. scene.layers = new Array();
  111903. }
  111904. /**
  111905. * Registers the component in a given scene
  111906. */
  111907. LayerSceneComponent.prototype.register = function () {
  111908. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  111909. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  111910. };
  111911. /**
  111912. * Rebuilds the elements related to this component in case of
  111913. * context lost for instance.
  111914. */
  111915. LayerSceneComponent.prototype.rebuild = function () {
  111916. var layers = this.scene.layers;
  111917. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  111918. var layer = layers_1[_i];
  111919. layer._rebuild();
  111920. }
  111921. };
  111922. /**
  111923. * Disposes the component and the associated ressources.
  111924. */
  111925. LayerSceneComponent.prototype.dispose = function () {
  111926. var layers = this.scene.layers;
  111927. while (layers.length) {
  111928. layers[0].dispose();
  111929. }
  111930. };
  111931. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  111932. var layers = this.scene.layers;
  111933. if (layers.length) {
  111934. this._engine.setDepthBuffer(false);
  111935. var cameraLayerMask = camera.layerMask;
  111936. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  111937. var layer = layers_2[_i];
  111938. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  111939. layer.render();
  111940. }
  111941. }
  111942. this._engine.setDepthBuffer(true);
  111943. }
  111944. };
  111945. LayerSceneComponent.prototype._drawBackground = function (camera) {
  111946. this._draw(camera, true);
  111947. };
  111948. LayerSceneComponent.prototype._drawForeground = function (camera) {
  111949. this._draw(camera, false);
  111950. };
  111951. return LayerSceneComponent;
  111952. }());
  111953. BABYLON.LayerSceneComponent = LayerSceneComponent;
  111954. })(BABYLON || (BABYLON = {}));
  111955. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  111956. var BABYLON;
  111957. (function (BABYLON) {
  111958. /**
  111959. * This represents a full screen 2d layer.
  111960. * This can be usefull to display a picture in the background of your scene for instance.
  111961. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111962. */
  111963. var Layer = /** @class */ (function () {
  111964. /**
  111965. * Instantiates a new layer.
  111966. * This represents a full screen 2d layer.
  111967. * This can be usefull to display a picture in the background of your scene for instance.
  111968. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111969. * @param name Define the name of the layer in the scene
  111970. * @param imgUrl Define the url of the texture to display in the layer
  111971. * @param scene Define the scene the layer belongs to
  111972. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  111973. * @param color Defines a color for the layer
  111974. */
  111975. function Layer(
  111976. /**
  111977. * Define the name of the layer.
  111978. */
  111979. name, imgUrl, scene, isBackground, color) {
  111980. this.name = name;
  111981. /**
  111982. * Define the scale of the layer in order to zoom in out of the texture.
  111983. */
  111984. this.scale = new BABYLON.Vector2(1, 1);
  111985. /**
  111986. * Define an offset for the layer in order to shift the texture.
  111987. */
  111988. this.offset = new BABYLON.Vector2(0, 0);
  111989. /**
  111990. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  111991. */
  111992. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  111993. /**
  111994. * Define a mask to restrict the layer to only some of the scene cameras.
  111995. */
  111996. this.layerMask = 0x0FFFFFFF;
  111997. this._vertexBuffers = {};
  111998. /**
  111999. * An event triggered when the layer is disposed.
  112000. */
  112001. this.onDisposeObservable = new BABYLON.Observable();
  112002. /**
  112003. * An event triggered before rendering the scene
  112004. */
  112005. this.onBeforeRenderObservable = new BABYLON.Observable();
  112006. /**
  112007. * An event triggered after rendering the scene
  112008. */
  112009. this.onAfterRenderObservable = new BABYLON.Observable();
  112010. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  112011. this.isBackground = isBackground === undefined ? true : isBackground;
  112012. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  112013. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  112014. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  112015. if (!layerComponent) {
  112016. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  112017. this._scene._addComponent(layerComponent);
  112018. }
  112019. this._scene.layers.push(this);
  112020. var engine = this._scene.getEngine();
  112021. // VBO
  112022. var vertices = [];
  112023. vertices.push(1, 1);
  112024. vertices.push(-1, 1);
  112025. vertices.push(-1, -1);
  112026. vertices.push(1, -1);
  112027. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  112028. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  112029. this._createIndexBuffer();
  112030. // Effects
  112031. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  112032. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  112033. }
  112034. Object.defineProperty(Layer.prototype, "onDispose", {
  112035. /**
  112036. * Back compatibility with callback before the onDisposeObservable existed.
  112037. * The set callback will be triggered when the layer has been disposed.
  112038. */
  112039. set: function (callback) {
  112040. if (this._onDisposeObserver) {
  112041. this.onDisposeObservable.remove(this._onDisposeObserver);
  112042. }
  112043. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  112044. },
  112045. enumerable: true,
  112046. configurable: true
  112047. });
  112048. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  112049. /**
  112050. * Back compatibility with callback before the onBeforeRenderObservable existed.
  112051. * The set callback will be triggered just before rendering the layer.
  112052. */
  112053. set: function (callback) {
  112054. if (this._onBeforeRenderObserver) {
  112055. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  112056. }
  112057. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  112058. },
  112059. enumerable: true,
  112060. configurable: true
  112061. });
  112062. Object.defineProperty(Layer.prototype, "onAfterRender", {
  112063. /**
  112064. * Back compatibility with callback before the onAfterRenderObservable existed.
  112065. * The set callback will be triggered just after rendering the layer.
  112066. */
  112067. set: function (callback) {
  112068. if (this._onAfterRenderObserver) {
  112069. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  112070. }
  112071. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  112072. },
  112073. enumerable: true,
  112074. configurable: true
  112075. });
  112076. Layer.prototype._createIndexBuffer = function () {
  112077. var engine = this._scene.getEngine();
  112078. // Indices
  112079. var indices = [];
  112080. indices.push(0);
  112081. indices.push(1);
  112082. indices.push(2);
  112083. indices.push(0);
  112084. indices.push(2);
  112085. indices.push(3);
  112086. this._indexBuffer = engine.createIndexBuffer(indices);
  112087. };
  112088. /** @hidden */
  112089. Layer.prototype._rebuild = function () {
  112090. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  112091. if (vb) {
  112092. vb._rebuild();
  112093. }
  112094. this._createIndexBuffer();
  112095. };
  112096. /**
  112097. * Renders the layer in the scene.
  112098. */
  112099. Layer.prototype.render = function () {
  112100. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  112101. // Check
  112102. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  112103. return;
  112104. }
  112105. var engine = this._scene.getEngine();
  112106. this.onBeforeRenderObservable.notifyObservers(this);
  112107. // Render
  112108. engine.enableEffect(currentEffect);
  112109. engine.setState(false);
  112110. // Texture
  112111. currentEffect.setTexture("textureSampler", this.texture);
  112112. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  112113. // Color
  112114. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  112115. // Scale / offset
  112116. currentEffect.setVector2("offset", this.offset);
  112117. currentEffect.setVector2("scale", this.scale);
  112118. // VBOs
  112119. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  112120. // Draw order
  112121. if (!this.alphaTest) {
  112122. engine.setAlphaMode(this.alphaBlendingMode);
  112123. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112124. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  112125. }
  112126. else {
  112127. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112128. }
  112129. this.onAfterRenderObservable.notifyObservers(this);
  112130. };
  112131. /**
  112132. * Disposes and releases the associated ressources.
  112133. */
  112134. Layer.prototype.dispose = function () {
  112135. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  112136. if (vertexBuffer) {
  112137. vertexBuffer.dispose();
  112138. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  112139. }
  112140. if (this._indexBuffer) {
  112141. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  112142. this._indexBuffer = null;
  112143. }
  112144. if (this.texture) {
  112145. this.texture.dispose();
  112146. this.texture = null;
  112147. }
  112148. // Remove from scene
  112149. var index = this._scene.layers.indexOf(this);
  112150. this._scene.layers.splice(index, 1);
  112151. // Callback
  112152. this.onDisposeObservable.notifyObservers(this);
  112153. this.onDisposeObservable.clear();
  112154. this.onAfterRenderObservable.clear();
  112155. this.onBeforeRenderObservable.clear();
  112156. };
  112157. return Layer;
  112158. }());
  112159. BABYLON.Layer = Layer;
  112160. })(BABYLON || (BABYLON = {}));
  112161. //# sourceMappingURL=babylon.layer.js.map
  112162. var BABYLON;
  112163. (function (BABYLON) {
  112164. /**
  112165. * Class used to host texture specific utilities
  112166. */
  112167. var TextureTools = /** @class */ (function () {
  112168. function TextureTools() {
  112169. }
  112170. /**
  112171. * Uses the GPU to create a copy texture rescaled at a given size
  112172. * @param texture Texture to copy from
  112173. * @param width defines the desired width
  112174. * @param height defines the desired height
  112175. * @param useBilinearMode defines if bilinear mode has to be used
  112176. * @return the generated texture
  112177. */
  112178. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  112179. if (useBilinearMode === void 0) { useBilinearMode = true; }
  112180. var scene = texture.getScene();
  112181. var engine = scene.getEngine();
  112182. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  112183. rtt.wrapU = texture.wrapU;
  112184. rtt.wrapV = texture.wrapV;
  112185. rtt.uOffset = texture.uOffset;
  112186. rtt.vOffset = texture.vOffset;
  112187. rtt.uScale = texture.uScale;
  112188. rtt.vScale = texture.vScale;
  112189. rtt.uAng = texture.uAng;
  112190. rtt.vAng = texture.vAng;
  112191. rtt.wAng = texture.wAng;
  112192. rtt.coordinatesIndex = texture.coordinatesIndex;
  112193. rtt.level = texture.level;
  112194. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  112195. rtt._texture.isReady = false;
  112196. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112197. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112198. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  112199. passPostProcess.getEffect().executeWhenCompiled(function () {
  112200. passPostProcess.onApply = function (effect) {
  112201. effect.setTexture("textureSampler", texture);
  112202. };
  112203. var internalTexture = rtt.getInternalTexture();
  112204. if (internalTexture) {
  112205. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  112206. engine.unBindFramebuffer(internalTexture);
  112207. rtt.disposeFramebufferObjects();
  112208. passPostProcess.dispose();
  112209. internalTexture.isReady = true;
  112210. }
  112211. });
  112212. return rtt;
  112213. };
  112214. /**
  112215. * Gets an environment BRDF texture for a given scene
  112216. * @param scene defines the hosting scene
  112217. * @returns the environment BRDF texture
  112218. */
  112219. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  112220. if (!scene._environmentBRDFTexture) {
  112221. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  112222. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112223. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112224. scene._environmentBRDFTexture = texture;
  112225. }
  112226. return scene._environmentBRDFTexture;
  112227. };
  112228. 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=";
  112229. return TextureTools;
  112230. }());
  112231. BABYLON.TextureTools = TextureTools;
  112232. })(BABYLON || (BABYLON = {}));
  112233. //# sourceMappingURL=babylon.textureTools.js.map
  112234. var BABYLON;
  112235. (function (BABYLON) {
  112236. /**
  112237. * 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.
  112238. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  112239. */
  112240. var FramingBehavior = /** @class */ (function () {
  112241. function FramingBehavior() {
  112242. this._mode = FramingBehavior.FitFrustumSidesMode;
  112243. this._radiusScale = 1.0;
  112244. this._positionScale = 0.5;
  112245. this._defaultElevation = 0.3;
  112246. this._elevationReturnTime = 1500;
  112247. this._elevationReturnWaitTime = 1000;
  112248. this._zoomStopsAnimation = false;
  112249. this._framingTime = 1500;
  112250. /**
  112251. * Define if the behavior should automatically change the configured
  112252. * camera limits and sensibilities.
  112253. */
  112254. this.autoCorrectCameraLimitsAndSensibility = true;
  112255. this._isPointerDown = false;
  112256. this._lastInteractionTime = -Infinity;
  112257. // Framing control
  112258. this._animatables = new Array();
  112259. this._betaIsAnimating = false;
  112260. }
  112261. Object.defineProperty(FramingBehavior.prototype, "name", {
  112262. /**
  112263. * Gets the name of the behavior.
  112264. */
  112265. get: function () {
  112266. return "Framing";
  112267. },
  112268. enumerable: true,
  112269. configurable: true
  112270. });
  112271. Object.defineProperty(FramingBehavior.prototype, "mode", {
  112272. /**
  112273. * Gets current mode used by the behavior.
  112274. */
  112275. get: function () {
  112276. return this._mode;
  112277. },
  112278. /**
  112279. * Sets the current mode used by the behavior
  112280. */
  112281. set: function (mode) {
  112282. this._mode = mode;
  112283. },
  112284. enumerable: true,
  112285. configurable: true
  112286. });
  112287. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  112288. /**
  112289. * Gets the scale applied to the radius
  112290. */
  112291. get: function () {
  112292. return this._radiusScale;
  112293. },
  112294. /**
  112295. * Sets the scale applied to the radius (1 by default)
  112296. */
  112297. set: function (radius) {
  112298. this._radiusScale = radius;
  112299. },
  112300. enumerable: true,
  112301. configurable: true
  112302. });
  112303. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  112304. /**
  112305. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112306. */
  112307. get: function () {
  112308. return this._positionScale;
  112309. },
  112310. /**
  112311. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112312. */
  112313. set: function (scale) {
  112314. this._positionScale = scale;
  112315. },
  112316. enumerable: true,
  112317. configurable: true
  112318. });
  112319. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  112320. /**
  112321. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112322. * behaviour is triggered, in radians.
  112323. */
  112324. get: function () {
  112325. return this._defaultElevation;
  112326. },
  112327. /**
  112328. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112329. * behaviour is triggered, in radians.
  112330. */
  112331. set: function (elevation) {
  112332. this._defaultElevation = elevation;
  112333. },
  112334. enumerable: true,
  112335. configurable: true
  112336. });
  112337. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  112338. /**
  112339. * Gets the time (in milliseconds) taken to return to the default beta position.
  112340. * Negative value indicates camera should not return to default.
  112341. */
  112342. get: function () {
  112343. return this._elevationReturnTime;
  112344. },
  112345. /**
  112346. * Sets the time (in milliseconds) taken to return to the default beta position.
  112347. * Negative value indicates camera should not return to default.
  112348. */
  112349. set: function (speed) {
  112350. this._elevationReturnTime = speed;
  112351. },
  112352. enumerable: true,
  112353. configurable: true
  112354. });
  112355. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  112356. /**
  112357. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112358. */
  112359. get: function () {
  112360. return this._elevationReturnWaitTime;
  112361. },
  112362. /**
  112363. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112364. */
  112365. set: function (time) {
  112366. this._elevationReturnWaitTime = time;
  112367. },
  112368. enumerable: true,
  112369. configurable: true
  112370. });
  112371. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  112372. /**
  112373. * Gets the flag that indicates if user zooming should stop animation.
  112374. */
  112375. get: function () {
  112376. return this._zoomStopsAnimation;
  112377. },
  112378. /**
  112379. * Sets the flag that indicates if user zooming should stop animation.
  112380. */
  112381. set: function (flag) {
  112382. this._zoomStopsAnimation = flag;
  112383. },
  112384. enumerable: true,
  112385. configurable: true
  112386. });
  112387. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  112388. /**
  112389. * Gets the transition time when framing the mesh, in milliseconds
  112390. */
  112391. get: function () {
  112392. return this._framingTime;
  112393. },
  112394. /**
  112395. * Sets the transition time when framing the mesh, in milliseconds
  112396. */
  112397. set: function (time) {
  112398. this._framingTime = time;
  112399. },
  112400. enumerable: true,
  112401. configurable: true
  112402. });
  112403. /**
  112404. * Initializes the behavior.
  112405. */
  112406. FramingBehavior.prototype.init = function () {
  112407. // Do notihng
  112408. };
  112409. /**
  112410. * Attaches the behavior to its arc rotate camera.
  112411. * @param camera Defines the camera to attach the behavior to
  112412. */
  112413. FramingBehavior.prototype.attach = function (camera) {
  112414. var _this = this;
  112415. this._attachedCamera = camera;
  112416. var scene = this._attachedCamera.getScene();
  112417. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  112418. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  112419. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  112420. _this._isPointerDown = true;
  112421. return;
  112422. }
  112423. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  112424. _this._isPointerDown = false;
  112425. }
  112426. });
  112427. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112428. if (mesh) {
  112429. _this.zoomOnMesh(mesh);
  112430. }
  112431. });
  112432. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112433. // Stop the animation if there is user interaction and the animation should stop for this interaction
  112434. _this._applyUserInteraction();
  112435. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  112436. // back to the default position after a given timeout
  112437. _this._maintainCameraAboveGround();
  112438. });
  112439. };
  112440. /**
  112441. * Detaches the behavior from its current arc rotate camera.
  112442. */
  112443. FramingBehavior.prototype.detach = function () {
  112444. if (!this._attachedCamera) {
  112445. return;
  112446. }
  112447. var scene = this._attachedCamera.getScene();
  112448. if (this._onPrePointerObservableObserver) {
  112449. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  112450. }
  112451. if (this._onAfterCheckInputsObserver) {
  112452. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112453. }
  112454. if (this._onMeshTargetChangedObserver) {
  112455. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112456. }
  112457. this._attachedCamera = null;
  112458. };
  112459. /**
  112460. * Targets the given mesh and updates zoom level accordingly.
  112461. * @param mesh The mesh to target.
  112462. * @param radius Optional. If a cached radius position already exists, overrides default.
  112463. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112464. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112465. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112466. */
  112467. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112468. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112469. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112470. mesh.computeWorldMatrix(true);
  112471. var boundingBox = mesh.getBoundingInfo().boundingBox;
  112472. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  112473. };
  112474. /**
  112475. * Targets the given mesh with its children and updates zoom level accordingly.
  112476. * @param mesh The mesh to target.
  112477. * @param radius Optional. If a cached radius position already exists, overrides default.
  112478. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112479. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112480. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112481. */
  112482. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112483. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112484. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112485. mesh.computeWorldMatrix(true);
  112486. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  112487. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  112488. };
  112489. /**
  112490. * Targets the given meshes with their children and updates zoom level accordingly.
  112491. * @param meshes The mesh to target.
  112492. * @param radius Optional. If a cached radius position already exists, overrides default.
  112493. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112494. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112495. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112496. */
  112497. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  112498. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112499. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112500. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  112501. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  112502. for (var i = 0; i < meshes.length; i++) {
  112503. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  112504. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  112505. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  112506. }
  112507. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  112508. };
  112509. /**
  112510. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  112511. * @param minimumWorld Determines the smaller position of the bounding box extend
  112512. * @param maximumWorld Determines the bigger position of the bounding box extend
  112513. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112514. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112515. */
  112516. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  112517. var _this = this;
  112518. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112519. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112520. var zoomTarget;
  112521. if (!this._attachedCamera) {
  112522. return;
  112523. }
  112524. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  112525. var bottom = minimumWorld.y;
  112526. var top = maximumWorld.y;
  112527. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  112528. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  112529. if (focusOnOriginXZ) {
  112530. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  112531. }
  112532. else {
  112533. var centerWorld = minimumWorld.add(radiusWorld);
  112534. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  112535. }
  112536. if (!this._vectorTransition) {
  112537. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  112538. }
  112539. this._betaIsAnimating = true;
  112540. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  112541. if (animatable) {
  112542. this._animatables.push(animatable);
  112543. }
  112544. // sets the radius and lower radius bounds
  112545. // Small delta ensures camera is not always at lower zoom limit.
  112546. var radius = 0;
  112547. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  112548. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112549. if (this.autoCorrectCameraLimitsAndSensibility) {
  112550. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  112551. }
  112552. radius = position;
  112553. }
  112554. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112555. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112556. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  112557. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  112558. }
  112559. }
  112560. // Set sensibilities
  112561. if (this.autoCorrectCameraLimitsAndSensibility) {
  112562. var extend = maximumWorld.subtract(minimumWorld).length();
  112563. this._attachedCamera.panningSensibility = 5000 / extend;
  112564. this._attachedCamera.wheelPrecision = 100 / radius;
  112565. }
  112566. // transition to new radius
  112567. if (!this._radiusTransition) {
  112568. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112569. }
  112570. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  112571. _this.stopAllAnimations();
  112572. if (onAnimationEnd) {
  112573. onAnimationEnd();
  112574. }
  112575. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  112576. _this._attachedCamera.storeState();
  112577. }
  112578. });
  112579. if (animatable) {
  112580. this._animatables.push(animatable);
  112581. }
  112582. };
  112583. /**
  112584. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  112585. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  112586. * frustum width.
  112587. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  112588. * to fully enclose the mesh in the viewing frustum.
  112589. */
  112590. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  112591. var size = maximumWorld.subtract(minimumWorld);
  112592. var boxVectorGlobalDiagonal = size.length();
  112593. var frustumSlope = this._getFrustumSlope();
  112594. // Formula for setting distance
  112595. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  112596. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  112597. // Horizon distance
  112598. var radius = radiusWithoutFraming * this._radiusScale;
  112599. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  112600. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  112601. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  112602. var camera = this._attachedCamera;
  112603. if (!camera) {
  112604. return 0;
  112605. }
  112606. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112607. // Don't exceed the requested limit
  112608. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  112609. }
  112610. // Don't exceed the upper radius limit
  112611. if (camera.upperRadiusLimit) {
  112612. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  112613. }
  112614. return distance;
  112615. };
  112616. /**
  112617. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  112618. * is automatically returned to its default position (expected to be above ground plane).
  112619. */
  112620. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  112621. var _this = this;
  112622. if (this._elevationReturnTime < 0) {
  112623. return;
  112624. }
  112625. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  112626. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  112627. var limitBeta = Math.PI * 0.5;
  112628. // Bring the camera back up if below the ground plane
  112629. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  112630. this._betaIsAnimating = true;
  112631. //Transition to new position
  112632. this.stopAllAnimations();
  112633. if (!this._betaTransition) {
  112634. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112635. }
  112636. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  112637. _this._clearAnimationLocks();
  112638. _this.stopAllAnimations();
  112639. });
  112640. if (animatabe) {
  112641. this._animatables.push(animatabe);
  112642. }
  112643. }
  112644. };
  112645. /**
  112646. * Returns the frustum slope based on the canvas ratio and camera FOV
  112647. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  112648. */
  112649. FramingBehavior.prototype._getFrustumSlope = function () {
  112650. // Calculate the viewport ratio
  112651. // Aspect Ratio is Height/Width.
  112652. var camera = this._attachedCamera;
  112653. if (!camera) {
  112654. return BABYLON.Vector2.Zero();
  112655. }
  112656. var engine = camera.getScene().getEngine();
  112657. var aspectRatio = engine.getAspectRatio(camera);
  112658. // Camera FOV is the vertical field of view (top-bottom) in radians.
  112659. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  112660. var frustumSlopeY = Math.tan(camera.fov / 2);
  112661. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  112662. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  112663. // along the forward vector.
  112664. var frustumSlopeX = frustumSlopeY * aspectRatio;
  112665. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  112666. };
  112667. /**
  112668. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  112669. */
  112670. FramingBehavior.prototype._clearAnimationLocks = function () {
  112671. this._betaIsAnimating = false;
  112672. };
  112673. /**
  112674. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  112675. */
  112676. FramingBehavior.prototype._applyUserInteraction = function () {
  112677. if (this.isUserIsMoving) {
  112678. this._lastInteractionTime = BABYLON.Tools.Now;
  112679. this.stopAllAnimations();
  112680. this._clearAnimationLocks();
  112681. }
  112682. };
  112683. /**
  112684. * Stops and removes all animations that have been applied to the camera
  112685. */
  112686. FramingBehavior.prototype.stopAllAnimations = function () {
  112687. if (this._attachedCamera) {
  112688. this._attachedCamera.animations = [];
  112689. }
  112690. while (this._animatables.length) {
  112691. if (this._animatables[0]) {
  112692. this._animatables[0].onAnimationEnd = null;
  112693. this._animatables[0].stop();
  112694. }
  112695. this._animatables.shift();
  112696. }
  112697. };
  112698. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  112699. /**
  112700. * Gets a value indicating if the user is moving the camera
  112701. */
  112702. get: function () {
  112703. if (!this._attachedCamera) {
  112704. return false;
  112705. }
  112706. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  112707. this._attachedCamera.inertialBetaOffset !== 0 ||
  112708. this._attachedCamera.inertialRadiusOffset !== 0 ||
  112709. this._attachedCamera.inertialPanningX !== 0 ||
  112710. this._attachedCamera.inertialPanningY !== 0 ||
  112711. this._isPointerDown;
  112712. },
  112713. enumerable: true,
  112714. configurable: true
  112715. });
  112716. /**
  112717. * The easing function used by animations
  112718. */
  112719. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  112720. /**
  112721. * The easing mode used by animations
  112722. */
  112723. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  112724. // Statics
  112725. /**
  112726. * The camera can move all the way towards the mesh.
  112727. */
  112728. FramingBehavior.IgnoreBoundsSizeMode = 0;
  112729. /**
  112730. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  112731. */
  112732. FramingBehavior.FitFrustumSidesMode = 1;
  112733. return FramingBehavior;
  112734. }());
  112735. BABYLON.FramingBehavior = FramingBehavior;
  112736. })(BABYLON || (BABYLON = {}));
  112737. //# sourceMappingURL=babylon.framingBehavior.js.map
  112738. var BABYLON;
  112739. (function (BABYLON) {
  112740. /**
  112741. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  112742. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  112743. */
  112744. var BouncingBehavior = /** @class */ (function () {
  112745. function BouncingBehavior() {
  112746. /**
  112747. * The duration of the animation, in milliseconds
  112748. */
  112749. this.transitionDuration = 450;
  112750. /**
  112751. * Length of the distance animated by the transition when lower radius is reached
  112752. */
  112753. this.lowerRadiusTransitionRange = 2;
  112754. /**
  112755. * Length of the distance animated by the transition when upper radius is reached
  112756. */
  112757. this.upperRadiusTransitionRange = -2;
  112758. this._autoTransitionRange = false;
  112759. // Animations
  112760. this._radiusIsAnimating = false;
  112761. this._radiusBounceTransition = null;
  112762. this._animatables = new Array();
  112763. }
  112764. Object.defineProperty(BouncingBehavior.prototype, "name", {
  112765. /**
  112766. * Gets the name of the behavior.
  112767. */
  112768. get: function () {
  112769. return "Bouncing";
  112770. },
  112771. enumerable: true,
  112772. configurable: true
  112773. });
  112774. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  112775. /**
  112776. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112777. */
  112778. get: function () {
  112779. return this._autoTransitionRange;
  112780. },
  112781. /**
  112782. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112783. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  112784. */
  112785. set: function (value) {
  112786. var _this = this;
  112787. if (this._autoTransitionRange === value) {
  112788. return;
  112789. }
  112790. this._autoTransitionRange = value;
  112791. var camera = this._attachedCamera;
  112792. if (!camera) {
  112793. return;
  112794. }
  112795. if (value) {
  112796. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112797. if (!mesh) {
  112798. return;
  112799. }
  112800. mesh.computeWorldMatrix(true);
  112801. var diagonal = mesh.getBoundingInfo().diagonalLength;
  112802. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  112803. _this.upperRadiusTransitionRange = diagonal * 0.05;
  112804. });
  112805. }
  112806. else if (this._onMeshTargetChangedObserver) {
  112807. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112808. }
  112809. },
  112810. enumerable: true,
  112811. configurable: true
  112812. });
  112813. /**
  112814. * Initializes the behavior.
  112815. */
  112816. BouncingBehavior.prototype.init = function () {
  112817. // Do notihng
  112818. };
  112819. /**
  112820. * Attaches the behavior to its arc rotate camera.
  112821. * @param camera Defines the camera to attach the behavior to
  112822. */
  112823. BouncingBehavior.prototype.attach = function (camera) {
  112824. var _this = this;
  112825. this._attachedCamera = camera;
  112826. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112827. if (!_this._attachedCamera) {
  112828. return;
  112829. }
  112830. // Add the bounce animation to the lower radius limit
  112831. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  112832. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  112833. }
  112834. // Add the bounce animation to the upper radius limit
  112835. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  112836. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  112837. }
  112838. });
  112839. };
  112840. /**
  112841. * Detaches the behavior from its current arc rotate camera.
  112842. */
  112843. BouncingBehavior.prototype.detach = function () {
  112844. if (!this._attachedCamera) {
  112845. return;
  112846. }
  112847. if (this._onAfterCheckInputsObserver) {
  112848. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112849. }
  112850. if (this._onMeshTargetChangedObserver) {
  112851. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112852. }
  112853. this._attachedCamera = null;
  112854. };
  112855. /**
  112856. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  112857. * @param radiusLimit The limit to check against.
  112858. * @return Bool to indicate if at limit.
  112859. */
  112860. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  112861. if (!this._attachedCamera) {
  112862. return false;
  112863. }
  112864. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  112865. return true;
  112866. }
  112867. return false;
  112868. };
  112869. /**
  112870. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  112871. * @param radiusDelta The delta by which to animate to. Can be negative.
  112872. */
  112873. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  112874. var _this = this;
  112875. if (!this._attachedCamera) {
  112876. return;
  112877. }
  112878. if (!this._radiusBounceTransition) {
  112879. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  112880. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  112881. }
  112882. // Prevent zoom until bounce has completed
  112883. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  112884. this._attachedCamera.wheelPrecision = Infinity;
  112885. this._attachedCamera.inertialRadiusOffset = 0;
  112886. // Animate to the radius limit
  112887. this.stopAllAnimations();
  112888. this._radiusIsAnimating = true;
  112889. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  112890. if (animatable) {
  112891. this._animatables.push(animatable);
  112892. }
  112893. };
  112894. /**
  112895. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  112896. */
  112897. BouncingBehavior.prototype._clearAnimationLocks = function () {
  112898. this._radiusIsAnimating = false;
  112899. if (this._attachedCamera) {
  112900. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  112901. }
  112902. };
  112903. /**
  112904. * Stops and removes all animations that have been applied to the camera
  112905. */
  112906. BouncingBehavior.prototype.stopAllAnimations = function () {
  112907. if (this._attachedCamera) {
  112908. this._attachedCamera.animations = [];
  112909. }
  112910. while (this._animatables.length) {
  112911. this._animatables[0].onAnimationEnd = null;
  112912. this._animatables[0].stop();
  112913. this._animatables.shift();
  112914. }
  112915. };
  112916. /**
  112917. * The easing function used by animations
  112918. */
  112919. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  112920. /**
  112921. * The easing mode used by animations
  112922. */
  112923. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  112924. return BouncingBehavior;
  112925. }());
  112926. BABYLON.BouncingBehavior = BouncingBehavior;
  112927. })(BABYLON || (BABYLON = {}));
  112928. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  112929. var BABYLON;
  112930. (function (BABYLON) {
  112931. /**
  112932. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  112933. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  112934. */
  112935. var AutoRotationBehavior = /** @class */ (function () {
  112936. function AutoRotationBehavior() {
  112937. this._zoomStopsAnimation = false;
  112938. this._idleRotationSpeed = 0.05;
  112939. this._idleRotationWaitTime = 2000;
  112940. this._idleRotationSpinupTime = 2000;
  112941. this._isPointerDown = false;
  112942. this._lastFrameTime = null;
  112943. this._lastInteractionTime = -Infinity;
  112944. this._cameraRotationSpeed = 0;
  112945. this._lastFrameRadius = 0;
  112946. }
  112947. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  112948. /**
  112949. * Gets the name of the behavior.
  112950. */
  112951. get: function () {
  112952. return "AutoRotation";
  112953. },
  112954. enumerable: true,
  112955. configurable: true
  112956. });
  112957. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  112958. /**
  112959. * Gets the flag that indicates if user zooming should stop animation.
  112960. */
  112961. get: function () {
  112962. return this._zoomStopsAnimation;
  112963. },
  112964. /**
  112965. * Sets the flag that indicates if user zooming should stop animation.
  112966. */
  112967. set: function (flag) {
  112968. this._zoomStopsAnimation = flag;
  112969. },
  112970. enumerable: true,
  112971. configurable: true
  112972. });
  112973. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  112974. /**
  112975. * Gets the default speed at which the camera rotates around the model.
  112976. */
  112977. get: function () {
  112978. return this._idleRotationSpeed;
  112979. },
  112980. /**
  112981. * Sets the default speed at which the camera rotates around the model.
  112982. */
  112983. set: function (speed) {
  112984. this._idleRotationSpeed = speed;
  112985. },
  112986. enumerable: true,
  112987. configurable: true
  112988. });
  112989. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  112990. /**
  112991. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  112992. */
  112993. get: function () {
  112994. return this._idleRotationWaitTime;
  112995. },
  112996. /**
  112997. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  112998. */
  112999. set: function (time) {
  113000. this._idleRotationWaitTime = time;
  113001. },
  113002. enumerable: true,
  113003. configurable: true
  113004. });
  113005. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  113006. /**
  113007. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  113008. */
  113009. get: function () {
  113010. return this._idleRotationSpinupTime;
  113011. },
  113012. /**
  113013. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  113014. */
  113015. set: function (time) {
  113016. this._idleRotationSpinupTime = time;
  113017. },
  113018. enumerable: true,
  113019. configurable: true
  113020. });
  113021. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  113022. /**
  113023. * Gets a value indicating if the camera is currently rotating because of this behavior
  113024. */
  113025. get: function () {
  113026. return Math.abs(this._cameraRotationSpeed) > 0;
  113027. },
  113028. enumerable: true,
  113029. configurable: true
  113030. });
  113031. /**
  113032. * Initializes the behavior.
  113033. */
  113034. AutoRotationBehavior.prototype.init = function () {
  113035. // Do notihng
  113036. };
  113037. /**
  113038. * Attaches the behavior to its arc rotate camera.
  113039. * @param camera Defines the camera to attach the behavior to
  113040. */
  113041. AutoRotationBehavior.prototype.attach = function (camera) {
  113042. var _this = this;
  113043. this._attachedCamera = camera;
  113044. var scene = this._attachedCamera.getScene();
  113045. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  113046. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  113047. _this._isPointerDown = true;
  113048. return;
  113049. }
  113050. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  113051. _this._isPointerDown = false;
  113052. }
  113053. });
  113054. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  113055. var now = BABYLON.Tools.Now;
  113056. var dt = 0;
  113057. if (_this._lastFrameTime != null) {
  113058. dt = now - _this._lastFrameTime;
  113059. }
  113060. _this._lastFrameTime = now;
  113061. // Stop the animation if there is user interaction and the animation should stop for this interaction
  113062. _this._applyUserInteraction();
  113063. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  113064. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  113065. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  113066. // Step camera rotation by rotation speed
  113067. if (_this._attachedCamera) {
  113068. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  113069. }
  113070. });
  113071. };
  113072. /**
  113073. * Detaches the behavior from its current arc rotate camera.
  113074. */
  113075. AutoRotationBehavior.prototype.detach = function () {
  113076. if (!this._attachedCamera) {
  113077. return;
  113078. }
  113079. var scene = this._attachedCamera.getScene();
  113080. if (this._onPrePointerObservableObserver) {
  113081. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  113082. }
  113083. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  113084. this._attachedCamera = null;
  113085. };
  113086. /**
  113087. * Returns true if user is scrolling.
  113088. * @return true if user is scrolling.
  113089. */
  113090. AutoRotationBehavior.prototype._userIsZooming = function () {
  113091. if (!this._attachedCamera) {
  113092. return false;
  113093. }
  113094. return this._attachedCamera.inertialRadiusOffset !== 0;
  113095. };
  113096. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  113097. if (!this._attachedCamera) {
  113098. return false;
  113099. }
  113100. var zoomHasHitLimit = false;
  113101. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  113102. zoomHasHitLimit = true;
  113103. }
  113104. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  113105. this._lastFrameRadius = this._attachedCamera.radius;
  113106. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  113107. };
  113108. /**
  113109. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  113110. */
  113111. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  113112. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  113113. this._lastInteractionTime = BABYLON.Tools.Now;
  113114. }
  113115. };
  113116. // Tools
  113117. AutoRotationBehavior.prototype._userIsMoving = function () {
  113118. if (!this._attachedCamera) {
  113119. return false;
  113120. }
  113121. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  113122. this._attachedCamera.inertialBetaOffset !== 0 ||
  113123. this._attachedCamera.inertialRadiusOffset !== 0 ||
  113124. this._attachedCamera.inertialPanningX !== 0 ||
  113125. this._attachedCamera.inertialPanningY !== 0 ||
  113126. this._isPointerDown;
  113127. };
  113128. return AutoRotationBehavior;
  113129. }());
  113130. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  113131. })(BABYLON || (BABYLON = {}));
  113132. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  113133. var BABYLON;
  113134. (function (BABYLON) {
  113135. /**
  113136. * Options to create the null engine
  113137. */
  113138. var NullEngineOptions = /** @class */ (function () {
  113139. function NullEngineOptions() {
  113140. /**
  113141. * Render width (Default: 512)
  113142. */
  113143. this.renderWidth = 512;
  113144. /**
  113145. * Render height (Default: 256)
  113146. */
  113147. this.renderHeight = 256;
  113148. /**
  113149. * Texture size (Default: 512)
  113150. */
  113151. this.textureSize = 512;
  113152. /**
  113153. * If delta time between frames should be constant
  113154. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113155. */
  113156. this.deterministicLockstep = false;
  113157. /**
  113158. * Maximum about of steps between frames (Default: 4)
  113159. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113160. */
  113161. this.lockstepMaxSteps = 4;
  113162. }
  113163. return NullEngineOptions;
  113164. }());
  113165. BABYLON.NullEngineOptions = NullEngineOptions;
  113166. /**
  113167. * The null engine class provides support for headless version of babylon.js.
  113168. * This can be used in server side scenario or for testing purposes
  113169. */
  113170. var NullEngine = /** @class */ (function (_super) {
  113171. __extends(NullEngine, _super);
  113172. function NullEngine(options) {
  113173. if (options === void 0) { options = new NullEngineOptions(); }
  113174. var _this = _super.call(this, null) || this;
  113175. if (options.deterministicLockstep === undefined) {
  113176. options.deterministicLockstep = false;
  113177. }
  113178. if (options.lockstepMaxSteps === undefined) {
  113179. options.lockstepMaxSteps = 4;
  113180. }
  113181. _this._options = options;
  113182. // Init caps
  113183. // We consider we are on a webgl1 capable device
  113184. _this._caps = new BABYLON.EngineCapabilities();
  113185. _this._caps.maxTexturesImageUnits = 16;
  113186. _this._caps.maxVertexTextureImageUnits = 16;
  113187. _this._caps.maxTextureSize = 512;
  113188. _this._caps.maxCubemapTextureSize = 512;
  113189. _this._caps.maxRenderTextureSize = 512;
  113190. _this._caps.maxVertexAttribs = 16;
  113191. _this._caps.maxVaryingVectors = 16;
  113192. _this._caps.maxFragmentUniformVectors = 16;
  113193. _this._caps.maxVertexUniformVectors = 16;
  113194. // Extensions
  113195. _this._caps.standardDerivatives = false;
  113196. _this._caps.astc = null;
  113197. _this._caps.s3tc = null;
  113198. _this._caps.pvrtc = null;
  113199. _this._caps.etc1 = null;
  113200. _this._caps.etc2 = null;
  113201. _this._caps.textureAnisotropicFilterExtension = null;
  113202. _this._caps.maxAnisotropy = 0;
  113203. _this._caps.uintIndices = false;
  113204. _this._caps.fragmentDepthSupported = false;
  113205. _this._caps.highPrecisionShaderSupported = true;
  113206. _this._caps.colorBufferFloat = false;
  113207. _this._caps.textureFloat = false;
  113208. _this._caps.textureFloatLinearFiltering = false;
  113209. _this._caps.textureFloatRender = false;
  113210. _this._caps.textureHalfFloat = false;
  113211. _this._caps.textureHalfFloatLinearFiltering = false;
  113212. _this._caps.textureHalfFloatRender = false;
  113213. _this._caps.textureLOD = false;
  113214. _this._caps.drawBuffersExtension = false;
  113215. _this._caps.depthTextureExtension = false;
  113216. _this._caps.vertexArrayObject = false;
  113217. _this._caps.instancedArrays = false;
  113218. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  113219. // Wrappers
  113220. if (typeof URL === "undefined") {
  113221. URL = {
  113222. createObjectURL: function () { },
  113223. revokeObjectURL: function () { }
  113224. };
  113225. }
  113226. if (typeof Blob === "undefined") {
  113227. Blob = function () { };
  113228. }
  113229. return _this;
  113230. }
  113231. /**
  113232. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113233. */
  113234. NullEngine.prototype.isDeterministicLockStep = function () {
  113235. return this._options.deterministicLockstep;
  113236. };
  113237. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  113238. NullEngine.prototype.getLockstepMaxSteps = function () {
  113239. return this._options.lockstepMaxSteps;
  113240. };
  113241. /**
  113242. * Sets hardware scaling, used to save performance if needed
  113243. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  113244. */
  113245. NullEngine.prototype.getHardwareScalingLevel = function () {
  113246. return 1.0;
  113247. };
  113248. NullEngine.prototype.createVertexBuffer = function (vertices) {
  113249. return {
  113250. capacity: 0,
  113251. references: 1,
  113252. is32Bits: false
  113253. };
  113254. };
  113255. NullEngine.prototype.createIndexBuffer = function (indices) {
  113256. return {
  113257. capacity: 0,
  113258. references: 1,
  113259. is32Bits: false
  113260. };
  113261. };
  113262. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  113263. if (stencil === void 0) { stencil = false; }
  113264. };
  113265. NullEngine.prototype.getRenderWidth = function (useScreen) {
  113266. if (useScreen === void 0) { useScreen = false; }
  113267. if (!useScreen && this._currentRenderTarget) {
  113268. return this._currentRenderTarget.width;
  113269. }
  113270. return this._options.renderWidth;
  113271. };
  113272. NullEngine.prototype.getRenderHeight = function (useScreen) {
  113273. if (useScreen === void 0) { useScreen = false; }
  113274. if (!useScreen && this._currentRenderTarget) {
  113275. return this._currentRenderTarget.height;
  113276. }
  113277. return this._options.renderHeight;
  113278. };
  113279. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  113280. this._cachedViewport = viewport;
  113281. };
  113282. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  113283. return {
  113284. transformFeedback: null,
  113285. __SPECTOR_rebuildProgram: null
  113286. };
  113287. };
  113288. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  113289. return [];
  113290. };
  113291. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  113292. return [];
  113293. };
  113294. NullEngine.prototype.bindSamplers = function (effect) {
  113295. this._currentEffect = null;
  113296. };
  113297. NullEngine.prototype.enableEffect = function (effect) {
  113298. this._currentEffect = effect;
  113299. if (effect.onBind) {
  113300. effect.onBind(effect);
  113301. }
  113302. if (effect._onBindObservable) {
  113303. effect._onBindObservable.notifyObservers(effect);
  113304. }
  113305. };
  113306. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  113307. if (zOffset === void 0) { zOffset = 0; }
  113308. if (reverseSide === void 0) { reverseSide = false; }
  113309. };
  113310. NullEngine.prototype.setIntArray = function (uniform, array) {
  113311. };
  113312. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  113313. };
  113314. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  113315. };
  113316. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  113317. };
  113318. NullEngine.prototype.setFloatArray = function (uniform, array) {
  113319. };
  113320. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  113321. };
  113322. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  113323. };
  113324. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  113325. };
  113326. NullEngine.prototype.setArray = function (uniform, array) {
  113327. };
  113328. NullEngine.prototype.setArray2 = function (uniform, array) {
  113329. };
  113330. NullEngine.prototype.setArray3 = function (uniform, array) {
  113331. };
  113332. NullEngine.prototype.setArray4 = function (uniform, array) {
  113333. };
  113334. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  113335. };
  113336. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  113337. };
  113338. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  113339. };
  113340. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  113341. };
  113342. NullEngine.prototype.setFloat = function (uniform, value) {
  113343. };
  113344. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  113345. };
  113346. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  113347. };
  113348. NullEngine.prototype.setBool = function (uniform, bool) {
  113349. };
  113350. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  113351. };
  113352. NullEngine.prototype.setColor3 = function (uniform, color3) {
  113353. };
  113354. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  113355. };
  113356. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  113357. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  113358. if (this._alphaMode === mode) {
  113359. return;
  113360. }
  113361. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  113362. if (!noDepthWriteChange) {
  113363. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  113364. }
  113365. this._alphaMode = mode;
  113366. };
  113367. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  113368. };
  113369. NullEngine.prototype.wipeCaches = function (bruteForce) {
  113370. if (this.preventCacheWipeBetweenFrames) {
  113371. return;
  113372. }
  113373. this.resetTextureCache();
  113374. this._currentEffect = null;
  113375. if (bruteForce) {
  113376. this._currentProgram = null;
  113377. this._stencilState.reset();
  113378. this._depthCullingState.reset();
  113379. this._alphaState.reset();
  113380. }
  113381. this._cachedVertexBuffers = null;
  113382. this._cachedIndexBuffer = null;
  113383. this._cachedEffectForVertexBuffers = null;
  113384. };
  113385. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  113386. };
  113387. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  113388. };
  113389. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  113390. };
  113391. /** @hidden */
  113392. NullEngine.prototype._createTexture = function () {
  113393. return {};
  113394. };
  113395. /** @hidden */
  113396. NullEngine.prototype._releaseTexture = function (texture) {
  113397. };
  113398. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  113399. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113400. if (onLoad === void 0) { onLoad = null; }
  113401. if (onError === void 0) { onError = null; }
  113402. if (buffer === void 0) { buffer = null; }
  113403. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  113404. var url = String(urlArg);
  113405. texture.url = url;
  113406. texture.generateMipMaps = !noMipmap;
  113407. texture.samplingMode = samplingMode;
  113408. texture.invertY = invertY;
  113409. texture.baseWidth = this._options.textureSize;
  113410. texture.baseHeight = this._options.textureSize;
  113411. texture.width = this._options.textureSize;
  113412. texture.height = this._options.textureSize;
  113413. if (format) {
  113414. texture.format = format;
  113415. }
  113416. texture.isReady = true;
  113417. if (onLoad) {
  113418. onLoad();
  113419. }
  113420. this._internalTexturesCache.push(texture);
  113421. return texture;
  113422. };
  113423. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  113424. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  113425. if (options !== undefined && typeof options === "object") {
  113426. fullOptions.generateMipMaps = options.generateMipMaps;
  113427. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  113428. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  113429. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  113430. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  113431. }
  113432. else {
  113433. fullOptions.generateMipMaps = options;
  113434. fullOptions.generateDepthBuffer = true;
  113435. fullOptions.generateStencilBuffer = false;
  113436. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  113437. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  113438. }
  113439. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  113440. var width = size.width || size;
  113441. var height = size.height || size;
  113442. texture._depthStencilBuffer = {};
  113443. texture._framebuffer = {};
  113444. texture.baseWidth = width;
  113445. texture.baseHeight = height;
  113446. texture.width = width;
  113447. texture.height = height;
  113448. texture.isReady = true;
  113449. texture.samples = 1;
  113450. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  113451. texture.samplingMode = fullOptions.samplingMode;
  113452. texture.type = fullOptions.type;
  113453. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  113454. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  113455. this._internalTexturesCache.push(texture);
  113456. return texture;
  113457. };
  113458. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  113459. texture.samplingMode = samplingMode;
  113460. };
  113461. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  113462. if (this._currentRenderTarget) {
  113463. this.unBindFramebuffer(this._currentRenderTarget);
  113464. }
  113465. this._currentRenderTarget = texture;
  113466. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  113467. if (this._cachedViewport && !forceFullscreenViewport) {
  113468. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  113469. }
  113470. };
  113471. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  113472. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  113473. this._currentRenderTarget = null;
  113474. if (onBeforeUnbind) {
  113475. if (texture._MSAAFramebuffer) {
  113476. this._currentFramebuffer = texture._framebuffer;
  113477. }
  113478. onBeforeUnbind();
  113479. }
  113480. this._currentFramebuffer = null;
  113481. };
  113482. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  113483. var vbo = {
  113484. capacity: 1,
  113485. references: 1,
  113486. is32Bits: false
  113487. };
  113488. return vbo;
  113489. };
  113490. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  113491. if (premulAlpha === void 0) { premulAlpha = false; }
  113492. };
  113493. /**
  113494. * @hidden
  113495. * Get the current error code of the webGL context
  113496. * @returns the error code
  113497. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  113498. */
  113499. NullEngine.prototype.getError = function () {
  113500. return 0;
  113501. };
  113502. /** @hidden */
  113503. NullEngine.prototype._getUnpackAlignement = function () {
  113504. return 1;
  113505. };
  113506. /** @hidden */
  113507. NullEngine.prototype._unpackFlipY = function (value) {
  113508. };
  113509. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  113510. if (offset === void 0) { offset = 0; }
  113511. };
  113512. /**
  113513. * Updates a dynamic vertex buffer.
  113514. * @param vertexBuffer the vertex buffer to update
  113515. * @param data the data used to update the vertex buffer
  113516. * @param byteOffset the byte offset of the data (optional)
  113517. * @param byteLength the byte length of the data (optional)
  113518. */
  113519. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  113520. };
  113521. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  113522. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  113523. this._boundTexturesCache[this._activeChannel] = texture;
  113524. return true;
  113525. }
  113526. return false;
  113527. };
  113528. /** @hidden */
  113529. NullEngine.prototype._bindTexture = function (channel, texture) {
  113530. if (channel < 0) {
  113531. return;
  113532. }
  113533. this._bindTextureDirectly(0, texture);
  113534. };
  113535. /** @hidden */
  113536. NullEngine.prototype._releaseBuffer = function (buffer) {
  113537. buffer.references--;
  113538. if (buffer.references === 0) {
  113539. return true;
  113540. }
  113541. return false;
  113542. };
  113543. NullEngine.prototype.releaseEffects = function () {
  113544. };
  113545. NullEngine.prototype.displayLoadingUI = function () {
  113546. };
  113547. NullEngine.prototype.hideLoadingUI = function () {
  113548. };
  113549. /** @hidden */
  113550. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  113551. if (faceIndex === void 0) { faceIndex = 0; }
  113552. if (lod === void 0) { lod = 0; }
  113553. };
  113554. /** @hidden */
  113555. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  113556. if (faceIndex === void 0) { faceIndex = 0; }
  113557. if (lod === void 0) { lod = 0; }
  113558. };
  113559. /** @hidden */
  113560. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  113561. if (faceIndex === void 0) { faceIndex = 0; }
  113562. if (lod === void 0) { lod = 0; }
  113563. };
  113564. /** @hidden */
  113565. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  113566. if (faceIndex === void 0) { faceIndex = 0; }
  113567. if (lod === void 0) { lod = 0; }
  113568. };
  113569. return NullEngine;
  113570. }(BABYLON.Engine));
  113571. BABYLON.NullEngine = NullEngine;
  113572. })(BABYLON || (BABYLON = {}));
  113573. //# sourceMappingURL=babylon.nullEngine.js.map
  113574. var BABYLON;
  113575. (function (BABYLON) {
  113576. /**
  113577. * This class can be used to get instrumentation data from a Babylon engine
  113578. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113579. */
  113580. var EngineInstrumentation = /** @class */ (function () {
  113581. /**
  113582. * Instantiates a new engine instrumentation.
  113583. * This class can be used to get instrumentation data from a Babylon engine
  113584. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113585. * @param engine Defines the engine to instrument
  113586. */
  113587. function EngineInstrumentation(
  113588. /**
  113589. * Define the instrumented engine.
  113590. */
  113591. engine) {
  113592. this.engine = engine;
  113593. this._captureGPUFrameTime = false;
  113594. this._gpuFrameTime = new BABYLON.PerfCounter();
  113595. this._captureShaderCompilationTime = false;
  113596. this._shaderCompilationTime = new BABYLON.PerfCounter();
  113597. // Observers
  113598. this._onBeginFrameObserver = null;
  113599. this._onEndFrameObserver = null;
  113600. this._onBeforeShaderCompilationObserver = null;
  113601. this._onAfterShaderCompilationObserver = null;
  113602. }
  113603. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  113604. // Properties
  113605. /**
  113606. * Gets the perf counter used for GPU frame time
  113607. */
  113608. get: function () {
  113609. return this._gpuFrameTime;
  113610. },
  113611. enumerable: true,
  113612. configurable: true
  113613. });
  113614. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  113615. /**
  113616. * Gets the GPU frame time capture status
  113617. */
  113618. get: function () {
  113619. return this._captureGPUFrameTime;
  113620. },
  113621. /**
  113622. * Enable or disable the GPU frame time capture
  113623. */
  113624. set: function (value) {
  113625. var _this = this;
  113626. if (value === this._captureGPUFrameTime) {
  113627. return;
  113628. }
  113629. this._captureGPUFrameTime = value;
  113630. if (value) {
  113631. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  113632. if (!_this._gpuFrameTimeToken) {
  113633. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  113634. }
  113635. });
  113636. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  113637. if (!_this._gpuFrameTimeToken) {
  113638. return;
  113639. }
  113640. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  113641. if (time > -1) {
  113642. _this._gpuFrameTimeToken = null;
  113643. _this._gpuFrameTime.fetchNewFrame();
  113644. _this._gpuFrameTime.addCount(time, true);
  113645. }
  113646. });
  113647. }
  113648. else {
  113649. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113650. this._onBeginFrameObserver = null;
  113651. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113652. this._onEndFrameObserver = null;
  113653. }
  113654. },
  113655. enumerable: true,
  113656. configurable: true
  113657. });
  113658. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  113659. /**
  113660. * Gets the perf counter used for shader compilation time
  113661. */
  113662. get: function () {
  113663. return this._shaderCompilationTime;
  113664. },
  113665. enumerable: true,
  113666. configurable: true
  113667. });
  113668. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  113669. /**
  113670. * Gets the shader compilation time capture status
  113671. */
  113672. get: function () {
  113673. return this._captureShaderCompilationTime;
  113674. },
  113675. /**
  113676. * Enable or disable the shader compilation time capture
  113677. */
  113678. set: function (value) {
  113679. var _this = this;
  113680. if (value === this._captureShaderCompilationTime) {
  113681. return;
  113682. }
  113683. this._captureShaderCompilationTime = value;
  113684. if (value) {
  113685. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  113686. _this._shaderCompilationTime.fetchNewFrame();
  113687. _this._shaderCompilationTime.beginMonitoring();
  113688. });
  113689. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  113690. _this._shaderCompilationTime.endMonitoring();
  113691. });
  113692. }
  113693. else {
  113694. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113695. this._onBeforeShaderCompilationObserver = null;
  113696. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113697. this._onAfterShaderCompilationObserver = null;
  113698. }
  113699. },
  113700. enumerable: true,
  113701. configurable: true
  113702. });
  113703. /**
  113704. * Dispose and release associated resources.
  113705. */
  113706. EngineInstrumentation.prototype.dispose = function () {
  113707. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113708. this._onBeginFrameObserver = null;
  113709. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113710. this._onEndFrameObserver = null;
  113711. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113712. this._onBeforeShaderCompilationObserver = null;
  113713. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113714. this._onAfterShaderCompilationObserver = null;
  113715. this.engine = null;
  113716. };
  113717. return EngineInstrumentation;
  113718. }());
  113719. BABYLON.EngineInstrumentation = EngineInstrumentation;
  113720. })(BABYLON || (BABYLON = {}));
  113721. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  113722. var BABYLON;
  113723. (function (BABYLON) {
  113724. /**
  113725. * This class can be used to get instrumentation data from a Babylon engine
  113726. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113727. */
  113728. var SceneInstrumentation = /** @class */ (function () {
  113729. /**
  113730. * Instantiates a new scene instrumentation.
  113731. * This class can be used to get instrumentation data from a Babylon engine
  113732. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113733. * @param scene Defines the scene to instrument
  113734. */
  113735. function SceneInstrumentation(
  113736. /**
  113737. * Defines the scene to instrument
  113738. */
  113739. scene) {
  113740. var _this = this;
  113741. this.scene = scene;
  113742. this._captureActiveMeshesEvaluationTime = false;
  113743. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  113744. this._captureRenderTargetsRenderTime = false;
  113745. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  113746. this._captureFrameTime = false;
  113747. this._frameTime = new BABYLON.PerfCounter();
  113748. this._captureRenderTime = false;
  113749. this._renderTime = new BABYLON.PerfCounter();
  113750. this._captureInterFrameTime = false;
  113751. this._interFrameTime = new BABYLON.PerfCounter();
  113752. this._captureParticlesRenderTime = false;
  113753. this._particlesRenderTime = new BABYLON.PerfCounter();
  113754. this._captureSpritesRenderTime = false;
  113755. this._spritesRenderTime = new BABYLON.PerfCounter();
  113756. this._capturePhysicsTime = false;
  113757. this._physicsTime = new BABYLON.PerfCounter();
  113758. this._captureAnimationsTime = false;
  113759. this._animationsTime = new BABYLON.PerfCounter();
  113760. this._captureCameraRenderTime = false;
  113761. this._cameraRenderTime = new BABYLON.PerfCounter();
  113762. // Observers
  113763. this._onBeforeActiveMeshesEvaluationObserver = null;
  113764. this._onAfterActiveMeshesEvaluationObserver = null;
  113765. this._onBeforeRenderTargetsRenderObserver = null;
  113766. this._onAfterRenderTargetsRenderObserver = null;
  113767. this._onAfterRenderObserver = null;
  113768. this._onBeforeDrawPhaseObserver = null;
  113769. this._onAfterDrawPhaseObserver = null;
  113770. this._onBeforeAnimationsObserver = null;
  113771. this._onBeforeParticlesRenderingObserver = null;
  113772. this._onAfterParticlesRenderingObserver = null;
  113773. this._onBeforeSpritesRenderingObserver = null;
  113774. this._onAfterSpritesRenderingObserver = null;
  113775. this._onBeforePhysicsObserver = null;
  113776. this._onAfterPhysicsObserver = null;
  113777. this._onAfterAnimationsObserver = null;
  113778. this._onBeforeCameraRenderObserver = null;
  113779. this._onAfterCameraRenderObserver = null;
  113780. // Before render
  113781. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  113782. if (_this._captureActiveMeshesEvaluationTime) {
  113783. _this._activeMeshesEvaluationTime.fetchNewFrame();
  113784. }
  113785. if (_this._captureRenderTargetsRenderTime) {
  113786. _this._renderTargetsRenderTime.fetchNewFrame();
  113787. }
  113788. if (_this._captureFrameTime) {
  113789. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  113790. _this._frameTime.beginMonitoring();
  113791. }
  113792. if (_this._captureInterFrameTime) {
  113793. _this._interFrameTime.endMonitoring();
  113794. }
  113795. if (_this._captureParticlesRenderTime) {
  113796. _this._particlesRenderTime.fetchNewFrame();
  113797. }
  113798. if (_this._captureSpritesRenderTime) {
  113799. _this._spritesRenderTime.fetchNewFrame();
  113800. }
  113801. if (_this._captureAnimationsTime) {
  113802. _this._animationsTime.beginMonitoring();
  113803. }
  113804. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  113805. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  113806. });
  113807. // After render
  113808. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  113809. if (_this._captureFrameTime) {
  113810. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  113811. _this._frameTime.endMonitoring();
  113812. }
  113813. if (_this._captureRenderTime) {
  113814. _this._renderTime.endMonitoring(false);
  113815. }
  113816. if (_this._captureInterFrameTime) {
  113817. _this._interFrameTime.beginMonitoring();
  113818. }
  113819. });
  113820. }
  113821. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  113822. // Properties
  113823. /**
  113824. * Gets the perf counter used for active meshes evaluation time
  113825. */
  113826. get: function () {
  113827. return this._activeMeshesEvaluationTime;
  113828. },
  113829. enumerable: true,
  113830. configurable: true
  113831. });
  113832. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  113833. /**
  113834. * Gets the active meshes evaluation time capture status
  113835. */
  113836. get: function () {
  113837. return this._captureActiveMeshesEvaluationTime;
  113838. },
  113839. /**
  113840. * Enable or disable the active meshes evaluation time capture
  113841. */
  113842. set: function (value) {
  113843. var _this = this;
  113844. if (value === this._captureActiveMeshesEvaluationTime) {
  113845. return;
  113846. }
  113847. this._captureActiveMeshesEvaluationTime = value;
  113848. if (value) {
  113849. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  113850. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  113851. _this._activeMeshesEvaluationTime.beginMonitoring();
  113852. });
  113853. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  113854. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  113855. _this._activeMeshesEvaluationTime.endMonitoring();
  113856. });
  113857. }
  113858. else {
  113859. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  113860. this._onBeforeActiveMeshesEvaluationObserver = null;
  113861. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  113862. this._onAfterActiveMeshesEvaluationObserver = null;
  113863. }
  113864. },
  113865. enumerable: true,
  113866. configurable: true
  113867. });
  113868. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  113869. /**
  113870. * Gets the perf counter used for render targets render time
  113871. */
  113872. get: function () {
  113873. return this._renderTargetsRenderTime;
  113874. },
  113875. enumerable: true,
  113876. configurable: true
  113877. });
  113878. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  113879. /**
  113880. * Gets the render targets render time capture status
  113881. */
  113882. get: function () {
  113883. return this._captureRenderTargetsRenderTime;
  113884. },
  113885. /**
  113886. * Enable or disable the render targets render time capture
  113887. */
  113888. set: function (value) {
  113889. var _this = this;
  113890. if (value === this._captureRenderTargetsRenderTime) {
  113891. return;
  113892. }
  113893. this._captureRenderTargetsRenderTime = value;
  113894. if (value) {
  113895. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  113896. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  113897. _this._renderTargetsRenderTime.beginMonitoring();
  113898. });
  113899. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  113900. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  113901. _this._renderTargetsRenderTime.endMonitoring(false);
  113902. });
  113903. }
  113904. else {
  113905. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  113906. this._onBeforeRenderTargetsRenderObserver = null;
  113907. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  113908. this._onAfterRenderTargetsRenderObserver = null;
  113909. }
  113910. },
  113911. enumerable: true,
  113912. configurable: true
  113913. });
  113914. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  113915. /**
  113916. * Gets the perf counter used for particles render time
  113917. */
  113918. get: function () {
  113919. return this._particlesRenderTime;
  113920. },
  113921. enumerable: true,
  113922. configurable: true
  113923. });
  113924. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  113925. /**
  113926. * Gets the particles render time capture status
  113927. */
  113928. get: function () {
  113929. return this._captureParticlesRenderTime;
  113930. },
  113931. /**
  113932. * Enable or disable the particles render time capture
  113933. */
  113934. set: function (value) {
  113935. var _this = this;
  113936. if (value === this._captureParticlesRenderTime) {
  113937. return;
  113938. }
  113939. this._captureParticlesRenderTime = value;
  113940. if (value) {
  113941. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  113942. BABYLON.Tools.StartPerformanceCounter("Particles");
  113943. _this._particlesRenderTime.beginMonitoring();
  113944. });
  113945. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  113946. BABYLON.Tools.EndPerformanceCounter("Particles");
  113947. _this._particlesRenderTime.endMonitoring(false);
  113948. });
  113949. }
  113950. else {
  113951. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  113952. this._onBeforeParticlesRenderingObserver = null;
  113953. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  113954. this._onAfterParticlesRenderingObserver = null;
  113955. }
  113956. },
  113957. enumerable: true,
  113958. configurable: true
  113959. });
  113960. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  113961. /**
  113962. * Gets the perf counter used for sprites render time
  113963. */
  113964. get: function () {
  113965. return this._spritesRenderTime;
  113966. },
  113967. enumerable: true,
  113968. configurable: true
  113969. });
  113970. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  113971. /**
  113972. * Gets the sprites render time capture status
  113973. */
  113974. get: function () {
  113975. return this._captureSpritesRenderTime;
  113976. },
  113977. /**
  113978. * Enable or disable the sprites render time capture
  113979. */
  113980. set: function (value) {
  113981. var _this = this;
  113982. if (value === this._captureSpritesRenderTime) {
  113983. return;
  113984. }
  113985. this._captureSpritesRenderTime = value;
  113986. if (!this.scene.spriteManagers) {
  113987. return;
  113988. }
  113989. if (value) {
  113990. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  113991. BABYLON.Tools.StartPerformanceCounter("Sprites");
  113992. _this._spritesRenderTime.beginMonitoring();
  113993. });
  113994. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  113995. BABYLON.Tools.EndPerformanceCounter("Sprites");
  113996. _this._spritesRenderTime.endMonitoring(false);
  113997. });
  113998. }
  113999. else {
  114000. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  114001. this._onBeforeSpritesRenderingObserver = null;
  114002. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  114003. this._onAfterSpritesRenderingObserver = null;
  114004. }
  114005. },
  114006. enumerable: true,
  114007. configurable: true
  114008. });
  114009. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  114010. /**
  114011. * Gets the perf counter used for physics time
  114012. */
  114013. get: function () {
  114014. return this._physicsTime;
  114015. },
  114016. enumerable: true,
  114017. configurable: true
  114018. });
  114019. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  114020. /**
  114021. * Gets the physics time capture status
  114022. */
  114023. get: function () {
  114024. return this._capturePhysicsTime;
  114025. },
  114026. /**
  114027. * Enable or disable the physics time capture
  114028. */
  114029. set: function (value) {
  114030. var _this = this;
  114031. if (value === this._capturePhysicsTime) {
  114032. return;
  114033. }
  114034. if (!this.scene.onBeforePhysicsObservable) {
  114035. return;
  114036. }
  114037. this._capturePhysicsTime = value;
  114038. if (value) {
  114039. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  114040. BABYLON.Tools.StartPerformanceCounter("Physics");
  114041. _this._physicsTime.beginMonitoring();
  114042. });
  114043. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  114044. BABYLON.Tools.EndPerformanceCounter("Physics");
  114045. _this._physicsTime.endMonitoring();
  114046. });
  114047. }
  114048. else {
  114049. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  114050. this._onBeforePhysicsObserver = null;
  114051. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  114052. this._onAfterPhysicsObserver = null;
  114053. }
  114054. },
  114055. enumerable: true,
  114056. configurable: true
  114057. });
  114058. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  114059. /**
  114060. * Gets the perf counter used for animations time
  114061. */
  114062. get: function () {
  114063. return this._animationsTime;
  114064. },
  114065. enumerable: true,
  114066. configurable: true
  114067. });
  114068. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  114069. /**
  114070. * Gets the animations time capture status
  114071. */
  114072. get: function () {
  114073. return this._captureAnimationsTime;
  114074. },
  114075. /**
  114076. * Enable or disable the animations time capture
  114077. */
  114078. set: function (value) {
  114079. var _this = this;
  114080. if (value === this._captureAnimationsTime) {
  114081. return;
  114082. }
  114083. this._captureAnimationsTime = value;
  114084. if (value) {
  114085. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  114086. _this._animationsTime.endMonitoring();
  114087. });
  114088. }
  114089. else {
  114090. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  114091. this._onAfterAnimationsObserver = null;
  114092. }
  114093. },
  114094. enumerable: true,
  114095. configurable: true
  114096. });
  114097. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  114098. /**
  114099. * Gets the perf counter used for frame time capture
  114100. */
  114101. get: function () {
  114102. return this._frameTime;
  114103. },
  114104. enumerable: true,
  114105. configurable: true
  114106. });
  114107. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  114108. /**
  114109. * Gets the frame time capture status
  114110. */
  114111. get: function () {
  114112. return this._captureFrameTime;
  114113. },
  114114. /**
  114115. * Enable or disable the frame time capture
  114116. */
  114117. set: function (value) {
  114118. this._captureFrameTime = value;
  114119. },
  114120. enumerable: true,
  114121. configurable: true
  114122. });
  114123. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  114124. /**
  114125. * Gets the perf counter used for inter-frames time capture
  114126. */
  114127. get: function () {
  114128. return this._interFrameTime;
  114129. },
  114130. enumerable: true,
  114131. configurable: true
  114132. });
  114133. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  114134. /**
  114135. * Gets the inter-frames time capture status
  114136. */
  114137. get: function () {
  114138. return this._captureInterFrameTime;
  114139. },
  114140. /**
  114141. * Enable or disable the inter-frames time capture
  114142. */
  114143. set: function (value) {
  114144. this._captureInterFrameTime = value;
  114145. },
  114146. enumerable: true,
  114147. configurable: true
  114148. });
  114149. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  114150. /**
  114151. * Gets the perf counter used for render time capture
  114152. */
  114153. get: function () {
  114154. return this._renderTime;
  114155. },
  114156. enumerable: true,
  114157. configurable: true
  114158. });
  114159. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  114160. /**
  114161. * Gets the render time capture status
  114162. */
  114163. get: function () {
  114164. return this._captureRenderTime;
  114165. },
  114166. /**
  114167. * Enable or disable the render time capture
  114168. */
  114169. set: function (value) {
  114170. var _this = this;
  114171. if (value === this._captureRenderTime) {
  114172. return;
  114173. }
  114174. this._captureRenderTime = value;
  114175. if (value) {
  114176. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  114177. _this._renderTime.beginMonitoring();
  114178. BABYLON.Tools.StartPerformanceCounter("Main render");
  114179. });
  114180. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  114181. _this._renderTime.endMonitoring(false);
  114182. BABYLON.Tools.EndPerformanceCounter("Main render");
  114183. });
  114184. }
  114185. else {
  114186. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  114187. this._onBeforeDrawPhaseObserver = null;
  114188. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  114189. this._onAfterDrawPhaseObserver = null;
  114190. }
  114191. },
  114192. enumerable: true,
  114193. configurable: true
  114194. });
  114195. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  114196. /**
  114197. * Gets the perf counter used for camera render time capture
  114198. */
  114199. get: function () {
  114200. return this._cameraRenderTime;
  114201. },
  114202. enumerable: true,
  114203. configurable: true
  114204. });
  114205. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  114206. /**
  114207. * Gets the camera render time capture status
  114208. */
  114209. get: function () {
  114210. return this._captureCameraRenderTime;
  114211. },
  114212. /**
  114213. * Enable or disable the camera render time capture
  114214. */
  114215. set: function (value) {
  114216. var _this = this;
  114217. if (value === this._captureCameraRenderTime) {
  114218. return;
  114219. }
  114220. this._captureCameraRenderTime = value;
  114221. if (value) {
  114222. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  114223. _this._cameraRenderTime.beginMonitoring();
  114224. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  114225. });
  114226. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  114227. _this._cameraRenderTime.endMonitoring(false);
  114228. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  114229. });
  114230. }
  114231. else {
  114232. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  114233. this._onBeforeCameraRenderObserver = null;
  114234. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  114235. this._onAfterCameraRenderObserver = null;
  114236. }
  114237. },
  114238. enumerable: true,
  114239. configurable: true
  114240. });
  114241. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  114242. /**
  114243. * Gets the perf counter used for draw calls
  114244. */
  114245. get: function () {
  114246. return this.scene.getEngine()._drawCalls;
  114247. },
  114248. enumerable: true,
  114249. configurable: true
  114250. });
  114251. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  114252. /**
  114253. * Gets the perf counter used for texture collisions
  114254. */
  114255. get: function () {
  114256. return this.scene.getEngine()._textureCollisions;
  114257. },
  114258. enumerable: true,
  114259. configurable: true
  114260. });
  114261. /**
  114262. * Dispose and release associated resources.
  114263. */
  114264. SceneInstrumentation.prototype.dispose = function () {
  114265. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  114266. this._onAfterRenderObserver = null;
  114267. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  114268. this._onBeforeActiveMeshesEvaluationObserver = null;
  114269. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  114270. this._onAfterActiveMeshesEvaluationObserver = null;
  114271. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  114272. this._onBeforeRenderTargetsRenderObserver = null;
  114273. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  114274. this._onAfterRenderTargetsRenderObserver = null;
  114275. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  114276. this._onBeforeAnimationsObserver = null;
  114277. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  114278. this._onBeforeParticlesRenderingObserver = null;
  114279. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  114280. this._onAfterParticlesRenderingObserver = null;
  114281. if (this._onBeforeSpritesRenderingObserver) {
  114282. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  114283. this._onBeforeSpritesRenderingObserver = null;
  114284. }
  114285. if (this._onAfterSpritesRenderingObserver) {
  114286. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  114287. this._onAfterSpritesRenderingObserver = null;
  114288. }
  114289. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  114290. this._onBeforeDrawPhaseObserver = null;
  114291. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  114292. this._onAfterDrawPhaseObserver = null;
  114293. if (this._onBeforePhysicsObserver) {
  114294. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  114295. this._onBeforePhysicsObserver = null;
  114296. }
  114297. if (this._onAfterPhysicsObserver) {
  114298. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  114299. this._onAfterPhysicsObserver = null;
  114300. }
  114301. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  114302. this._onAfterAnimationsObserver = null;
  114303. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  114304. this._onBeforeCameraRenderObserver = null;
  114305. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  114306. this._onAfterCameraRenderObserver = null;
  114307. this.scene = null;
  114308. };
  114309. return SceneInstrumentation;
  114310. }());
  114311. BABYLON.SceneInstrumentation = SceneInstrumentation;
  114312. })(BABYLON || (BABYLON = {}));
  114313. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  114314. var BABYLON;
  114315. (function (BABYLON) {
  114316. /**
  114317. * @hidden
  114318. **/
  114319. var _TimeToken = /** @class */ (function () {
  114320. function _TimeToken() {
  114321. this._timeElapsedQueryEnded = false;
  114322. }
  114323. return _TimeToken;
  114324. }());
  114325. BABYLON._TimeToken = _TimeToken;
  114326. })(BABYLON || (BABYLON = {}));
  114327. //# sourceMappingURL=babylon.timeToken.js.map
  114328. var BABYLON;
  114329. (function (BABYLON) {
  114330. /**
  114331. * Background material defines definition.
  114332. * @hidden Mainly internal Use
  114333. */
  114334. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  114335. __extends(BackgroundMaterialDefines, _super);
  114336. /**
  114337. * Constructor of the defines.
  114338. */
  114339. function BackgroundMaterialDefines() {
  114340. var _this = _super.call(this) || this;
  114341. /**
  114342. * True if the diffuse texture is in use.
  114343. */
  114344. _this.DIFFUSE = false;
  114345. /**
  114346. * The direct UV channel to use.
  114347. */
  114348. _this.DIFFUSEDIRECTUV = 0;
  114349. /**
  114350. * True if the diffuse texture is in gamma space.
  114351. */
  114352. _this.GAMMADIFFUSE = false;
  114353. /**
  114354. * True if the diffuse texture has opacity in the alpha channel.
  114355. */
  114356. _this.DIFFUSEHASALPHA = false;
  114357. /**
  114358. * True if you want the material to fade to transparent at grazing angle.
  114359. */
  114360. _this.OPACITYFRESNEL = false;
  114361. /**
  114362. * True if an extra blur needs to be added in the reflection.
  114363. */
  114364. _this.REFLECTIONBLUR = false;
  114365. /**
  114366. * True if you want the material to fade to reflection at grazing angle.
  114367. */
  114368. _this.REFLECTIONFRESNEL = false;
  114369. /**
  114370. * True if you want the material to falloff as far as you move away from the scene center.
  114371. */
  114372. _this.REFLECTIONFALLOFF = false;
  114373. /**
  114374. * False if the current Webgl implementation does not support the texture lod extension.
  114375. */
  114376. _this.TEXTURELODSUPPORT = false;
  114377. /**
  114378. * True to ensure the data are premultiplied.
  114379. */
  114380. _this.PREMULTIPLYALPHA = false;
  114381. /**
  114382. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  114383. */
  114384. _this.USERGBCOLOR = false;
  114385. /**
  114386. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  114387. * stays aligned with the desired configuration.
  114388. */
  114389. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  114390. /**
  114391. * True to add noise in order to reduce the banding effect.
  114392. */
  114393. _this.NOISE = false;
  114394. /**
  114395. * is the reflection texture in BGR color scheme?
  114396. * Mainly used to solve a bug in ios10 video tag
  114397. */
  114398. _this.REFLECTIONBGR = false;
  114399. _this.IMAGEPROCESSING = false;
  114400. _this.VIGNETTE = false;
  114401. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  114402. _this.VIGNETTEBLENDMODEOPAQUE = false;
  114403. _this.TONEMAPPING = false;
  114404. _this.TONEMAPPING_ACES = false;
  114405. _this.CONTRAST = false;
  114406. _this.COLORCURVES = false;
  114407. _this.COLORGRADING = false;
  114408. _this.COLORGRADING3D = false;
  114409. _this.SAMPLER3DGREENDEPTH = false;
  114410. _this.SAMPLER3DBGRMAP = false;
  114411. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  114412. _this.EXPOSURE = false;
  114413. // Reflection.
  114414. _this.REFLECTION = false;
  114415. _this.REFLECTIONMAP_3D = false;
  114416. _this.REFLECTIONMAP_SPHERICAL = false;
  114417. _this.REFLECTIONMAP_PLANAR = false;
  114418. _this.REFLECTIONMAP_CUBIC = false;
  114419. _this.REFLECTIONMAP_PROJECTION = false;
  114420. _this.REFLECTIONMAP_SKYBOX = false;
  114421. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114422. _this.REFLECTIONMAP_EXPLICIT = false;
  114423. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114424. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114425. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  114426. _this.INVERTCUBICMAP = false;
  114427. _this.REFLECTIONMAP_OPPOSITEZ = false;
  114428. _this.LODINREFLECTIONALPHA = false;
  114429. _this.GAMMAREFLECTION = false;
  114430. _this.RGBDREFLECTION = false;
  114431. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  114432. // Default BJS.
  114433. _this.MAINUV1 = false;
  114434. _this.MAINUV2 = false;
  114435. _this.UV1 = false;
  114436. _this.UV2 = false;
  114437. _this.CLIPPLANE = false;
  114438. _this.CLIPPLANE2 = false;
  114439. _this.CLIPPLANE3 = false;
  114440. _this.CLIPPLANE4 = false;
  114441. _this.POINTSIZE = false;
  114442. _this.FOG = false;
  114443. _this.NORMAL = false;
  114444. _this.NUM_BONE_INFLUENCERS = 0;
  114445. _this.BonesPerMesh = 0;
  114446. _this.INSTANCES = false;
  114447. _this.SHADOWFLOAT = false;
  114448. _this.rebuild();
  114449. return _this;
  114450. }
  114451. return BackgroundMaterialDefines;
  114452. }(BABYLON.MaterialDefines));
  114453. /**
  114454. * Background material used to create an efficient environement around your scene.
  114455. */
  114456. var BackgroundMaterial = /** @class */ (function (_super) {
  114457. __extends(BackgroundMaterial, _super);
  114458. /**
  114459. * Instantiates a Background Material in the given scene
  114460. * @param name The friendly name of the material
  114461. * @param scene The scene to add the material to
  114462. */
  114463. function BackgroundMaterial(name, scene) {
  114464. var _this = _super.call(this, name, scene) || this;
  114465. /**
  114466. * Key light Color (multiply against the environement texture)
  114467. */
  114468. _this.primaryColor = BABYLON.Color3.White();
  114469. _this._primaryColorShadowLevel = 0;
  114470. _this._primaryColorHighlightLevel = 0;
  114471. /**
  114472. * Reflection Texture used in the material.
  114473. * Should be author in a specific way for the best result (refer to the documentation).
  114474. */
  114475. _this.reflectionTexture = null;
  114476. /**
  114477. * Reflection Texture level of blur.
  114478. *
  114479. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  114480. * texture twice.
  114481. */
  114482. _this.reflectionBlur = 0;
  114483. /**
  114484. * Diffuse Texture used in the material.
  114485. * Should be author in a specific way for the best result (refer to the documentation).
  114486. */
  114487. _this.diffuseTexture = null;
  114488. _this._shadowLights = null;
  114489. /**
  114490. * Specify the list of lights casting shadow on the material.
  114491. * All scene shadow lights will be included if null.
  114492. */
  114493. _this.shadowLights = null;
  114494. /**
  114495. * Helps adjusting the shadow to a softer level if required.
  114496. * 0 means black shadows and 1 means no shadows.
  114497. */
  114498. _this.shadowLevel = 0;
  114499. /**
  114500. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  114501. * It is usually zero but might be interesting to modify according to your setup.
  114502. */
  114503. _this.sceneCenter = BABYLON.Vector3.Zero();
  114504. /**
  114505. * This helps specifying that the material is falling off to the sky box at grazing angle.
  114506. * This helps ensuring a nice transition when the camera goes under the ground.
  114507. */
  114508. _this.opacityFresnel = true;
  114509. /**
  114510. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  114511. * This helps adding a mirror texture on the ground.
  114512. */
  114513. _this.reflectionFresnel = false;
  114514. /**
  114515. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  114516. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  114517. */
  114518. _this.reflectionFalloffDistance = 0.0;
  114519. /**
  114520. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  114521. */
  114522. _this.reflectionAmount = 1.0;
  114523. /**
  114524. * This specifies the weight of the reflection at grazing angle.
  114525. */
  114526. _this.reflectionReflectance0 = 0.05;
  114527. /**
  114528. * This specifies the weight of the reflection at a perpendicular point of view.
  114529. */
  114530. _this.reflectionReflectance90 = 0.5;
  114531. /**
  114532. * Helps to directly use the maps channels instead of their level.
  114533. */
  114534. _this.useRGBColor = true;
  114535. /**
  114536. * This helps reducing the banding effect that could occur on the background.
  114537. */
  114538. _this.enableNoise = false;
  114539. _this._fovMultiplier = 1.0;
  114540. /**
  114541. * Enable the FOV adjustment feature controlled by fovMultiplier.
  114542. */
  114543. _this.useEquirectangularFOV = false;
  114544. _this._maxSimultaneousLights = 4;
  114545. /**
  114546. * Number of Simultaneous lights allowed on the material.
  114547. */
  114548. _this.maxSimultaneousLights = 4;
  114549. /**
  114550. * Keep track of the image processing observer to allow dispose and replace.
  114551. */
  114552. _this._imageProcessingObserver = null;
  114553. /**
  114554. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  114555. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  114556. */
  114557. _this.switchToBGR = false;
  114558. // Temp values kept as cache in the material.
  114559. _this._renderTargets = new BABYLON.SmartArray(16);
  114560. _this._reflectionControls = BABYLON.Vector4.Zero();
  114561. _this._white = BABYLON.Color3.White();
  114562. _this._primaryShadowColor = BABYLON.Color3.Black();
  114563. _this._primaryHighlightColor = BABYLON.Color3.Black();
  114564. // Setup the default processing configuration to the scene.
  114565. _this._attachImageProcessingConfiguration(null);
  114566. _this.getRenderTargetTextures = function () {
  114567. _this._renderTargets.reset();
  114568. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  114569. _this._renderTargets.push(_this._diffuseTexture);
  114570. }
  114571. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  114572. _this._renderTargets.push(_this._reflectionTexture);
  114573. }
  114574. return _this._renderTargets;
  114575. };
  114576. return _this;
  114577. }
  114578. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  114579. /**
  114580. * Experimental Internal Use Only.
  114581. *
  114582. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  114583. * This acts as a helper to set the primary color to a more "human friendly" value.
  114584. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  114585. * output color as close as possible from the chosen value.
  114586. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  114587. * part of lighting setup.)
  114588. */
  114589. get: function () {
  114590. return this.__perceptualColor;
  114591. },
  114592. set: function (value) {
  114593. this.__perceptualColor = value;
  114594. this._computePrimaryColorFromPerceptualColor();
  114595. this._markAllSubMeshesAsLightsDirty();
  114596. },
  114597. enumerable: true,
  114598. configurable: true
  114599. });
  114600. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  114601. /**
  114602. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  114603. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  114604. */
  114605. get: function () {
  114606. return this._primaryColorShadowLevel;
  114607. },
  114608. set: function (value) {
  114609. this._primaryColorShadowLevel = value;
  114610. this._computePrimaryColors();
  114611. this._markAllSubMeshesAsLightsDirty();
  114612. },
  114613. enumerable: true,
  114614. configurable: true
  114615. });
  114616. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  114617. /**
  114618. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  114619. * The primary color is used at the level chosen to define what the white area would look.
  114620. */
  114621. get: function () {
  114622. return this._primaryColorHighlightLevel;
  114623. },
  114624. set: function (value) {
  114625. this._primaryColorHighlightLevel = value;
  114626. this._computePrimaryColors();
  114627. this._markAllSubMeshesAsLightsDirty();
  114628. },
  114629. enumerable: true,
  114630. configurable: true
  114631. });
  114632. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  114633. /**
  114634. * Sets the reflection reflectance fresnel values according to the default standard
  114635. * empirically know to work well :-)
  114636. */
  114637. set: function (value) {
  114638. var reflectionWeight = value;
  114639. if (reflectionWeight < 0.5) {
  114640. reflectionWeight = reflectionWeight * 2.0;
  114641. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  114642. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  114643. }
  114644. else {
  114645. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  114646. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  114647. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  114648. }
  114649. },
  114650. enumerable: true,
  114651. configurable: true
  114652. });
  114653. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  114654. /**
  114655. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114656. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  114657. * Recommended to be keep at 1.0 except for special cases.
  114658. */
  114659. get: function () {
  114660. return this._fovMultiplier;
  114661. },
  114662. set: function (value) {
  114663. if (isNaN(value)) {
  114664. value = 1.0;
  114665. }
  114666. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  114667. },
  114668. enumerable: true,
  114669. configurable: true
  114670. });
  114671. /**
  114672. * Attaches a new image processing configuration to the PBR Material.
  114673. * @param configuration (if null the scene configuration will be use)
  114674. */
  114675. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  114676. var _this = this;
  114677. if (configuration === this._imageProcessingConfiguration) {
  114678. return;
  114679. }
  114680. // Detaches observer.
  114681. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  114682. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  114683. }
  114684. // Pick the scene configuration if needed.
  114685. if (!configuration) {
  114686. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  114687. }
  114688. else {
  114689. this._imageProcessingConfiguration = configuration;
  114690. }
  114691. // Attaches observer.
  114692. if (this._imageProcessingConfiguration) {
  114693. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  114694. _this._computePrimaryColorFromPerceptualColor();
  114695. _this._markAllSubMeshesAsImageProcessingDirty();
  114696. });
  114697. }
  114698. };
  114699. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  114700. /**
  114701. * Gets the image processing configuration used either in this material.
  114702. */
  114703. get: function () {
  114704. return this._imageProcessingConfiguration;
  114705. },
  114706. /**
  114707. * Sets the Default image processing configuration used either in the this material.
  114708. *
  114709. * If sets to null, the scene one is in use.
  114710. */
  114711. set: function (value) {
  114712. this._attachImageProcessingConfiguration(value);
  114713. // Ensure the effect will be rebuilt.
  114714. this._markAllSubMeshesAsTexturesDirty();
  114715. },
  114716. enumerable: true,
  114717. configurable: true
  114718. });
  114719. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  114720. /**
  114721. * Gets wether the color curves effect is enabled.
  114722. */
  114723. get: function () {
  114724. return this.imageProcessingConfiguration.colorCurvesEnabled;
  114725. },
  114726. /**
  114727. * Sets wether the color curves effect is enabled.
  114728. */
  114729. set: function (value) {
  114730. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  114731. },
  114732. enumerable: true,
  114733. configurable: true
  114734. });
  114735. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  114736. /**
  114737. * Gets wether the color grading effect is enabled.
  114738. */
  114739. get: function () {
  114740. return this.imageProcessingConfiguration.colorGradingEnabled;
  114741. },
  114742. /**
  114743. * Gets wether the color grading effect is enabled.
  114744. */
  114745. set: function (value) {
  114746. this.imageProcessingConfiguration.colorGradingEnabled = value;
  114747. },
  114748. enumerable: true,
  114749. configurable: true
  114750. });
  114751. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  114752. /**
  114753. * Gets wether tonemapping is enabled or not.
  114754. */
  114755. get: function () {
  114756. return this._imageProcessingConfiguration.toneMappingEnabled;
  114757. },
  114758. /**
  114759. * Sets wether tonemapping is enabled or not
  114760. */
  114761. set: function (value) {
  114762. this._imageProcessingConfiguration.toneMappingEnabled = value;
  114763. },
  114764. enumerable: true,
  114765. configurable: true
  114766. });
  114767. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  114768. /**
  114769. * The camera exposure used on this material.
  114770. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114771. * This corresponds to a photographic exposure.
  114772. */
  114773. get: function () {
  114774. return this._imageProcessingConfiguration.exposure;
  114775. },
  114776. /**
  114777. * The camera exposure used on this material.
  114778. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114779. * This corresponds to a photographic exposure.
  114780. */
  114781. set: function (value) {
  114782. this._imageProcessingConfiguration.exposure = value;
  114783. },
  114784. enumerable: true,
  114785. configurable: true
  114786. });
  114787. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  114788. /**
  114789. * Gets The camera contrast used on this material.
  114790. */
  114791. get: function () {
  114792. return this._imageProcessingConfiguration.contrast;
  114793. },
  114794. /**
  114795. * Sets The camera contrast used on this material.
  114796. */
  114797. set: function (value) {
  114798. this._imageProcessingConfiguration.contrast = value;
  114799. },
  114800. enumerable: true,
  114801. configurable: true
  114802. });
  114803. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  114804. /**
  114805. * Gets the Color Grading 2D Lookup Texture.
  114806. */
  114807. get: function () {
  114808. return this._imageProcessingConfiguration.colorGradingTexture;
  114809. },
  114810. /**
  114811. * Sets the Color Grading 2D Lookup Texture.
  114812. */
  114813. set: function (value) {
  114814. this.imageProcessingConfiguration.colorGradingTexture = value;
  114815. },
  114816. enumerable: true,
  114817. configurable: true
  114818. });
  114819. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  114820. /**
  114821. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114822. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114823. * 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;
  114824. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114825. */
  114826. get: function () {
  114827. return this.imageProcessingConfiguration.colorCurves;
  114828. },
  114829. /**
  114830. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114831. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114832. * 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;
  114833. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114834. */
  114835. set: function (value) {
  114836. this.imageProcessingConfiguration.colorCurves = value;
  114837. },
  114838. enumerable: true,
  114839. configurable: true
  114840. });
  114841. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  114842. /**
  114843. * Gets a boolean indicating that current material needs to register RTT
  114844. */
  114845. get: function () {
  114846. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  114847. return true;
  114848. }
  114849. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  114850. return true;
  114851. }
  114852. return false;
  114853. },
  114854. enumerable: true,
  114855. configurable: true
  114856. });
  114857. /**
  114858. * The entire material has been created in order to prevent overdraw.
  114859. * @returns false
  114860. */
  114861. BackgroundMaterial.prototype.needAlphaTesting = function () {
  114862. return true;
  114863. };
  114864. /**
  114865. * The entire material has been created in order to prevent overdraw.
  114866. * @returns true if blending is enable
  114867. */
  114868. BackgroundMaterial.prototype.needAlphaBlending = function () {
  114869. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  114870. };
  114871. /**
  114872. * Checks wether the material is ready to be rendered for a given mesh.
  114873. * @param mesh The mesh to render
  114874. * @param subMesh The submesh to check against
  114875. * @param useInstances Specify wether or not the material is used with instances
  114876. * @returns true if all the dependencies are ready (Textures, Effects...)
  114877. */
  114878. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  114879. var _this = this;
  114880. if (useInstances === void 0) { useInstances = false; }
  114881. if (subMesh.effect && this.isFrozen) {
  114882. if (this._wasPreviouslyReady) {
  114883. return true;
  114884. }
  114885. }
  114886. if (!subMesh._materialDefines) {
  114887. subMesh._materialDefines = new BackgroundMaterialDefines();
  114888. }
  114889. var scene = this.getScene();
  114890. var defines = subMesh._materialDefines;
  114891. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  114892. if (defines._renderId === scene.getRenderId()) {
  114893. return true;
  114894. }
  114895. }
  114896. var engine = scene.getEngine();
  114897. // Lights
  114898. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  114899. defines._needNormals = true;
  114900. // Textures
  114901. if (defines._areTexturesDirty) {
  114902. defines._needUVs = false;
  114903. if (scene.texturesEnabled) {
  114904. if (scene.getEngine().getCaps().textureLOD) {
  114905. defines.TEXTURELODSUPPORT = true;
  114906. }
  114907. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114908. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  114909. return false;
  114910. }
  114911. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  114912. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  114913. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  114914. defines.OPACITYFRESNEL = this._opacityFresnel;
  114915. }
  114916. else {
  114917. defines.DIFFUSE = false;
  114918. defines.DIFFUSEHASALPHA = false;
  114919. defines.GAMMADIFFUSE = false;
  114920. defines.OPACITYFRESNEL = false;
  114921. }
  114922. var reflectionTexture = this._reflectionTexture;
  114923. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114924. if (!reflectionTexture.isReadyOrNotBlocking()) {
  114925. return false;
  114926. }
  114927. defines.REFLECTION = true;
  114928. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  114929. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  114930. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  114931. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  114932. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  114933. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  114934. defines.REFLECTIONBGR = this.switchToBGR;
  114935. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  114936. defines.INVERTCUBICMAP = true;
  114937. }
  114938. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  114939. switch (reflectionTexture.coordinatesMode) {
  114940. case BABYLON.Texture.EXPLICIT_MODE:
  114941. defines.REFLECTIONMAP_EXPLICIT = true;
  114942. break;
  114943. case BABYLON.Texture.PLANAR_MODE:
  114944. defines.REFLECTIONMAP_PLANAR = true;
  114945. break;
  114946. case BABYLON.Texture.PROJECTION_MODE:
  114947. defines.REFLECTIONMAP_PROJECTION = true;
  114948. break;
  114949. case BABYLON.Texture.SKYBOX_MODE:
  114950. defines.REFLECTIONMAP_SKYBOX = true;
  114951. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  114952. break;
  114953. case BABYLON.Texture.SPHERICAL_MODE:
  114954. defines.REFLECTIONMAP_SPHERICAL = true;
  114955. break;
  114956. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  114957. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  114958. break;
  114959. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  114960. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  114961. break;
  114962. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  114963. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  114964. break;
  114965. case BABYLON.Texture.CUBIC_MODE:
  114966. case BABYLON.Texture.INVCUBIC_MODE:
  114967. default:
  114968. defines.REFLECTIONMAP_CUBIC = true;
  114969. break;
  114970. }
  114971. if (this.reflectionFresnel) {
  114972. defines.REFLECTIONFRESNEL = true;
  114973. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  114974. this._reflectionControls.x = this.reflectionAmount;
  114975. this._reflectionControls.y = this.reflectionReflectance0;
  114976. this._reflectionControls.z = this.reflectionReflectance90;
  114977. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  114978. }
  114979. else {
  114980. defines.REFLECTIONFRESNEL = false;
  114981. defines.REFLECTIONFALLOFF = false;
  114982. }
  114983. }
  114984. else {
  114985. defines.REFLECTION = false;
  114986. defines.REFLECTIONFRESNEL = false;
  114987. defines.REFLECTIONFALLOFF = false;
  114988. defines.REFLECTIONBLUR = false;
  114989. defines.REFLECTIONMAP_3D = false;
  114990. defines.REFLECTIONMAP_SPHERICAL = false;
  114991. defines.REFLECTIONMAP_PLANAR = false;
  114992. defines.REFLECTIONMAP_CUBIC = false;
  114993. defines.REFLECTIONMAP_PROJECTION = false;
  114994. defines.REFLECTIONMAP_SKYBOX = false;
  114995. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114996. defines.REFLECTIONMAP_EXPLICIT = false;
  114997. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114998. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114999. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  115000. defines.INVERTCUBICMAP = false;
  115001. defines.REFLECTIONMAP_OPPOSITEZ = false;
  115002. defines.LODINREFLECTIONALPHA = false;
  115003. defines.GAMMAREFLECTION = false;
  115004. defines.RGBDREFLECTION = false;
  115005. }
  115006. }
  115007. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  115008. defines.USERGBCOLOR = this._useRGBColor;
  115009. defines.NOISE = this._enableNoise;
  115010. }
  115011. if (defines._areLightsDirty) {
  115012. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  115013. }
  115014. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  115015. if (!this._imageProcessingConfiguration.isReady()) {
  115016. return false;
  115017. }
  115018. this._imageProcessingConfiguration.prepareDefines(defines);
  115019. }
  115020. // Misc.
  115021. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  115022. // Values that need to be evaluated on every frame
  115023. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  115024. // Attribs
  115025. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  115026. if (mesh) {
  115027. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  115028. mesh.createNormals(true);
  115029. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  115030. }
  115031. }
  115032. }
  115033. // Get correct effect
  115034. if (defines.isDirty) {
  115035. defines.markAsProcessed();
  115036. scene.resetCachedMaterial();
  115037. // Fallbacks
  115038. var fallbacks = new BABYLON.EffectFallbacks();
  115039. if (defines.FOG) {
  115040. fallbacks.addFallback(0, "FOG");
  115041. }
  115042. if (defines.POINTSIZE) {
  115043. fallbacks.addFallback(1, "POINTSIZE");
  115044. }
  115045. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  115046. if (defines.NUM_BONE_INFLUENCERS > 0) {
  115047. fallbacks.addCPUSkinningFallback(0, mesh);
  115048. }
  115049. //Attributes
  115050. var attribs = [BABYLON.VertexBuffer.PositionKind];
  115051. if (defines.NORMAL) {
  115052. attribs.push(BABYLON.VertexBuffer.NormalKind);
  115053. }
  115054. if (defines.UV1) {
  115055. attribs.push(BABYLON.VertexBuffer.UVKind);
  115056. }
  115057. if (defines.UV2) {
  115058. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  115059. }
  115060. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  115061. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  115062. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  115063. "vFogInfos", "vFogColor", "pointSize",
  115064. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  115065. "vPrimaryColor", "vPrimaryColorShadow",
  115066. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  115067. "shadowLevel", "alpha",
  115068. "vBackgroundCenter", "vReflectionControl",
  115069. "vDiffuseInfos", "diffuseMatrix",
  115070. ];
  115071. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  115072. var uniformBuffers = ["Material", "Scene"];
  115073. if (BABYLON.ImageProcessingConfiguration) {
  115074. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  115075. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  115076. }
  115077. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  115078. uniformsNames: uniforms,
  115079. uniformBuffersNames: uniformBuffers,
  115080. samplers: samplers,
  115081. defines: defines,
  115082. maxSimultaneousLights: this._maxSimultaneousLights
  115083. });
  115084. var onCompiled = function (effect) {
  115085. if (_this.onCompiled) {
  115086. _this.onCompiled(effect);
  115087. }
  115088. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  115089. };
  115090. var join = defines.toString();
  115091. subMesh.setEffect(scene.getEngine().createEffect("background", {
  115092. attributes: attribs,
  115093. uniformsNames: uniforms,
  115094. uniformBuffersNames: uniformBuffers,
  115095. samplers: samplers,
  115096. defines: join,
  115097. fallbacks: fallbacks,
  115098. onCompiled: onCompiled,
  115099. onError: this.onError,
  115100. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  115101. }, engine), defines);
  115102. this.buildUniformLayout();
  115103. }
  115104. if (!subMesh.effect || !subMesh.effect.isReady()) {
  115105. return false;
  115106. }
  115107. defines._renderId = scene.getRenderId();
  115108. this._wasPreviouslyReady = true;
  115109. return true;
  115110. };
  115111. /**
  115112. * Compute the primary color according to the chosen perceptual color.
  115113. */
  115114. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  115115. if (!this.__perceptualColor) {
  115116. return;
  115117. }
  115118. this._primaryColor.copyFrom(this.__perceptualColor);
  115119. // Revert gamma space.
  115120. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  115121. // Revert image processing configuration.
  115122. if (this._imageProcessingConfiguration) {
  115123. // Revert Exposure.
  115124. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  115125. }
  115126. this._computePrimaryColors();
  115127. };
  115128. /**
  115129. * Compute the highlights and shadow colors according to their chosen levels.
  115130. */
  115131. BackgroundMaterial.prototype._computePrimaryColors = function () {
  115132. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  115133. return;
  115134. }
  115135. // Find the highlight color based on the configuration.
  115136. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  115137. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  115138. // Find the shadow color based on the configuration.
  115139. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  115140. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  115141. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  115142. };
  115143. /**
  115144. * Build the uniform buffer used in the material.
  115145. */
  115146. BackgroundMaterial.prototype.buildUniformLayout = function () {
  115147. // Order is important !
  115148. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  115149. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  115150. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  115151. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  115152. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  115153. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  115154. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  115155. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  115156. this._uniformBuffer.addUniform("pointSize", 1);
  115157. this._uniformBuffer.addUniform("shadowLevel", 1);
  115158. this._uniformBuffer.addUniform("alpha", 1);
  115159. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  115160. this._uniformBuffer.addUniform("vReflectionControl", 4);
  115161. this._uniformBuffer.create();
  115162. };
  115163. /**
  115164. * Unbind the material.
  115165. */
  115166. BackgroundMaterial.prototype.unbind = function () {
  115167. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  115168. this._uniformBuffer.setTexture("diffuseSampler", null);
  115169. }
  115170. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  115171. this._uniformBuffer.setTexture("reflectionSampler", null);
  115172. }
  115173. _super.prototype.unbind.call(this);
  115174. };
  115175. /**
  115176. * Bind only the world matrix to the material.
  115177. * @param world The world matrix to bind.
  115178. */
  115179. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  115180. this._activeEffect.setMatrix("world", world);
  115181. };
  115182. /**
  115183. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  115184. * @param world The world matrix to bind.
  115185. * @param subMesh The submesh to bind for.
  115186. */
  115187. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  115188. var scene = this.getScene();
  115189. var defines = subMesh._materialDefines;
  115190. if (!defines) {
  115191. return;
  115192. }
  115193. var effect = subMesh.effect;
  115194. if (!effect) {
  115195. return;
  115196. }
  115197. this._activeEffect = effect;
  115198. // Matrices
  115199. this.bindOnlyWorldMatrix(world);
  115200. // Bones
  115201. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  115202. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  115203. if (mustRebind) {
  115204. this._uniformBuffer.bindToEffect(effect, "Material");
  115205. this.bindViewProjection(effect);
  115206. var reflectionTexture = this._reflectionTexture;
  115207. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  115208. // Texture uniforms
  115209. if (scene.texturesEnabled) {
  115210. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  115211. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  115212. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  115213. }
  115214. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  115215. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  115216. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  115217. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  115218. }
  115219. }
  115220. if (this.shadowLevel > 0) {
  115221. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  115222. }
  115223. this._uniformBuffer.updateFloat("alpha", this.alpha);
  115224. // Point size
  115225. if (this.pointsCloud) {
  115226. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  115227. }
  115228. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  115229. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  115230. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  115231. }
  115232. else {
  115233. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  115234. }
  115235. }
  115236. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  115237. // Textures
  115238. if (scene.texturesEnabled) {
  115239. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  115240. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  115241. }
  115242. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  115243. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  115244. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  115245. }
  115246. else if (!defines.REFLECTIONBLUR) {
  115247. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  115248. }
  115249. else {
  115250. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  115251. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  115252. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  115253. }
  115254. if (defines.REFLECTIONFRESNEL) {
  115255. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  115256. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  115257. }
  115258. }
  115259. }
  115260. // Clip plane
  115261. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  115262. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  115263. }
  115264. if (mustRebind || !this.isFrozen) {
  115265. if (scene.lightsEnabled) {
  115266. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  115267. }
  115268. // View
  115269. this.bindView(effect);
  115270. // Fog
  115271. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  115272. // image processing
  115273. if (this._imageProcessingConfiguration) {
  115274. this._imageProcessingConfiguration.bind(this._activeEffect);
  115275. }
  115276. }
  115277. this._uniformBuffer.update();
  115278. this._afterBind(mesh, this._activeEffect);
  115279. };
  115280. /**
  115281. * Dispose the material.
  115282. * @param forceDisposeEffect Force disposal of the associated effect.
  115283. * @param forceDisposeTextures Force disposal of the associated textures.
  115284. */
  115285. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  115286. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  115287. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  115288. if (forceDisposeTextures) {
  115289. if (this.diffuseTexture) {
  115290. this.diffuseTexture.dispose();
  115291. }
  115292. if (this.reflectionTexture) {
  115293. this.reflectionTexture.dispose();
  115294. }
  115295. }
  115296. this._renderTargets.dispose();
  115297. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  115298. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  115299. }
  115300. _super.prototype.dispose.call(this, forceDisposeEffect);
  115301. };
  115302. /**
  115303. * Clones the material.
  115304. * @param name The cloned name.
  115305. * @returns The cloned material.
  115306. */
  115307. BackgroundMaterial.prototype.clone = function (name) {
  115308. var _this = this;
  115309. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  115310. };
  115311. /**
  115312. * Serializes the current material to its JSON representation.
  115313. * @returns The JSON representation.
  115314. */
  115315. BackgroundMaterial.prototype.serialize = function () {
  115316. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  115317. serializationObject.customType = "BABYLON.BackgroundMaterial";
  115318. return serializationObject;
  115319. };
  115320. /**
  115321. * Gets the class name of the material
  115322. * @returns "BackgroundMaterial"
  115323. */
  115324. BackgroundMaterial.prototype.getClassName = function () {
  115325. return "BackgroundMaterial";
  115326. };
  115327. /**
  115328. * Parse a JSON input to create back a background material.
  115329. * @param source The JSON data to parse
  115330. * @param scene The scene to create the parsed material in
  115331. * @param rootUrl The root url of the assets the material depends upon
  115332. * @returns the instantiated BackgroundMaterial.
  115333. */
  115334. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  115335. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  115336. };
  115337. /**
  115338. * Standard reflectance value at parallel view angle.
  115339. */
  115340. BackgroundMaterial.StandardReflectance0 = 0.05;
  115341. /**
  115342. * Standard reflectance value at grazing angle.
  115343. */
  115344. BackgroundMaterial.StandardReflectance90 = 0.5;
  115345. __decorate([
  115346. BABYLON.serializeAsColor3()
  115347. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  115348. __decorate([
  115349. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115350. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  115351. __decorate([
  115352. BABYLON.serializeAsColor3()
  115353. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  115354. __decorate([
  115355. BABYLON.serialize()
  115356. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  115357. __decorate([
  115358. BABYLON.serialize()
  115359. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  115360. __decorate([
  115361. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115362. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  115363. __decorate([
  115364. BABYLON.serializeAsTexture()
  115365. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  115366. __decorate([
  115367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115368. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  115369. __decorate([
  115370. BABYLON.serialize()
  115371. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  115372. __decorate([
  115373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115374. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  115375. __decorate([
  115376. BABYLON.serializeAsTexture()
  115377. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  115378. __decorate([
  115379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115380. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  115381. __decorate([
  115382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115383. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  115384. __decorate([
  115385. BABYLON.serialize()
  115386. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  115387. __decorate([
  115388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115389. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  115390. __decorate([
  115391. BABYLON.serializeAsVector3()
  115392. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  115393. __decorate([
  115394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115395. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  115396. __decorate([
  115397. BABYLON.serialize()
  115398. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  115399. __decorate([
  115400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115401. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  115402. __decorate([
  115403. BABYLON.serialize()
  115404. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  115405. __decorate([
  115406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115407. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  115408. __decorate([
  115409. BABYLON.serialize()
  115410. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  115411. __decorate([
  115412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115413. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  115414. __decorate([
  115415. BABYLON.serialize()
  115416. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  115417. __decorate([
  115418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115419. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  115420. __decorate([
  115421. BABYLON.serialize()
  115422. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  115423. __decorate([
  115424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115425. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  115426. __decorate([
  115427. BABYLON.serialize()
  115428. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  115429. __decorate([
  115430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115431. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  115432. __decorate([
  115433. BABYLON.serialize()
  115434. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  115435. __decorate([
  115436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115437. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  115438. __decorate([
  115439. BABYLON.serialize()
  115440. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  115441. __decorate([
  115442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115443. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  115444. __decorate([
  115445. BABYLON.serialize()
  115446. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  115447. __decorate([
  115448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115449. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  115450. __decorate([
  115451. BABYLON.serializeAsImageProcessingConfiguration()
  115452. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  115453. return BackgroundMaterial;
  115454. }(BABYLON.PushMaterial));
  115455. BABYLON.BackgroundMaterial = BackgroundMaterial;
  115456. })(BABYLON || (BABYLON = {}));
  115457. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  115458. var __assign = (this && this.__assign) || function () {
  115459. __assign = Object.assign || function(t) {
  115460. for (var s, i = 1, n = arguments.length; i < n; i++) {
  115461. s = arguments[i];
  115462. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  115463. t[p] = s[p];
  115464. }
  115465. return t;
  115466. };
  115467. return __assign.apply(this, arguments);
  115468. };
  115469. var BABYLON;
  115470. (function (BABYLON) {
  115471. /**
  115472. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  115473. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  115474. * It also helps with the default setup of your imageProcessing configuration.
  115475. */
  115476. var EnvironmentHelper = /** @class */ (function () {
  115477. /**
  115478. * constructor
  115479. * @param options
  115480. * @param scene The scene to add the material to
  115481. */
  115482. function EnvironmentHelper(options, scene) {
  115483. var _this = this;
  115484. this._errorHandler = function (message, exception) {
  115485. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  115486. };
  115487. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  115488. this._scene = scene;
  115489. this.onErrorObservable = new BABYLON.Observable();
  115490. this._setupBackground();
  115491. this._setupImageProcessing();
  115492. }
  115493. /**
  115494. * Creates the default options for the helper.
  115495. */
  115496. EnvironmentHelper._getDefaultOptions = function () {
  115497. return {
  115498. createGround: true,
  115499. groundSize: 15,
  115500. groundTexture: this._groundTextureCDNUrl,
  115501. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115502. groundOpacity: 0.9,
  115503. enableGroundShadow: true,
  115504. groundShadowLevel: 0.5,
  115505. enableGroundMirror: false,
  115506. groundMirrorSizeRatio: 0.3,
  115507. groundMirrorBlurKernel: 64,
  115508. groundMirrorAmount: 1,
  115509. groundMirrorFresnelWeight: 1,
  115510. groundMirrorFallOffDistance: 0,
  115511. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  115512. groundYBias: 0.00001,
  115513. createSkybox: true,
  115514. skyboxSize: 20,
  115515. skyboxTexture: this._skyboxTextureCDNUrl,
  115516. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115517. backgroundYRotation: 0,
  115518. sizeAuto: true,
  115519. rootPosition: BABYLON.Vector3.Zero(),
  115520. setupImageProcessing: true,
  115521. environmentTexture: this._environmentTextureCDNUrl,
  115522. cameraExposure: 0.8,
  115523. cameraContrast: 1.2,
  115524. toneMappingEnabled: true,
  115525. };
  115526. };
  115527. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  115528. /**
  115529. * Gets the root mesh created by the helper.
  115530. */
  115531. get: function () {
  115532. return this._rootMesh;
  115533. },
  115534. enumerable: true,
  115535. configurable: true
  115536. });
  115537. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  115538. /**
  115539. * Gets the skybox created by the helper.
  115540. */
  115541. get: function () {
  115542. return this._skybox;
  115543. },
  115544. enumerable: true,
  115545. configurable: true
  115546. });
  115547. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  115548. /**
  115549. * Gets the skybox texture created by the helper.
  115550. */
  115551. get: function () {
  115552. return this._skyboxTexture;
  115553. },
  115554. enumerable: true,
  115555. configurable: true
  115556. });
  115557. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  115558. /**
  115559. * Gets the skybox material created by the helper.
  115560. */
  115561. get: function () {
  115562. return this._skyboxMaterial;
  115563. },
  115564. enumerable: true,
  115565. configurable: true
  115566. });
  115567. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  115568. /**
  115569. * Gets the ground mesh created by the helper.
  115570. */
  115571. get: function () {
  115572. return this._ground;
  115573. },
  115574. enumerable: true,
  115575. configurable: true
  115576. });
  115577. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  115578. /**
  115579. * Gets the ground texture created by the helper.
  115580. */
  115581. get: function () {
  115582. return this._groundTexture;
  115583. },
  115584. enumerable: true,
  115585. configurable: true
  115586. });
  115587. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  115588. /**
  115589. * Gets the ground mirror created by the helper.
  115590. */
  115591. get: function () {
  115592. return this._groundMirror;
  115593. },
  115594. enumerable: true,
  115595. configurable: true
  115596. });
  115597. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  115598. /**
  115599. * Gets the ground mirror render list to helps pushing the meshes
  115600. * you wish in the ground reflection.
  115601. */
  115602. get: function () {
  115603. if (this._groundMirror) {
  115604. return this._groundMirror.renderList;
  115605. }
  115606. return null;
  115607. },
  115608. enumerable: true,
  115609. configurable: true
  115610. });
  115611. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  115612. /**
  115613. * Gets the ground material created by the helper.
  115614. */
  115615. get: function () {
  115616. return this._groundMaterial;
  115617. },
  115618. enumerable: true,
  115619. configurable: true
  115620. });
  115621. /**
  115622. * Updates the background according to the new options
  115623. * @param options
  115624. */
  115625. EnvironmentHelper.prototype.updateOptions = function (options) {
  115626. var newOptions = __assign({}, this._options, options);
  115627. if (this._ground && !newOptions.createGround) {
  115628. this._ground.dispose();
  115629. this._ground = null;
  115630. }
  115631. if (this._groundMaterial && !newOptions.createGround) {
  115632. this._groundMaterial.dispose();
  115633. this._groundMaterial = null;
  115634. }
  115635. if (this._groundTexture) {
  115636. if (this._options.groundTexture != newOptions.groundTexture) {
  115637. this._groundTexture.dispose();
  115638. this._groundTexture = null;
  115639. }
  115640. }
  115641. if (this._skybox && !newOptions.createSkybox) {
  115642. this._skybox.dispose();
  115643. this._skybox = null;
  115644. }
  115645. if (this._skyboxMaterial && !newOptions.createSkybox) {
  115646. this._skyboxMaterial.dispose();
  115647. this._skyboxMaterial = null;
  115648. }
  115649. if (this._skyboxTexture) {
  115650. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  115651. this._skyboxTexture.dispose();
  115652. this._skyboxTexture = null;
  115653. }
  115654. }
  115655. if (this._groundMirror && !newOptions.enableGroundMirror) {
  115656. this._groundMirror.dispose();
  115657. this._groundMirror = null;
  115658. }
  115659. if (this._scene.environmentTexture) {
  115660. if (this._options.environmentTexture != newOptions.environmentTexture) {
  115661. this._scene.environmentTexture.dispose();
  115662. }
  115663. }
  115664. this._options = newOptions;
  115665. this._setupBackground();
  115666. this._setupImageProcessing();
  115667. };
  115668. /**
  115669. * Sets the primary color of all the available elements.
  115670. * @param color the main color to affect to the ground and the background
  115671. */
  115672. EnvironmentHelper.prototype.setMainColor = function (color) {
  115673. if (this.groundMaterial) {
  115674. this.groundMaterial.primaryColor = color;
  115675. }
  115676. if (this.skyboxMaterial) {
  115677. this.skyboxMaterial.primaryColor = color;
  115678. }
  115679. if (this.groundMirror) {
  115680. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  115681. }
  115682. };
  115683. /**
  115684. * Setup the image processing according to the specified options.
  115685. */
  115686. EnvironmentHelper.prototype._setupImageProcessing = function () {
  115687. if (this._options.setupImageProcessing) {
  115688. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  115689. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  115690. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  115691. this._setupEnvironmentTexture();
  115692. }
  115693. };
  115694. /**
  115695. * Setup the environment texture according to the specified options.
  115696. */
  115697. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  115698. if (this._scene.environmentTexture) {
  115699. return;
  115700. }
  115701. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  115702. this._scene.environmentTexture = this._options.environmentTexture;
  115703. return;
  115704. }
  115705. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  115706. this._scene.environmentTexture = environmentTexture;
  115707. };
  115708. /**
  115709. * Setup the background according to the specified options.
  115710. */
  115711. EnvironmentHelper.prototype._setupBackground = function () {
  115712. if (!this._rootMesh) {
  115713. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  115714. }
  115715. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  115716. var sceneSize = this._getSceneSize();
  115717. if (this._options.createGround) {
  115718. this._setupGround(sceneSize);
  115719. this._setupGroundMaterial();
  115720. this._setupGroundDiffuseTexture();
  115721. if (this._options.enableGroundMirror) {
  115722. this._setupGroundMirrorTexture(sceneSize);
  115723. }
  115724. this._setupMirrorInGroundMaterial();
  115725. }
  115726. if (this._options.createSkybox) {
  115727. this._setupSkybox(sceneSize);
  115728. this._setupSkyboxMaterial();
  115729. this._setupSkyboxReflectionTexture();
  115730. }
  115731. this._rootMesh.position.x = sceneSize.rootPosition.x;
  115732. this._rootMesh.position.z = sceneSize.rootPosition.z;
  115733. this._rootMesh.position.y = sceneSize.rootPosition.y;
  115734. };
  115735. /**
  115736. * Get the scene sizes according to the setup.
  115737. */
  115738. EnvironmentHelper.prototype._getSceneSize = function () {
  115739. var _this = this;
  115740. var groundSize = this._options.groundSize;
  115741. var skyboxSize = this._options.skyboxSize;
  115742. var rootPosition = this._options.rootPosition;
  115743. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  115744. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115745. }
  115746. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  115747. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  115748. });
  115749. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  115750. if (this._options.sizeAuto) {
  115751. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  115752. this._scene.activeCamera.upperRadiusLimit) {
  115753. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  115754. skyboxSize = groundSize;
  115755. }
  115756. var sceneDiagonalLenght = sceneDiagonal.length();
  115757. if (sceneDiagonalLenght > groundSize) {
  115758. groundSize = sceneDiagonalLenght * 2;
  115759. skyboxSize = groundSize;
  115760. }
  115761. // 10 % bigger.
  115762. groundSize *= 1.1;
  115763. skyboxSize *= 1.5;
  115764. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  115765. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  115766. }
  115767. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115768. };
  115769. /**
  115770. * Setup the ground according to the specified options.
  115771. */
  115772. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  115773. var _this = this;
  115774. if (!this._ground || this._ground.isDisposed()) {
  115775. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  115776. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  115777. this._ground.parent = this._rootMesh;
  115778. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  115779. }
  115780. this._ground.receiveShadows = this._options.enableGroundShadow;
  115781. };
  115782. /**
  115783. * Setup the ground material according to the specified options.
  115784. */
  115785. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  115786. if (!this._groundMaterial) {
  115787. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  115788. }
  115789. this._groundMaterial.alpha = this._options.groundOpacity;
  115790. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  115791. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  115792. this._groundMaterial.primaryColor = this._options.groundColor;
  115793. this._groundMaterial.useRGBColor = false;
  115794. this._groundMaterial.enableNoise = true;
  115795. if (this._ground) {
  115796. this._ground.material = this._groundMaterial;
  115797. }
  115798. };
  115799. /**
  115800. * Setup the ground diffuse texture according to the specified options.
  115801. */
  115802. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  115803. if (!this._groundMaterial) {
  115804. return;
  115805. }
  115806. if (this._groundTexture) {
  115807. return;
  115808. }
  115809. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  115810. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  115811. return;
  115812. }
  115813. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115814. diffuseTexture.gammaSpace = false;
  115815. diffuseTexture.hasAlpha = true;
  115816. this._groundMaterial.diffuseTexture = diffuseTexture;
  115817. };
  115818. /**
  115819. * Setup the ground mirror texture according to the specified options.
  115820. */
  115821. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  115822. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115823. if (!this._groundMirror) {
  115824. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  115825. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  115826. this._groundMirror.anisotropicFilteringLevel = 1;
  115827. this._groundMirror.wrapU = wrapping;
  115828. this._groundMirror.wrapV = wrapping;
  115829. this._groundMirror.gammaSpace = false;
  115830. if (this._groundMirror.renderList) {
  115831. for (var i = 0; i < this._scene.meshes.length; i++) {
  115832. var mesh = this._scene.meshes[i];
  115833. if (mesh !== this._ground &&
  115834. mesh !== this._skybox &&
  115835. mesh !== this._rootMesh) {
  115836. this._groundMirror.renderList.push(mesh);
  115837. }
  115838. }
  115839. }
  115840. }
  115841. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  115842. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  115843. };
  115844. /**
  115845. * Setup the ground to receive the mirror texture.
  115846. */
  115847. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  115848. if (this._groundMaterial) {
  115849. this._groundMaterial.reflectionTexture = this._groundMirror;
  115850. this._groundMaterial.reflectionFresnel = true;
  115851. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  115852. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  115853. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  115854. }
  115855. };
  115856. /**
  115857. * Setup the skybox according to the specified options.
  115858. */
  115859. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  115860. var _this = this;
  115861. if (!this._skybox || this._skybox.isDisposed()) {
  115862. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  115863. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  115864. }
  115865. this._skybox.parent = this._rootMesh;
  115866. };
  115867. /**
  115868. * Setup the skybox material according to the specified options.
  115869. */
  115870. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  115871. if (!this._skybox) {
  115872. return;
  115873. }
  115874. if (!this._skyboxMaterial) {
  115875. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  115876. }
  115877. this._skyboxMaterial.useRGBColor = false;
  115878. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  115879. this._skyboxMaterial.enableNoise = true;
  115880. this._skybox.material = this._skyboxMaterial;
  115881. };
  115882. /**
  115883. * Setup the skybox reflection texture according to the specified options.
  115884. */
  115885. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  115886. if (!this._skyboxMaterial) {
  115887. return;
  115888. }
  115889. if (this._skyboxTexture) {
  115890. return;
  115891. }
  115892. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  115893. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  115894. return;
  115895. }
  115896. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115897. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115898. this._skyboxTexture.gammaSpace = false;
  115899. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  115900. };
  115901. /**
  115902. * Dispose all the elements created by the Helper.
  115903. */
  115904. EnvironmentHelper.prototype.dispose = function () {
  115905. if (this._groundMaterial) {
  115906. this._groundMaterial.dispose(true, true);
  115907. }
  115908. if (this._skyboxMaterial) {
  115909. this._skyboxMaterial.dispose(true, true);
  115910. }
  115911. this._rootMesh.dispose(false);
  115912. };
  115913. /**
  115914. * Default ground texture URL.
  115915. */
  115916. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  115917. /**
  115918. * Default skybox texture URL.
  115919. */
  115920. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  115921. /**
  115922. * Default environment texture URL.
  115923. */
  115924. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  115925. return EnvironmentHelper;
  115926. }());
  115927. BABYLON.EnvironmentHelper = EnvironmentHelper;
  115928. })(BABYLON || (BABYLON = {}));
  115929. //# sourceMappingURL=babylon.environmentHelper.js.map
  115930. var BABYLON;
  115931. (function (BABYLON) {
  115932. /** Internal class used to store shapes for emitters */
  115933. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  115934. function ParticleSystemSetEmitterCreationOptions() {
  115935. }
  115936. return ParticleSystemSetEmitterCreationOptions;
  115937. }());
  115938. /**
  115939. * Represents a set of particle systems working together to create a specific effect
  115940. */
  115941. var ParticleSystemSet = /** @class */ (function () {
  115942. function ParticleSystemSet() {
  115943. /**
  115944. * Gets the particle system list
  115945. */
  115946. this.systems = new Array();
  115947. }
  115948. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  115949. /**
  115950. * Gets the emitter node used with this set
  115951. */
  115952. get: function () {
  115953. return this._emitterNode;
  115954. },
  115955. enumerable: true,
  115956. configurable: true
  115957. });
  115958. /**
  115959. * Creates a new emitter mesh as a sphere
  115960. * @param options defines the options used to create the sphere
  115961. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  115962. * @param scene defines the hosting scene
  115963. */
  115964. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  115965. if (this._emitterNode) {
  115966. this._emitterNode.dispose();
  115967. }
  115968. this._emitterCreationOptions = {
  115969. kind: "Sphere",
  115970. options: options,
  115971. renderingGroupId: renderingGroupId
  115972. };
  115973. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  115974. emitterMesh.renderingGroupId = renderingGroupId;
  115975. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  115976. material.emissiveColor = options.color;
  115977. emitterMesh.material = material;
  115978. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115979. var system = _a[_i];
  115980. system.emitter = emitterMesh;
  115981. }
  115982. this._emitterNode = emitterMesh;
  115983. };
  115984. /**
  115985. * Starts all particle systems of the set
  115986. * @param emitter defines an optional mesh to use as emitter for the particle systems
  115987. */
  115988. ParticleSystemSet.prototype.start = function (emitter) {
  115989. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115990. var system = _a[_i];
  115991. if (emitter) {
  115992. system.emitter = emitter;
  115993. }
  115994. system.start();
  115995. }
  115996. };
  115997. /**
  115998. * Release all associated resources
  115999. */
  116000. ParticleSystemSet.prototype.dispose = function () {
  116001. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116002. var system = _a[_i];
  116003. system.dispose();
  116004. }
  116005. this.systems = [];
  116006. if (this._emitterNode) {
  116007. this._emitterNode.dispose();
  116008. this._emitterNode = null;
  116009. }
  116010. };
  116011. /**
  116012. * Serialize the set into a JSON compatible object
  116013. * @returns a JSON compatible representation of the set
  116014. */
  116015. ParticleSystemSet.prototype.serialize = function () {
  116016. var result = {};
  116017. result.systems = [];
  116018. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116019. var system = _a[_i];
  116020. result.systems.push(system.serialize());
  116021. }
  116022. if (this._emitterNode) {
  116023. result.emitter = this._emitterCreationOptions;
  116024. }
  116025. return result;
  116026. };
  116027. /**
  116028. * Parse a new ParticleSystemSet from a serialized source
  116029. * @param data defines a JSON compatible representation of the set
  116030. * @param scene defines the hosting scene
  116031. * @param gpu defines if we want GPU particles or CPU particles
  116032. * @returns a new ParticleSystemSet
  116033. */
  116034. ParticleSystemSet.Parse = function (data, scene, gpu) {
  116035. if (gpu === void 0) { gpu = false; }
  116036. var result = new ParticleSystemSet();
  116037. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  116038. scene = scene || BABYLON.Engine.LastCreatedScene;
  116039. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  116040. var system = _a[_i];
  116041. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  116042. }
  116043. if (data.emitter) {
  116044. var options = data.emitter.options;
  116045. switch (data.emitter.kind) {
  116046. case "Sphere":
  116047. result.setEmitterAsSphere({
  116048. diameter: options.diameter,
  116049. segments: options.segments,
  116050. color: BABYLON.Color3.FromArray(options.color)
  116051. }, data.emitter.renderingGroupId, scene);
  116052. break;
  116053. }
  116054. }
  116055. return result;
  116056. };
  116057. return ParticleSystemSet;
  116058. }());
  116059. BABYLON.ParticleSystemSet = ParticleSystemSet;
  116060. })(BABYLON || (BABYLON = {}));
  116061. //# sourceMappingURL=babylon.particleSystemSet.js.map
  116062. var BABYLON;
  116063. (function (BABYLON) {
  116064. /**
  116065. * This class is made for on one-liner static method to help creating particle system set.
  116066. */
  116067. var ParticleHelper = /** @class */ (function () {
  116068. function ParticleHelper() {
  116069. }
  116070. /**
  116071. * Create a default particle system that you can tweak
  116072. * @param emitter defines the emitter to use
  116073. * @param capacity defines the system capacity (default is 500 particles)
  116074. * @param scene defines the hosting scene
  116075. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  116076. * @returns the new Particle system
  116077. */
  116078. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  116079. if (capacity === void 0) { capacity = 500; }
  116080. if (useGPU === void 0) { useGPU = false; }
  116081. var system;
  116082. if (useGPU) {
  116083. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  116084. }
  116085. else {
  116086. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  116087. }
  116088. system.emitter = emitter;
  116089. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  116090. system.createConeEmitter(0.1, Math.PI / 4);
  116091. // Particle color
  116092. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  116093. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  116094. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  116095. // Particle Size
  116096. system.minSize = 0.1;
  116097. system.maxSize = 0.1;
  116098. // Emission speed
  116099. system.minEmitPower = 2;
  116100. system.maxEmitPower = 2;
  116101. // Update speed
  116102. system.updateSpeed = 1 / 60;
  116103. system.emitRate = 30;
  116104. return system;
  116105. };
  116106. /**
  116107. * This is the main static method (one-liner) of this helper to create different particle systems
  116108. * @param type This string represents the type to the particle system to create
  116109. * @param scene The scene where the particle system should live
  116110. * @param gpu If the system will use gpu
  116111. * @returns the ParticleSystemSet created
  116112. */
  116113. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  116114. if (gpu === void 0) { gpu = false; }
  116115. if (!scene) {
  116116. scene = BABYLON.Engine.LastCreatedScene;
  116117. }
  116118. var token = {};
  116119. scene._addPendingData(token);
  116120. return new Promise(function (resolve, reject) {
  116121. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  116122. scene._removePendingData(token);
  116123. return reject("Particle system with GPU is not supported.");
  116124. }
  116125. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  116126. scene._removePendingData(token);
  116127. var newData = JSON.parse(data.toString());
  116128. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  116129. }, undefined, undefined, undefined, function (req, exception) {
  116130. scene._removePendingData(token);
  116131. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  116132. });
  116133. });
  116134. };
  116135. /**
  116136. * Static function used to export a particle system to a ParticleSystemSet variable.
  116137. * Please note that the emitter shape is not exported
  116138. * @param systems defines the particle systems to export
  116139. * @returns the created particle system set
  116140. */
  116141. ParticleHelper.ExportSet = function (systems) {
  116142. var set = new BABYLON.ParticleSystemSet();
  116143. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  116144. var system = systems_1[_i];
  116145. set.systems.push(system);
  116146. }
  116147. return set;
  116148. };
  116149. /**
  116150. * Gets or sets base Assets URL
  116151. */
  116152. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  116153. return ParticleHelper;
  116154. }());
  116155. BABYLON.ParticleHelper = ParticleHelper;
  116156. })(BABYLON || (BABYLON = {}));
  116157. //# sourceMappingURL=babylon.particleHelper.js.map
  116158. var BABYLON;
  116159. (function (BABYLON) {
  116160. /**
  116161. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  116162. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  116163. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  116164. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  116165. */
  116166. var VideoDome = /** @class */ (function (_super) {
  116167. __extends(VideoDome, _super);
  116168. /**
  116169. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  116170. * @param name Element's name, child elements will append suffixes for their own names.
  116171. * @param urlsOrVideo defines the url(s) or the video element to use
  116172. * @param options An object containing optional or exposed sub element properties
  116173. */
  116174. function VideoDome(name, urlsOrVideo, options, scene) {
  116175. var _this = _super.call(this, name, scene) || this;
  116176. _this._useDirectMapping = false;
  116177. // set defaults and manage values
  116178. name = name || "videoDome";
  116179. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  116180. options.clickToPlay = Boolean(options.clickToPlay);
  116181. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  116182. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  116183. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  116184. if (options.useDirectMapping === undefined) {
  116185. _this._useDirectMapping = true;
  116186. }
  116187. else {
  116188. _this._useDirectMapping = options.useDirectMapping;
  116189. }
  116190. _this._setReady(false);
  116191. // create
  116192. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  116193. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  116194. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  116195. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  116196. texture.onLoadObservable.addOnce(function () {
  116197. _this._setReady(true);
  116198. });
  116199. // configure material
  116200. material.useEquirectangularFOV = true;
  116201. material.fovMultiplier = 1.0;
  116202. material.opacityFresnel = false;
  116203. if (_this._useDirectMapping) {
  116204. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116205. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116206. material.diffuseTexture = texture;
  116207. }
  116208. else {
  116209. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116210. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116211. material.reflectionTexture = texture;
  116212. }
  116213. // configure mesh
  116214. _this._mesh.material = material;
  116215. _this._mesh.parent = _this;
  116216. // optional configuration
  116217. if (options.clickToPlay) {
  116218. scene.onPointerUp = function () {
  116219. _this._videoTexture.video.play();
  116220. };
  116221. }
  116222. return _this;
  116223. }
  116224. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  116225. /**
  116226. * Gets the video texture being displayed on the sphere
  116227. */
  116228. get: function () {
  116229. return this._videoTexture;
  116230. },
  116231. enumerable: true,
  116232. configurable: true
  116233. });
  116234. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  116235. /**
  116236. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116237. * Also see the options.resolution property.
  116238. */
  116239. get: function () {
  116240. return this._material.fovMultiplier;
  116241. },
  116242. set: function (value) {
  116243. this._material.fovMultiplier = value;
  116244. },
  116245. enumerable: true,
  116246. configurable: true
  116247. });
  116248. /**
  116249. * Releases resources associated with this node.
  116250. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116251. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116252. */
  116253. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116254. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116255. this._videoTexture.dispose();
  116256. this._mesh.dispose();
  116257. this._material.dispose();
  116258. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116259. };
  116260. return VideoDome;
  116261. }(BABYLON.TransformNode));
  116262. BABYLON.VideoDome = VideoDome;
  116263. })(BABYLON || (BABYLON = {}));
  116264. //# sourceMappingURL=babylon.videoDome.js.map
  116265. var BABYLON;
  116266. (function (BABYLON) {
  116267. /**
  116268. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  116269. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  116270. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  116271. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  116272. */
  116273. var PhotoDome = /** @class */ (function (_super) {
  116274. __extends(PhotoDome, _super);
  116275. /**
  116276. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  116277. * @param name Element's name, child elements will append suffixes for their own names.
  116278. * @param urlsOfPhoto defines the url of the photo to display
  116279. * @param options defines an object containing optional or exposed sub element properties
  116280. * @param onError defines a callback called when an error occured while loading the texture
  116281. */
  116282. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  116283. if (onError === void 0) { onError = null; }
  116284. var _this = _super.call(this, name, scene) || this;
  116285. _this._useDirectMapping = false;
  116286. /**
  116287. * Observable raised when an error occured while loading the 360 image
  116288. */
  116289. _this.onLoadErrorObservable = new BABYLON.Observable();
  116290. // set defaults and manage values
  116291. name = name || "photoDome";
  116292. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  116293. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  116294. if (options.useDirectMapping === undefined) {
  116295. _this._useDirectMapping = true;
  116296. }
  116297. else {
  116298. _this._useDirectMapping = options.useDirectMapping;
  116299. }
  116300. _this._setReady(false);
  116301. // create
  116302. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  116303. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  116304. // configure material
  116305. material.opacityFresnel = false;
  116306. material.useEquirectangularFOV = true;
  116307. material.fovMultiplier = 1.0;
  116308. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  116309. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  116310. if (onError) {
  116311. onError(message, exception);
  116312. }
  116313. });
  116314. _this.photoTexture.onLoadObservable.addOnce(function () {
  116315. _this._setReady(true);
  116316. });
  116317. // configure mesh
  116318. _this._mesh.material = material;
  116319. _this._mesh.parent = _this;
  116320. return _this;
  116321. }
  116322. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  116323. /**
  116324. * Gets or sets the texture being displayed on the sphere
  116325. */
  116326. get: function () {
  116327. return this._photoTexture;
  116328. },
  116329. set: function (value) {
  116330. if (this._photoTexture === value) {
  116331. return;
  116332. }
  116333. this._photoTexture = value;
  116334. if (this._useDirectMapping) {
  116335. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116336. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116337. this._material.diffuseTexture = this._photoTexture;
  116338. }
  116339. else {
  116340. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116341. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116342. this._material.reflectionTexture = this._photoTexture;
  116343. }
  116344. },
  116345. enumerable: true,
  116346. configurable: true
  116347. });
  116348. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  116349. /**
  116350. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116351. * Also see the options.resolution property.
  116352. */
  116353. get: function () {
  116354. return this._material.fovMultiplier;
  116355. },
  116356. set: function (value) {
  116357. this._material.fovMultiplier = value;
  116358. },
  116359. enumerable: true,
  116360. configurable: true
  116361. });
  116362. /**
  116363. * Releases resources associated with this node.
  116364. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116365. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116366. */
  116367. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116368. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116369. this._photoTexture.dispose();
  116370. this._mesh.dispose();
  116371. this._material.dispose();
  116372. this.onLoadErrorObservable.clear();
  116373. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116374. };
  116375. return PhotoDome;
  116376. }(BABYLON.TransformNode));
  116377. BABYLON.PhotoDome = PhotoDome;
  116378. })(BABYLON || (BABYLON = {}));
  116379. //# sourceMappingURL=babylon.photoDome.js.map
  116380. var BABYLON;
  116381. (function (BABYLON) {
  116382. /** @hidden */
  116383. var _OcclusionDataStorage = /** @class */ (function () {
  116384. function _OcclusionDataStorage() {
  116385. /** @hidden */
  116386. this.occlusionInternalRetryCounter = 0;
  116387. /** @hidden */
  116388. this.isOcclusionQueryInProgress = false;
  116389. /** @hidden */
  116390. this.isOccluded = false;
  116391. /** @hidden */
  116392. this.occlusionRetryCount = -1;
  116393. /** @hidden */
  116394. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  116395. /** @hidden */
  116396. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  116397. }
  116398. return _OcclusionDataStorage;
  116399. }());
  116400. BABYLON.Engine.prototype.createQuery = function () {
  116401. return this._gl.createQuery();
  116402. };
  116403. BABYLON.Engine.prototype.deleteQuery = function (query) {
  116404. this._gl.deleteQuery(query);
  116405. return this;
  116406. };
  116407. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  116408. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  116409. };
  116410. BABYLON.Engine.prototype.getQueryResult = function (query) {
  116411. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  116412. };
  116413. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  116414. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116415. this._gl.beginQuery(glAlgorithm, query);
  116416. return this;
  116417. };
  116418. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  116419. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116420. this._gl.endQuery(glAlgorithm);
  116421. return this;
  116422. };
  116423. BABYLON.Engine.prototype._createTimeQuery = function () {
  116424. var timerQuery = this.getCaps().timerQuery;
  116425. if (timerQuery.createQueryEXT) {
  116426. return timerQuery.createQueryEXT();
  116427. }
  116428. return this.createQuery();
  116429. };
  116430. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  116431. var timerQuery = this.getCaps().timerQuery;
  116432. if (timerQuery.deleteQueryEXT) {
  116433. timerQuery.deleteQueryEXT(query);
  116434. return;
  116435. }
  116436. this.deleteQuery(query);
  116437. };
  116438. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  116439. var timerQuery = this.getCaps().timerQuery;
  116440. if (timerQuery.getQueryObjectEXT) {
  116441. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  116442. }
  116443. return this.getQueryResult(query);
  116444. };
  116445. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  116446. var timerQuery = this.getCaps().timerQuery;
  116447. if (timerQuery.getQueryObjectEXT) {
  116448. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  116449. }
  116450. return this.isQueryResultAvailable(query);
  116451. };
  116452. BABYLON.Engine.prototype.startTimeQuery = function () {
  116453. var caps = this.getCaps();
  116454. var timerQuery = caps.timerQuery;
  116455. if (!timerQuery) {
  116456. return null;
  116457. }
  116458. var token = new BABYLON._TimeToken();
  116459. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116460. if (caps.canUseTimestampForTimerQuery) {
  116461. token._startTimeQuery = this._createTimeQuery();
  116462. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  116463. }
  116464. else {
  116465. if (this._currentNonTimestampToken) {
  116466. return this._currentNonTimestampToken;
  116467. }
  116468. token._timeElapsedQuery = this._createTimeQuery();
  116469. if (timerQuery.beginQueryEXT) {
  116470. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116471. }
  116472. else {
  116473. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116474. }
  116475. this._currentNonTimestampToken = token;
  116476. }
  116477. return token;
  116478. };
  116479. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  116480. var caps = this.getCaps();
  116481. var timerQuery = caps.timerQuery;
  116482. if (!timerQuery || !token) {
  116483. return -1;
  116484. }
  116485. if (caps.canUseTimestampForTimerQuery) {
  116486. if (!token._startTimeQuery) {
  116487. return -1;
  116488. }
  116489. if (!token._endTimeQuery) {
  116490. token._endTimeQuery = this._createTimeQuery();
  116491. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  116492. }
  116493. }
  116494. else if (!token._timeElapsedQueryEnded) {
  116495. if (!token._timeElapsedQuery) {
  116496. return -1;
  116497. }
  116498. if (timerQuery.endQueryEXT) {
  116499. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  116500. }
  116501. else {
  116502. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  116503. }
  116504. token._timeElapsedQueryEnded = true;
  116505. }
  116506. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116507. var available = false;
  116508. if (token._endTimeQuery) {
  116509. available = this._getTimeQueryAvailability(token._endTimeQuery);
  116510. }
  116511. else if (token._timeElapsedQuery) {
  116512. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  116513. }
  116514. if (available && !disjoint) {
  116515. var result = 0;
  116516. if (caps.canUseTimestampForTimerQuery) {
  116517. if (!token._startTimeQuery || !token._endTimeQuery) {
  116518. return -1;
  116519. }
  116520. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  116521. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  116522. result = timeEnd - timeStart;
  116523. this._deleteTimeQuery(token._startTimeQuery);
  116524. this._deleteTimeQuery(token._endTimeQuery);
  116525. token._startTimeQuery = null;
  116526. token._endTimeQuery = null;
  116527. }
  116528. else {
  116529. if (!token._timeElapsedQuery) {
  116530. return -1;
  116531. }
  116532. result = this._getTimeQueryResult(token._timeElapsedQuery);
  116533. this._deleteTimeQuery(token._timeElapsedQuery);
  116534. token._timeElapsedQuery = null;
  116535. token._timeElapsedQueryEnded = false;
  116536. this._currentNonTimestampToken = null;
  116537. }
  116538. return result;
  116539. }
  116540. return -1;
  116541. };
  116542. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  116543. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  116544. };
  116545. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  116546. get: function () {
  116547. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  116548. },
  116549. enumerable: false,
  116550. configurable: true
  116551. });
  116552. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  116553. get: function () {
  116554. if (!this.__occlusionDataStorage) {
  116555. this.__occlusionDataStorage = new _OcclusionDataStorage();
  116556. }
  116557. return this.__occlusionDataStorage;
  116558. },
  116559. enumerable: false,
  116560. configurable: true
  116561. });
  116562. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  116563. get: function () {
  116564. return this._occlusionDataStorage.isOccluded;
  116565. },
  116566. set: function (value) {
  116567. this._occlusionDataStorage.isOccluded = value;
  116568. },
  116569. enumerable: true,
  116570. configurable: true
  116571. });
  116572. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  116573. get: function () {
  116574. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  116575. },
  116576. set: function (value) {
  116577. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  116578. },
  116579. enumerable: true,
  116580. configurable: true
  116581. });
  116582. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  116583. get: function () {
  116584. return this._occlusionDataStorage.occlusionType;
  116585. },
  116586. set: function (value) {
  116587. this._occlusionDataStorage.occlusionType = value;
  116588. },
  116589. enumerable: true,
  116590. configurable: true
  116591. });
  116592. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  116593. get: function () {
  116594. return this._occlusionDataStorage.occlusionRetryCount;
  116595. },
  116596. set: function (value) {
  116597. this._occlusionDataStorage.occlusionRetryCount = value;
  116598. },
  116599. enumerable: true,
  116600. configurable: true
  116601. });
  116602. // We also need to update AbstractMesh as there is a portion of the code there
  116603. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  116604. var dataStorage = this._occlusionDataStorage;
  116605. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  116606. dataStorage.isOccluded = false;
  116607. return false;
  116608. }
  116609. var engine = this.getEngine();
  116610. if (engine.webGLVersion < 2) {
  116611. dataStorage.isOccluded = false;
  116612. return false;
  116613. }
  116614. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  116615. dataStorage.isOccluded = false;
  116616. return false;
  116617. }
  116618. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  116619. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  116620. if (isOcclusionQueryAvailable) {
  116621. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  116622. dataStorage.isOcclusionQueryInProgress = false;
  116623. dataStorage.occlusionInternalRetryCounter = 0;
  116624. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  116625. }
  116626. else {
  116627. dataStorage.occlusionInternalRetryCounter++;
  116628. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  116629. dataStorage.isOcclusionQueryInProgress = false;
  116630. dataStorage.occlusionInternalRetryCounter = 0;
  116631. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  116632. // if strict continue the last state of the object.
  116633. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  116634. }
  116635. else {
  116636. return false;
  116637. }
  116638. }
  116639. }
  116640. var scene = this.getScene();
  116641. if (scene.getBoundingBoxRenderer) {
  116642. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  116643. if (!this._occlusionQuery) {
  116644. this._occlusionQuery = engine.createQuery();
  116645. }
  116646. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  116647. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  116648. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  116649. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  116650. }
  116651. return dataStorage.isOccluded;
  116652. };
  116653. })(BABYLON || (BABYLON = {}));
  116654. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  116655. var BABYLON;
  116656. (function (BABYLON) {
  116657. /**
  116658. * Class used to generate noise procedural textures
  116659. */
  116660. var NoiseProceduralTexture = /** @class */ (function (_super) {
  116661. __extends(NoiseProceduralTexture, _super);
  116662. /**
  116663. * Creates a new NoiseProceduralTexture
  116664. * @param name defines the name fo the texture
  116665. * @param size defines the size of the texture (default is 256)
  116666. * @param scene defines the hosting scene
  116667. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  116668. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  116669. */
  116670. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  116671. if (size === void 0) { size = 256; }
  116672. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  116673. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  116674. _this._time = 0;
  116675. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  116676. _this.brightness = 0.2;
  116677. /** Defines the number of octaves to process */
  116678. _this.octaves = 3;
  116679. /** Defines the level of persistence (0.8 by default) */
  116680. _this.persistence = 0.8;
  116681. /** Gets or sets animation speed factor (default is 1) */
  116682. _this.animationSpeedFactor = 1;
  116683. _this._updateShaderUniforms();
  116684. return _this;
  116685. }
  116686. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  116687. var scene = this.getScene();
  116688. if (!scene) {
  116689. return;
  116690. }
  116691. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  116692. this.setFloat("brightness", this.brightness);
  116693. this.setFloat("persistence", this.persistence);
  116694. this.setFloat("timeScale", this._time);
  116695. };
  116696. NoiseProceduralTexture.prototype._getDefines = function () {
  116697. return "#define OCTAVES " + (this.octaves | 0);
  116698. };
  116699. /** Generate the current state of the procedural texture */
  116700. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  116701. this._updateShaderUniforms();
  116702. _super.prototype.render.call(this, useCameraPostProcess);
  116703. };
  116704. /**
  116705. * Serializes this noise procedural texture
  116706. * @returns a serialized noise procedural texture object
  116707. */
  116708. NoiseProceduralTexture.prototype.serialize = function () {
  116709. var serializationObject = {};
  116710. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  116711. serializationObject.brightness = this.brightness;
  116712. serializationObject.octaves = this.octaves;
  116713. serializationObject.persistence = this.persistence;
  116714. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  116715. serializationObject.size = this.getSize().width;
  116716. serializationObject.generateMipMaps = this._generateMipMaps;
  116717. return serializationObject;
  116718. };
  116719. /**
  116720. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  116721. * @param parsedTexture defines parsed texture data
  116722. * @param scene defines the current scene
  116723. * @param rootUrl defines the root URL containing noise procedural texture information
  116724. * @returns a parsed NoiseProceduralTexture
  116725. */
  116726. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  116727. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  116728. texture.brightness = parsedTexture.brightness;
  116729. texture.octaves = parsedTexture.octaves;
  116730. texture.persistence = parsedTexture.persistence;
  116731. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  116732. return texture;
  116733. };
  116734. return NoiseProceduralTexture;
  116735. }(BABYLON.ProceduralTexture));
  116736. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  116737. })(BABYLON || (BABYLON = {}));
  116738. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  116739. var __assign = (this && this.__assign) || function () {
  116740. __assign = Object.assign || function(t) {
  116741. for (var s, i = 1, n = arguments.length; i < n; i++) {
  116742. s = arguments[i];
  116743. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  116744. t[p] = s[p];
  116745. }
  116746. return t;
  116747. };
  116748. return __assign.apply(this, arguments);
  116749. };
  116750. var BABYLON;
  116751. (function (BABYLON) {
  116752. /**
  116753. * This can helps recording videos from BabylonJS.
  116754. * This is based on the available WebRTC functionalities of the browser.
  116755. *
  116756. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  116757. */
  116758. var VideoRecorder = /** @class */ (function () {
  116759. /**
  116760. * Create a new VideoCapture object which can help converting what you see in Babylon to
  116761. * a video file.
  116762. * @param engine Defines the BabylonJS Engine you wish to record
  116763. * @param options Defines options that can be used to customized the capture
  116764. */
  116765. function VideoRecorder(engine, options) {
  116766. if (options === void 0) { options = null; }
  116767. if (!VideoRecorder.IsSupported(engine)) {
  116768. throw "Your browser does not support recording so far.";
  116769. }
  116770. var canvas = engine.getRenderingCanvas();
  116771. if (!canvas) {
  116772. throw "The babylon engine must have a canvas to be recorded";
  116773. }
  116774. this._canvas = canvas;
  116775. this._canvas.isRecording = false;
  116776. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  116777. var stream = this._canvas.captureStream(this._options.fps);
  116778. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  116779. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  116780. this._mediaRecorder.onerror = this._handleError.bind(this);
  116781. this._mediaRecorder.onstop = this._handleStop.bind(this);
  116782. }
  116783. /**
  116784. * Returns wehther or not the VideoRecorder is available in your browser.
  116785. * @param engine Defines the Babylon Engine to check the support for
  116786. * @returns true if supported otherwise false
  116787. */
  116788. VideoRecorder.IsSupported = function (engine) {
  116789. var canvas = engine.getRenderingCanvas();
  116790. return (!!canvas && typeof canvas.captureStream === "function");
  116791. };
  116792. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  116793. /**
  116794. * True wether a recording is already in progress.
  116795. */
  116796. get: function () {
  116797. return !!this._canvas && this._canvas.isRecording;
  116798. },
  116799. enumerable: true,
  116800. configurable: true
  116801. });
  116802. /**
  116803. * Stops the current recording before the default capture timeout passed in the startRecording
  116804. * functions.
  116805. */
  116806. VideoRecorder.prototype.stopRecording = function () {
  116807. if (!this._canvas || !this._mediaRecorder) {
  116808. return;
  116809. }
  116810. if (!this.isRecording) {
  116811. return;
  116812. }
  116813. this._canvas.isRecording = false;
  116814. this._mediaRecorder.stop();
  116815. };
  116816. /**
  116817. * Starts recording the canvas for a max duration specified in parameters.
  116818. * @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.
  116819. * @param maxDuration Defines the maximum recording time in seconds.
  116820. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  116821. * @return a promise callback at the end of the recording with the video data in Blob.
  116822. */
  116823. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  116824. var _this = this;
  116825. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  116826. if (maxDuration === void 0) { maxDuration = 7; }
  116827. if (!this._canvas || !this._mediaRecorder) {
  116828. throw "Recorder has already been disposed";
  116829. }
  116830. if (this.isRecording) {
  116831. throw "Recording already in progress";
  116832. }
  116833. if (maxDuration > 0) {
  116834. setTimeout(function () {
  116835. _this.stopRecording();
  116836. }, maxDuration * 1000);
  116837. }
  116838. this._fileName = fileName;
  116839. this._recordedChunks = [];
  116840. this._resolve = null;
  116841. this._reject = null;
  116842. this._canvas.isRecording = true;
  116843. this._mediaRecorder.start(this._options.recordChunckSize);
  116844. return new Promise(function (resolve, reject) {
  116845. _this._resolve = resolve;
  116846. _this._reject = reject;
  116847. });
  116848. };
  116849. /**
  116850. * Releases internal resources used during the recording.
  116851. */
  116852. VideoRecorder.prototype.dispose = function () {
  116853. this._canvas = null;
  116854. this._mediaRecorder = null;
  116855. this._recordedChunks = [];
  116856. this._fileName = null;
  116857. this._resolve = null;
  116858. this._reject = null;
  116859. };
  116860. VideoRecorder.prototype._handleDataAvailable = function (event) {
  116861. if (event.data.size > 0) {
  116862. this._recordedChunks.push(event.data);
  116863. }
  116864. };
  116865. VideoRecorder.prototype._handleError = function (event) {
  116866. this.stopRecording();
  116867. if (this._reject) {
  116868. this._reject(event.error);
  116869. }
  116870. else {
  116871. throw new event.error();
  116872. }
  116873. };
  116874. VideoRecorder.prototype._handleStop = function () {
  116875. this.stopRecording();
  116876. var superBuffer = new Blob(this._recordedChunks);
  116877. if (this._resolve) {
  116878. this._resolve(superBuffer);
  116879. }
  116880. window.URL.createObjectURL(superBuffer);
  116881. if (this._fileName) {
  116882. BABYLON.Tools.Download(superBuffer, this._fileName);
  116883. }
  116884. };
  116885. VideoRecorder._defaultOptions = {
  116886. mimeType: "video/webm",
  116887. fps: 25,
  116888. recordChunckSize: 3000
  116889. };
  116890. return VideoRecorder;
  116891. }());
  116892. BABYLON.VideoRecorder = VideoRecorder;
  116893. })(BABYLON || (BABYLON = {}));
  116894. //# sourceMappingURL=babylon.videoRecorder.js.map
  116895. var BABYLON;
  116896. (function (BABYLON) {
  116897. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  116898. if (replace === void 0) { replace = false; }
  116899. // Dispose existing light in replace mode.
  116900. if (replace) {
  116901. if (this.lights) {
  116902. for (var i = 0; i < this.lights.length; i++) {
  116903. this.lights[i].dispose();
  116904. }
  116905. }
  116906. }
  116907. // Light
  116908. if (this.lights.length === 0) {
  116909. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  116910. }
  116911. };
  116912. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  116913. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116914. if (replace === void 0) { replace = false; }
  116915. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116916. // Dispose existing camera in replace mode.
  116917. if (replace) {
  116918. if (this.activeCamera) {
  116919. this.activeCamera.dispose();
  116920. this.activeCamera = null;
  116921. }
  116922. }
  116923. // Camera
  116924. if (!this.activeCamera) {
  116925. var worldExtends = this.getWorldExtends();
  116926. var worldSize = worldExtends.max.subtract(worldExtends.min);
  116927. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  116928. var camera;
  116929. var radius = worldSize.length() * 1.5;
  116930. // empty scene scenario!
  116931. if (!isFinite(radius)) {
  116932. radius = 1;
  116933. worldCenter.copyFromFloats(0, 0, 0);
  116934. }
  116935. if (createArcRotateCamera) {
  116936. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  116937. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  116938. arcRotateCamera.wheelPrecision = 100 / radius;
  116939. camera = arcRotateCamera;
  116940. }
  116941. else {
  116942. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  116943. freeCamera.setTarget(worldCenter);
  116944. camera = freeCamera;
  116945. }
  116946. camera.minZ = radius * 0.01;
  116947. camera.maxZ = radius * 1000;
  116948. camera.speed = radius * 0.2;
  116949. this.activeCamera = camera;
  116950. var canvas = this.getEngine().getRenderingCanvas();
  116951. if (attachCameraControls && canvas) {
  116952. camera.attachControl(canvas);
  116953. }
  116954. }
  116955. };
  116956. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  116957. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116958. if (replace === void 0) { replace = false; }
  116959. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116960. this.createDefaultLight(replace);
  116961. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  116962. };
  116963. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  116964. if (pbr === void 0) { pbr = false; }
  116965. if (scale === void 0) { scale = 1000; }
  116966. if (blur === void 0) { blur = 0; }
  116967. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  116968. if (!environmentTexture) {
  116969. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  116970. return null;
  116971. }
  116972. if (setGlobalEnvTexture) {
  116973. if (environmentTexture) {
  116974. this.environmentTexture = environmentTexture;
  116975. }
  116976. }
  116977. // Skybox
  116978. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  116979. if (pbr) {
  116980. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  116981. hdrSkyboxMaterial.backFaceCulling = false;
  116982. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  116983. if (hdrSkyboxMaterial.reflectionTexture) {
  116984. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  116985. }
  116986. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  116987. hdrSkyboxMaterial.disableLighting = true;
  116988. hdrSkyboxMaterial.twoSidedLighting = true;
  116989. hdrSkybox.infiniteDistance = true;
  116990. hdrSkybox.material = hdrSkyboxMaterial;
  116991. }
  116992. else {
  116993. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  116994. skyboxMaterial.backFaceCulling = false;
  116995. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  116996. if (skyboxMaterial.reflectionTexture) {
  116997. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  116998. }
  116999. skyboxMaterial.disableLighting = true;
  117000. hdrSkybox.infiniteDistance = true;
  117001. hdrSkybox.material = skyboxMaterial;
  117002. }
  117003. return hdrSkybox;
  117004. };
  117005. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  117006. if (BABYLON.EnvironmentHelper) {
  117007. return new BABYLON.EnvironmentHelper(options, this);
  117008. }
  117009. return null;
  117010. };
  117011. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  117012. if (webVROptions === void 0) { webVROptions = {}; }
  117013. return new BABYLON.VRExperienceHelper(this, webVROptions);
  117014. };
  117015. })(BABYLON || (BABYLON = {}));
  117016. //# sourceMappingURL=babylon.sceneHelpers.js.map
  117017. 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"};
  117018. 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};"};